JavaScript differences defining a function

I just bought the latest version of "JavaScript: The Ultimate Guide" and already asked a question .: D

Are the following lines semantically the same:

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

and

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

If so, what are the advantages / disadvantages of using any of them?

Thank you for your help!

+3
source share
3 answers

Check this:

a(); // prints 'A'

function a(){

    console.log('A');

};

and this:

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

var b = function() {

    console.log('B');

};

Did you notice the difference?

+3
source

Yes, they do the same.

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

+3
source

, :

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

// some code

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

you have a link for the function. On another solution, the function is statically declared.

Disclaimer: I need the JS guru to tell me if I am wrong =).

0
source

All Articles