Wednesday, 16 November 2016

Javascript: What is the difference between function foo(){...} and var foo = function(){...}

()This has been puzzling me for a long time.
function bar(){
    console.log("bar");
}

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

bar();
foo();

What's the difference between these two formats?

I always use the first format to declare a function and deem the second format as an advanced, fancy one.

Now I learnt that the 'fancy' format is actually the less preferred way to declare the function because the function must be called after its declaration while in first format the function can be called anywhere.


bar(); //Print 'bar'
foo(); //TypeError

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

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

It turns out Javascript compiler moves all the declaration (e.g. var a) to the top and leaves the assignment (a = 2) where it is.  (By the way, I wasn't aware Javascript has a compiler until today)

So the above code is interpreted by the compiler as

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

var foo;

bar(); //Print 'bar'
foo(); //TypeError

foo = function (){
    console.log("foo");
}

function bar() is moved to top as a whole but function foo is separated into var foo and foo = ...

Another point worth mentioning is that function declaration (in first format) overrides the same function name.


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

bar(); //Print 'foo'

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




No comments:

Post a Comment