Please let me know what is the difference between var and let in JavaScript?
How should I know whether to use let or var when coding?
I know that let is used with ECMAScript6 - it is not showing (or trowing an error) in the older versions of JavaScript).
When shall I use var and when let in my code?
The main difference between var and let is pretty simple:
let has a "block scope"
e
var has a "function scope"
Here are some examples:
Example 1 - using let:
for (let x=1; x<=5; x++)
console.log(x); // 1 … 5
console.log(x); // Ref. error
function test() {
console.log(x); // Ref. error
let x = 5;
}
test();
Example 1 - using var (the same code but with var instead of let):
for (var x=1; x<=5; x++)
console.log(x); // 1 … 5
console.log(x); // 6
function test() {
console.log(x); // undefined
var x = 5;
}
test();
Example 2 - using let:
let x = 100; // block scope
console.log(x); // 100
for (let x=1; x<=5; x++) {
console.log(x); // 1 … 5
} // end of block scope
console.log(x); // 100
console.log(x); // Ref. error
let x;
Example 2 - using var(the same code but with var instead of let):
var x = 100; // function scope
console.log(x); // 100
for (var x=1; x<=5; x++) {
console.log(x); // 1 … 5
} // same x inside the loop
console.log(x); // 6
console.log(x); // undefined
var x;
Here is short video explaining the difference between var, let and const in JavaScript:
- If you need a constant, use const.
- If you want to limit the scope of a variable to just one code block, use let.
- If you need a general global or local variable, use var.
And if you're ever in doubt experiment and see which one of the 3 will give you the result you want. Cheers
