Home > Web Front-end > JS Tutorial > How Does JavaScript Function Hoisting and Scoping Affect Variable Overwriting?

How Does JavaScript Function Hoisting and Scoping Affect Variable Overwriting?

Mary-Kate Olsen
Release: 2024-12-24 03:02:13
Original
768 people have browsed it

How Does JavaScript Function Hoisting and Scoping Affect Variable Overwriting?

Javascript Function Scoping and Hoisting: A Deeper Dive

Ben Cherry's article on Javascript Scoping and Hoisting introduces the concepts of function hoisting and variable scoping. To better understand their impact, let's delve into an intriguing example he provides:

var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}

b();
alert(a);
Copy after login

Run this code, and you'll find that it alerts "1," which may seem puzzling.

Function hoisting is a crucial concept هنا، elevating function declarations to the start of their scope. This means that the code above is effectively rewritten as:

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

Oddly enough, the function within the function, a(), functions similarly to a variable declaration (var a = function () {};). Consider this:

var a = 1;

function b() {
  var a = function () {};
  a = 10;
  return;
}

b();
alert(a);
Copy after login

Both versions yield the exact same result.

Essentially, the code does this:

var a = 1;                 // Defines "a" in the global scope
function b() {  
   var a = function () {}; // Defines "a" in the local scope 
   a = 10;                 // Overwrites the local variable "a"
   return;      
}       
b();       
alert(a);                 // Alerts the global variable "a"
Copy after login

The key takeaway is that function hoisting and variable scoping interact to produce this behavior. The inner function creates a local variable a, while the function declaration itself elevates the function to the top. This ultimately leads to the globally defined a being unaffected by changes within the function.

The above is the detailed content of How Does JavaScript Function Hoisting and Scoping Affect Variable Overwriting?. 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