Home >Web Front-end >JS Tutorial >Why Does This JavaScript Code Fail, Even Though Similar Examples Work?
JavaScript Function Declaration and Evaluation Order
Background:
In JavaScript, functions can be declared or created using expressions. Function declarations occur during the compilation phase, while function expressions are evaluated during the execution phase. Understanding this distinction is crucial for comprehending the behavior of JavaScript code.
The Question:
Why does the first example in the following code block fail, while the remaining examples execute successfully?
<code class="javascript">// 1 - does not work (function() { setTimeout(someFunction1, 10); var someFunction1 = function() { alert('here1'); }; })(); // ... other examples</code>
The Answer:
The failure of the first example is not due to a scope or closure issue but rather a misunderstanding between declarations and expressions.
Function Declarations vs. Expressions:
Phase 1: Compilation
During compilation, the compiler processes function declarations, creating variables for the functions. In the first example, the variable someFunction1 is created but remains undefined because its value (the function body) is evaluated later.
Phase 2: Execution
Example 1:
At runtime, the interpreter encounters setTimeout(someFunction1, 10) and attempts to pass an undefined someFunction1 to setTimeout.
Example 2:
In contrast, function someFunction2() is a declaration, creating the function during compilation. When setTimeout is called, it receives the compiled function reference.
Example 3:
Here, an anonymous function is passed to setTimeout, which creates a closure to the variable someFunction3. When setTimeout triggers, someFunction3 has been assigned a value, and the function executes successfully.
Example 4:
Similar to Example 2, the function someFunction4 is declared, making its reference available to setTimeout.
Additional Clarification:
The above is the detailed content of Why Does This JavaScript Code Fail, Even Though Similar Examples Work?. For more information, please follow other related articles on the PHP Chinese website!