简体   繁体   中英

JavaScript let and var usage

A while ago, I read some article about using let and var in JavaScript and they're saying that a variable you declare using "var" keyword (even in for loop) works only within it's function, so why is it possible to make multiple for loops in one function, each of them look like : for (var i = 0; i < array.length; i++); and JavaScript has no problem with "redeclaring" the i variable? Thanks :)

JS has a special case for var as it allows hoisting , which means multiple declaration of the same variables is allowed and they got moved to the enclosing functional scope. However they are still the same variable. Consider the following code:

function foo(){
 for(var i=0; i<3; i++){
  console.log("x");
 }
 for(var i;i<6;i++){
  console.log("y");
 }
}

foo()

Notice there is no initialization of i in the second loop, but it will execute fine and produce 3 x and 3 y . It used to be a problem with old browsers, but new browser simply allows it with no error given.

A seemingly small question with a complex answer. var is the old method declaration. You can declare it anywhere and as many times as you want. JavaScript will not care. All declared variables are available immediately, because declaration gets moved up to the very beginning of the function's code. This is known as hoisting.

let is the new way of declaring variables. const exists, but we're not interested in that right now. let is block scoped. The rules behind let and scoping can be confusing, but it's advantageous to learn/understand. It is the future of JavaScript. I thoroughly talk about it in my blog post, here .

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.

var is rather a keyword which defines a variable globally regardless of block scope.

ES6 introduced the 'let' keyword to tackle this issue only. It allows a variable to be bound to its scope within a function so that you cannot re-declare it outside preventing hoisting issues. Example -

for(var i=0; i<5; i++) {
    console.log(i);
}
console.log(i);

Here the output will be - 0 1 2 3 4 5 Instead of 5 we must get 'Uncaught Reference Error' since variable i should be accessible only within the function. Because of Hoisting in JavaScript, all the variables and function names are stored to one place before execution. So the code actually looks like the following -

var i;
for(i=0; i<5; i++) {
        console.log(i);
}
console.log(i);

This is resolved if you use the let keyword.

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