Question: Explain the difference between function declarations and function expressions in JavaScript.
Answer:
Function declarations and expressions are two ways of creating functions in JavaScript.
Function Declaration:
function foo() { return 5; }
Anonymous Function Expression:
var foo = function() { return 5; }
Named Function Expression:
var foo = function foo() { return 5; }
Browser Differences:
Function declarations have always been loaded into the execution context before any code. Function expressions, however, used to cause some inconsistencies in browsers. Specifically, in earlier versions of Safari, the following function expression would throw an error:
var foo = function foo() { return 5; }
This issue has since been resolved, and all major browsers now treat function expressions consistently.
Additional Clarification:
Function expressions are loaded lazily, meaning they are only loaded when the interpreter reaches the line of code where they are created. This can lead to issues if you attempt to call a function expression before it has loaded. Function declarations, on the other hand, are always accessible because they are loaded before any code execution.
The above is the detailed content of What's the Difference Between Function Declarations and Expressions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!