3

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){
                 return n * n;
             };

and

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

If yes, what are the advantages/disadvantages of using either of them?

Thanks for your help!

2

3 Answers 3

3

Check this out:

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the simple explanation!
3

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.

2 Comments

I agree with the first sentence but if they both do the exact same thing, how can one be different from the other?
You can do the same with a function declaration (passing and assigning).
0

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 =).

2 Comments

Hi Clement, to be honest, I don't understand what the last line does. Could you kindly explain me the purpose of return nnn; when I want to calculate the square?
Your example is a function that return the square value of a number, but that could be any other function, that does complicated, or really context-dependent work. Returning n*n*n for a square method is silly, but it is just for the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.