0

I am having doubt in following code how const is working. below code runs without error and showing Z is 8 . what my expectation is it should throw refrence error z is already defined . Can anyone explain this

(function() {
  {
    const z = 4;

    if (true) {
      const z = 8;
      console.log("Z is " + z);
    }
  }
})()
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • const variables may be declared and initialized in a new lexical environment, i.e. in a new block. – Andrew Li Mar 03 '20 at 13:21
  • `const` and `let` are not hoisted. In addition, here you're shadowing the outer `z`. Hence, it logs `8`. – Aadit M Shah Mar 03 '20 at 13:22
  • 2
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) or [const keyword scope in Javascript](https://stackoverflow.com/q/12272836/215552) or [Are variables declared with let or const not hoisted in ES6?](https://stackoverflow.com/q/31219420/215552) – Heretic Monkey Mar 03 '20 at 13:24

1 Answers1

3

This has nothing to do with hoisting.

const (and let) are scoped to the block, not the function (var is scoped to the function).

The if block is a new scope so can have a new const with the same name (masking the one outside the if).

(function() {
  {
    const z = 4;

    if (true) {
      const z = 8;
      console.log("Z inside the IF block is " + z);
    }

    console.log("Z outside the IF block is " + z);
  }
})()
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335