Anyone familiar with javascript will know function objects are one of the most important parts, if not the most important reference type. Hence it comes with great confusion when they learn that functions can be expressed in various ways. From object elements to stand-alone variables, functions are usually flexible and can be appended to unlimited scenarios.

There are two main ways, however, in which we write javascript functions. There is the function declaration:

function myFunction(argument){

return argument;

}

And there is the function expression:

var myFunction = function(argument){

return argument;

}

The question on which style is preferred relies solely on preference of the user. Generally, both ways are acceptable and mostly interchangeable. Majority of people tend to use both without a preferred standard. Chances are when using one, the other can be substituted with no observable differences. There is however a minor but very crucial difference between the two. Consider a function that takes two arguments and returns their product. Below are both methods that can be used to call the function:

FUNCTION EXPRESSION:

var iMultiply = function(x , y){

return x * y;

}



FUNCTION DECLARATION:

function iMultiply(x , y){

return x * y;

}

Let’s call a variable product that passes the arguments 10 and 20 in the iMultiply function. To point out the difference, let’s call product before we define our iMultiply function

FUNCTION EXPRESSION:

var product = iMultiply(10,20);

var iMultiply = function(x , y){

return x * y;

}



FUNCTION DECLARATION:

var product = iMultiply(10,20);

function iMultiply(x , y){

return x * y;

}

In the first instance (i.e. function expression), an error will be returned. In the function declaration example, our code will still work. While javascript usually executes code on a line by line basis, functions are handled slightly differently. Before the code starts to execute, functions are usually pulled to the execution context, a process called function declaration hoisting. Function declarations make the respective functions available for execution regardless of their position. Function expression, on the other hand, limits the scope of the function until the line has been executed. This means the function is useless when called before function has been declared.

Aside from this ‘small’ difference, function declarations and function expressions are pretty much identical and can be interchanged.