1. A variable defined using a var statement is known throughout the function it is defined in, from the start of the function. (*)
2. A variable defined using a let statement is only known in the block it is defined in, from the moment it is defined onward. (**)
3. let variables are only visible in their nearest enclosing block ({ ... }).
4. let variables are only usable in lines of code that occur after the variable is declared (even though they are hoisted!).
5. let variables may not be redeclared by a subsequent var or let.
6. Global let variables are not added to the global window object.
7. let variables are easy to use with closures (they do not cause race conditions).
2. A variable defined using a let statement is only known in the block it is defined in, from the moment it is defined onward. (**)
3. let variables are only visible in their nearest enclosing block ({ ... }).
4. let variables are only usable in lines of code that occur after the variable is declared (even though they are hoisted!).
5. let variables may not be redeclared by a subsequent var or let.
6. Global let variables are not added to the global window object.
7. let variables are easy to use with closures (they do not cause race conditions).
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.Lets see an example
<script>
// let - for block-level variables
for(let i = 0; i < 3; i++) {
console.log(i); // 0 1 2
}
//console.log(i) // ReferenceError: i is not defined
for(var j = 0; j < 3; j++) {
console.log(j); // 0 1 2
}
console.log(j) // 3
</script>
Most Helpful This Week
jQuery get the coordinates of div clicked
jQuery simple form with name and email validations
Image Rollover Using onMouseOver and onMouseOut
How to declare multiple variables in one statement in Javascript?
jQuery example of scroll to top
Highlight and get the details of table row on click using JavaScript