The Difference Between var and let in JavaScript

In the ES2015 update, JavaScript released two new keywords for defining variables and constants; let and const. Previously there were only two types of scope available in JavaScript, the global and local scope and with this update, a block scope was introduced, which is an extension of the local scope.

 

In this tutorial, we will explore the difference between let and var and when to use one or the other.

 

The JavaScript Block Scope

A variable defined using let will only be available inside a block whereas var would be available outside it. Blocks in JavaScript are written using {} (curly brackets) and used to contain groups of statements. Let's define two variables in a block, one with let and one with var and see what they are outside of it using typeof().

 

{
  let x = 1;
  var y = 2;

  console.log(typeof(x));
  console.log(typeof(y));
}

console.log(typeof(x));
console.log(typeof(y));
number
number
undefined
number

 

In the example above var y was available outside the block while let x was undefined outside of the block.

 

let vs var - What Problem Does it solve?

Let's say we had a global variable defined and needed it to be a different value inside of a block. Changing the value of a variable using var inside a block will also change the global value of the variable.

 

var num = 2;

{
  var num = 1;

  console.log(num);
}

console.log(num);
1
1

 

If we change the variable num inside the block using let the global variable will not be affected.

 

var num = 2;

{
  let num = 1;

  console.log(num);
}

console.log(num);
1
2

 

let in a for Loop Scope

Defining a var in a for loop scope will change the value of a globally defined variable whereas let will not.

 

var num = 2;

for (var num = 0; num < 10; num++) {
  // do somthing
}

console.log(num);
10

 

The same example except this time using let to define num in the for loop:

 

var num = 2;

for (let num = 0; num < 10; num++) {
  // do somthing
}

console.log(num);
// the global variable num is not affected:
2

 

let Function Scope

let behaves just like var when it comes to the function scope, in that a let variable defined inside a function will not modify a global variable.

 

var fruit = ['apple','oranges','strawberries'];

function getFruit() {
  
  let fruit = 'apple';
  
  console.log(fruit);
}

getFruit();

console.log(fruit);
apple
["apple", "oranges", "strawberries"]

 

Conclusion

You know the difference between let and var in JavaScript and can make the decision whether to use one or the other.

variable scope block