Function Expression vs Function declaration

Asked

Viewed 341 times

7

What is the definition for Function Expression and Function declaration? What are the main advantages of one in relation to the other?

  • See if it can help you here. http://www.w3schools.com/js/js_function_definition.asp

  • Behold this if it no longer covers your question.

  • @Fernando truth... I looked but didn’t find, I also thought I’d been asked.

  • @Sergio, yes the research here in the OS is not the best (they should invest in it), hehe, is that I’ve done this question duplicate of this cited.

  • I also searched here and did not find. I believe that from now on the answer to this doubt will be found more easily.

1 answer

5


They look so much alike.
The main difference is whether they are available in the whole execution context or not.

A function declared by Function Expression will not be accessible on lines of code prior to the current execution line. Only available on run-time, the moment 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 on previous lines.

Both respect rules of scope.

Function Declaration

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

functions because the function is present throughout the execution context

Function Expression

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

This is gonna be a mistake.
foo(); can only be run after the line where the variable becomes a function.

Note 1:

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

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

It will be a mistake. Namely:

Typeerror: foo is not a Function

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

but notice that this error does not occur:

Uncaught Referenceerror: foo is not defined

which would be the case if foo had not yet been declared.

Note 2:

If we use for example the following Function Declaration on-mode "use strict" functions in conditional parts of the code will fail. That is, it cannot 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 to use. However there are cases where the Function Expression is very useful and does something that the Function Declaration does not allow to do.Example:

var id = document.geElementById;

ie we are assigning a function to a variable. This saves space in future code and would not be possible via Function Declaration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.