简体   繁体   中英

Javascript and Hoisting

In my code, the x value is undefined. If I remove if block, the x value is displayed as 77. I don't understand why if block is modifying the x value.

 var x = 77; function fn() { if (false) { var x = 55; } console.log(x); } fn();

 var x = 77; function fn() { if (false) { var x = 55; } console.log(x); // undefind } fn();

In the intermediate phase, x will be hoisted to its scope:

    var x = 77;
    function fn() {
    //var x = undefind; intermediate phase
      if (false) {
        var x = 55;
      }
      console.log(x);
    }

    fn();

 var x = 77; function fn() { if (false) { x = 55; } console.log(x); // 77 } fn();

The x variable is redeclared and hoisted inside the function, but never set because if (false) will never be reached thus undefined . The outer x is known inside the function if you remove the inner declaration.

This can be solved by using const or let (ES6) instead of var . const and let is not hoisted and lives only inside of the brackets they are declared:

const x = 77;

function fn() {
  if (false) {
    const x = 55;
  }
  console.log(x);  // 77
}
fn()

Another solution is to just use two different variable names or remove the var inside the if statement depending on your needs...

Simply remove the var inside the if-statement. That will fix the hoisting issue.

var x = 77;

function fn() {
    if(false) {
        x = 55;
    }
    console.log(x); // 77
}

fn();

Inside the scope of the function, the variable x is hoisted to the top as follows var x; If you print it, you get undefined . It is never assigned a variable as it is not going inside the if block

You can also use let keyword.

let x = 77;

function fn() {
  if (false) {
    let x = 55;
  }
  console.log(x); // 77
}

fn()

one should use wither ES6 define syntax const OR let while assigning the variable, if needs to mutate the variable then use let, otherwise use const, stop using var. In your scenario while using var there, it means you are trying to re initialize the x, it gets hoisted var x = 77; means var x; outside the block. So one should not need to re initialize the x just pass the value or either use let or const.

function fn() {
  if (false) {
  // 
    x = 55;
  }
  console.log(x);
}

fn();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM