Mastering the Differences Between let and var in JavaScript

We all have a confusion about the difference between two javascript main keywords "let" and "var". Let me clear this to you in the most easy way. So, "let" is something which has his control to himself while "var" is like giving his control to everyone. Simply saying "let" is block scope while "var" is not. "let" does not allow it's child block to modify it value, they can only play with it's value and it will get back it's original by itself.

var :

With "var" there are only two types of scope for a variable. There is global scope which is where we would place a variable if we define the variable with "var" outside of any function. And then there is function scope for variable defined inside of a function. But there is no block scope and this is a source of confusion and occasional bugs.

var x = 1;

if (x === 1) {
  var x = 2;
  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2
  • Here, we can see the block declaration of var has changed the value of "var" declared variable.

let :

"let" allows us to define variables. Previously we declare our variables using “var” keyword. But it has some limitations when it comes to scope as it does not offer block scope. But now using "let" keyword we can declare truly block-scoped variables.

let x = 1;

if (x === 1) {
  let x = 2;
  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 1
  • Here, we can see the block declaration of "let" is different in both the block and get back it's original value.
0
Subscribe to my newsletter

Read articles from Aryan Kesharwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aryan Kesharwani
Aryan Kesharwani

A team oriented problem solver pursuing Bachelor's degree in B.Tech.(CSE). Seeking for a position of MERN Developer as a intern.