Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with let keyword

Tags:

javascript

I was playing with some code and ran into a situation where I couldn't identify why 'let' is behaving the way it does.

For the below block of code:

var x = 20; // global scope

function f() {
  let x = x || 30;
}

f(); // VM3426:1 Uncaught ReferenceError: x is not defined(…)

I get the error 'x is not defined' on executing f(). I do understand 'let' variables are not hoisted but since 'x' has a global copy, why isn't the line inside function 'f' defaulting to global copy instead of throwing an error? Does 'let' set the variable to undeclared (instead of 'undefined' with var because of hoisting) at the beginning of the function? Is there any way to get the global copy of 'x' within the function?

like image 583
Adarsh Konchady Avatar asked Nov 10 '16 09:11

Adarsh Konchady


People also ask

Why is var better than let?

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.

Why we use let keyword?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Should I use let or VAR in JavaScript?

As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.


1 Answers

The exception is about the right side x - when you are initializing block-scope x variable the global one is already "forgotten" however the new one is still not being declared and cannot be used during initialization

Compare with explicit calling global one

    function f() {
      let x = window.x || 30;
    }

Also take a look at this MDN article about let dead zones

like image 79
m.antkowicz Avatar answered Sep 30 '22 06:09

m.antkowicz