Home  >  Article  >  Web Front-end  >  How Do Function Declarations and Expressions Affect Execution Order in JavaScript?

How Do Function Declarations and Expressions Affect Execution Order in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 18:35:47157browse

How Do Function Declarations and Expressions Affect Execution Order in JavaScript?

JavaScript Function Declaration and Evaluation Order

When working with JavaScript functions, it's crucial to understand the distinction between function declarations and expressions and their impact on the execution order. This can be illustrated by examining four examples:

// 1
(function() {
    setTimeout(someFunction1, 10);
    var someFunction1 = function() { alert('here1'); };
})();

// 2
(function() {
    setTimeout(someFunction2, 10);
    function someFunction2() { alert('here2'); }
})();

// 3
(function() {
    setTimeout(function() { someFunction3(); }, 10);
    var someFunction3 = function() { alert('here3'); };
})();

// 4
(function() {
    setTimeout(function() { someFunction4(); }, 10);
    function someFunction4() { alert('here4'); }
})();

The first example doesn't work because of the order of compilation and execution. In JavaScript, code is compiled in two phases: compilation and execution.

Phase 1: Compilation

During compilation, variables are created. In Example 1, the someFunction1 variable is declared after the setTimeout call. Therefore, when the compiler encounters someFunction1 in the setTimeout argument, it cannot find the variable.

Phase 2: Execution

During execution, the interpreter passes the value of someFunction1 to setTimeout. Since the someFunction1 variable is still undefined, the interpreter fails to execute the function.

In contrast, Examples 2, 3, and 4 all work because either the function declaration is defined before the setTimeout call (Example 2), or an anonymous function is passed to setTimeout (Example 3), or a reference to the declared function is used (Example 4).

Function Declarations vs Function Expressions

Understanding the difference between function declarations and expressions is key. Function declarations (as in Example 2) are parsed during compilation, while function expressions (as in Examples 1 and 3) are evaluated during execution. This difference can impact the access to variables and the order in which code is executed.

The above is the detailed content of How Do Function Declarations and Expressions Affect Execution Order in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn