Last Updated: September 09, 2019
·
10.98K
· steveniseki

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"; } 

more info on JavaScript concepts

1 Response
Add your 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
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside