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
How to change text after click event using JavaScript?
Using jQuery delete table row on click
Write a function that splits an array into groups the length of size and returns them as a two-dimensional array
JavaScript HTML5 Validation for name and email field
jQuery get the coordinates of div clicked
jQuery simple form with name and email validations