JavaScript function expression vs function statement
function expressions and function statements are very similar in JavaScript, the difference is how the browser loads them into the execution context.
// function statement
function foo() {
}
// function expression
var foo = function() {
};
<b>function statements</b>
A function statement loads before any code is executed. This behavior of function statements is called hoisting, which allows a function to be used before it is defined.
alert(foo()); // Alerts "hello from foo".
function foo() { return "hello from foo"; }
<b>function expressions</b>
A function expression associates a value with a variable, just like any other assignment statement. function expressions load only when the interpreter reaches the definition of the function.
alert(foo()); // ERROR!
var foo = function() { return "hello from foo"; }
Written by Steven Iseki
Related protips
1 Response
Such a subtle code but huge difference between how they behave. :)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#