Function expression vs function declaration [duplicate]

7

What is the definition for function expression and function declaration ? What are the main advantages of one against another?

    
asked by anonymous 14.05.2015 / 16:28

1 answer

5

They are very similar. The main difference is whether they are available in any execution context or not.

A function declared by Function Expression will not be accessible in lines of code prior to the current execution line. It is only available in run-time , by the time the line is run by the code.

While a function declared by Function Declaration is always available, this is called Hoisting , available in parse-time , even in the previous lines.

Both respect scoping rules.

Function Declaration

alert(foo());
function foo() { return 5; } 

works because the function is present in the entire execution context

Function Expression

alert(foo());
var foo = function() { return 5; } 

This will give error. foo(); can only be run after the line than where the variable becomes a function.

Note 1:

In Expression the variable is already started / declared (with value undefined ) but its (function) value will only be assigned after the code passes through this line in execution. In the above example:

alert(foo());
var foo = function() { return 5; } 

It will give error. In particular:

  

TypeError: foo is not a function

(in some browsers gives undefined is not a function instead of variable name)

But notice that it does not give this error:

  

Uncaught ReferenceError: foo is not defined

that would be the case if foo was not yet declared.

Note 2:

If we use for example the following Function Declaration in mode "use strict" functions defined in conditional parts of the code will give error. In other words, it can not be used. Example:

"use strict";
if (bar) {
    function foo() { return 5; }; // dá erro!
}

Note 3:

In most cases it does not make much difference which one to use. But there are cases where Function Expression is very useful and does something that Function Declaration does not allow. Example:

var id = document.geElementById;

In other words, we are assigning a function to a variable. This saves space on future code and would not be possible via Function Declaration .

    
14.05.2015 / 18:12