settingsAccountsettings
Menusettings

Q: What is the main difference between var and let in JavaScript?

+7 votes
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?
asked in JavaScript category by user nikole

3 Answers

+6 votes

The main difference between var and let is pretty simple:

let has a "block scope"

and

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;

 

answered by user paulcabalit
+5 votes
  • 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

answered by user richard8502
edited by user richard8502
+4 votes
Here is short video explaining the difference between var, let and const in JavaScript:

answered by user sam
...