Home > Web Front-end > JS Tutorial > Why Does This JavaScript Code Alert '1' Instead of '10'?

Why Does This JavaScript Code Alert '1' Instead of '10'?

Susan Sarandon
Release: 2024-12-22 04:57:09
Original
226 people have browsed it

Why Does This JavaScript Code Alert

Understanding JavaScript Hoisting and Scoping through an Intriguing Example

In a recent article, Ben Cherry sheds light on JavaScript's intriguing concepts of hoisting and scoping. To illustrate, he presents the following code:

var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}
b();
alert(a);
Copy after login

Expectation vs. Reality

Intuitively, one might expect the alert to display "10" because the function a is declared within b. However, the browser displays "1" instead.

Delving into Hoisting and Scoping

Hoisting is a phenomenon where functions are moved to the top of their scope. This means that the following code gets rewritten by the interpreter:

function b() {
  a = 10;
  return;
  function a() {}
}
Copy after login

Interestingly, JavaScript also allows for variable declaration within functions using the syntax function a() {}. This is equivalent to var a = function () {};.

Understanding the Execution Sequence

The code essentially functions as follows:

  • a is defined in the global scope with the value 1.
  • The function b is declared and hoisted.
  • Inside b, a variable a is declared in the local scope using function a() {} (equivalent to var a = function () {};). This creates a separate instance of a.
  • a is then overwritten in the local scope with the value 10.
  • b returns, and the local instance of a goes out of scope.
  • alert(a) accesses the global variable a, which still holds the value 1.

Therefore, the alert displays "1" instead of "10" as the global variable a is unaffected by the changes made to the local variable a within the function.

The above is the detailed content of Why Does This JavaScript Code Alert '1' Instead of '10'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template