In JavaScript, functions can be defined using either expressions or declarations. While both approaches allow you to create reusable code blocks, they have some fundamental differences in how they behave in the execution context.
A function expression is an anonymous function that is assigned as a value to a variable or constant. It follows the syntax:
var foo = function() { return 5; };
In this example, foo is an anonymous function (lacking a formal name) that returns the value 5 when invoked.
Conversely, a function declaration is a named function declared using the function keyword followed by a name and optional parameters:
function foo() { return 5; }
In this case, foo is a named function that performs the same task as the anonymous function expression above.
The key difference between expressions and declarations lies in how they are loaded into the execution context.
// Function Expression alert(foo()); // ERROR! var foo = function() { return 5; };
In this example, alert(foo()) will throw an error because foo is not yet defined.
// Function Declaration alert(foo()); // Alerts 5 function foo() { return 5; }
Here, alert(foo()) alerts 5 because function declarations are loaded before any code runs.
While function expressions and declarations behave similarly in most cases, there are some nuances to be aware of:
The above is the detailed content of What's the Key Difference Between JavaScript Function Declarations and Expressions?. For more information, please follow other related articles on the PHP Chinese website!