JavaScript – Benefits of Declaring JS Functions in Two Ways

javascript

I've come across JS code in which I see functions being declared in two different styles:

Method 1

function doSomething(){

   alert('This is one way of declaring a function');

}

Method 2

doSomething = function() {

    alert('And this is another way of declaring the same function');    

}

So what is the difference between the two and is there a case scenario where it would make sense to follow one method over the other?

PS: Sorry if the title seems vague. I didn't know the technical term used to describe the way the above two functions are declared.

Best Answer

Method 1

For Method 1, the function and its symbol is processed by the parser before any code in this file is run. Thus the definition is "hoisted" to the top of whatever scope it is in and the symbol can be used anywhere in the scope it is defined in. Order of declaration within a scope does not matter.

So, with the first method, you can do this:

hello();

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

because the first pass over the code to parse it will define the symbol hello to be your function. Therefore, in the second pass when the code is actually executed, the symbol hello already exists so it can be called at any time.

Method 2

For Method 2, the function is processed by the parser, but the symbol that contains the function is not assigned a value until the assignment statement is executed at run-time. Code in this scope before this line cannot use the symbol (because it doesn't yet have a value). Order of assignment within a scope does matter and does have to be paid attention to.

Using, your second method, the same ordering as in the example above will not work:

hello();

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

because the symbol hello is not yet defined when you try to use it. Instead, you would have to do this:

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

hello();

Summary

People seem to have a preference for one style vs. the other. Personally, I like the first style as it just seems simpler to let the parser define all your function symbols and not have to worry about declaration order. The one exception I make is if I'm actually assigning different functions to a given variable depending upon some condition. Then, I may use the second style.

Related Topic