Last Updated: September 09, 2019
·
4.593K
· originell

The difference between JavaScript function declarations

Most of you know that there are these two ways to declare a function in javascript:

function foo() {
    console.log('bar');
}

var foo = function() {
    console.log('bar');
}

I never knew that there is a big difference between these two which can affect your code architecture. Let's look at an example with the first declaration method:

foo();
function foo() {
    console.log('bar');
}

This will output bar, even though the function is defined after the initial call. Well, this is expected behavior. Define a function anywhere and you will be able to call it from where ever you want. However doing the same with the second approach:

foo();
var foo = function() {
    console.log('bar');
}

Will result in a nice exception: Uncaught TypeError: undefined is not a function.

While this might not be big news for most of you, it certainly was quite a welcome surprise for me today!

6 Responses
Add your response

I think I found this a few days back too. Since then I’ve decided to use only the first method bcs it’s more useful :)

over 1 year ago ·

I guess the interpreter load all anon functions at start and put it on global. Functions with pointer (= assignment) is lazily loaded.

over 1 year ago ·

There are actually a couple of other ways to define a function in javascript.

This is identical to your second example (eg, you cannot call it until after it has been defined in the code.) I am just including it here for the sake of completeness:

var foo = function foo() {
    console.log('bar');
}

This version is the same as the above, however, the function name is different from the variable name. The important thing to note about this declaration (and the above) is that the function name only works from within the function. If there is another function named "bar" elsewhere in the code, it will not be overridden.

var foo = function bar() {
    console.log('bar');
}

This syntax will execute the function immediately, though since it is anonymous you cannot reuse this function later in your code:

(function() {
    console.log('bar');
)();

There is a lot of great information on this topic here: http://kangax.github.io/nfe/

over 1 year ago ·

Thanks @jontas! Didn't know about the second method with different "variable" and "function" names.

For the self-invocation, there is also

!function() {
    console.log.bar();
}()

and the same without the exclamation mark but with a + instead (have a look at the latest twitter boostrap javascripts - always a good inspiration source)

over 1 year ago ·

These are two different things: function declarations and function expressions.
See, for example, http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

over 1 year ago ·

Thanks @dpashkevich! :)

over 1 year ago ·