Comparing different ways of declaring javascript functions

aaron's profile image
By aaron

In #javascript, there are different ways to declare functions.

You can do this:

function foo(){
return "Bar";
}

Or you can do this:

var foo = function(){
return "Bar";
}

So what's the difference?

The first type is a function declaration, while the second is a function expression. The key difference is that a function declaration is hoisted, so it is immediately available when the surrounding script is executed. In contrast, a function expression only becomes available when that line of code is executed. If you try to execute the function before declaring it, it is undefined. So this won't work:

foo(); // Fail
var foo = function(){
return "Bar";
}

When foo() is called, it is not declared yet, so this fails. #webdev

Support the author

This author accepts donations via the services listed below. Your donation will help them continue to create great content!

* Lernabit doesn't take any of the money from your donation, but the donation services or payment processors might take a fee. These trademarks are the property of their respective owners.

Replies

Login or signup to leave a reply.

Signup Login
No more replies to show here