Skip to content Skip to sidebar Skip to footer

Javascript Differences Defining A Function

I just bought the newest version of 'JavaScript: The Definitive Guide' and already have a question. :D Are the following lines semantically the same: var square = function(n){

Solution 1:

Check this out:

a(); // prints 'A'functiona(){

    console.log('A');

};

and this:

b(); // throws error. b is not a functionvar b = function() {

    console.log('B');

};

Did you notice the difference?

Solution 2:

Yes, they do the exact same thing.

The main advantage of the first approach is that it gives you a reference to that function so that you could pass it to another function or attach it to an object if you need to.

Solution 3:

Difference is that in the first solution, you can do that :

var square = function(n){
                 return n * n;
             };

// some code

square = function(n) { return n*n*n; }

you have reference to a function. On the other solution, the function is statically declared.

Disclaimer: need JS guru to tell me if I'm wrong =).

Post a Comment for "Javascript Differences Defining A Function"