Understanding Var, Let and Const | ES6 Guide

Deepak Kumar
Sep 19 · 2 min read

Before the release of ES6, var was the only option to declare variables in javascript. ES6(ES2015) introduced some new features like let and const for declaring variables in javascript.

Let’s understand the usage of each notation how and where it is used :

1. Var

  • Var keyword was previously used for declaring a variable in javascript.
  • Variables declared with var can be re-initialized and re-declared too.
  • It is not recommended to use var after release of let and const.
    var a = 10;

for(var i=0;i<5;i++){
var a = 20;
console.log(a); //Returns 20

console.log(a); // Returns 20

2. Let

  • “let” is used when you have to change the value of the variable later in the code.
  • It has block scope.
  • It can be re-initialized but not re-declared.
    let a = 10;

// re-initialization
a = 30; // Updating a value to 30.

let a = 20; // Throws Error

// Block 1
let c = 10;
console.log(c); // c=10 ( Block scoped)

console.log(c); // Throws Error, c not defined.

3. Const

  • Const is used to define a constant variable which can’t be changed throughout the code.
  • It has block scope.
  • You can neither be re-initialized nor re-declared.
    const a = 10;

// re-initialization
a = 30; // Throws Error, CONST variable can't be changed

const a = 20; // Throws Error

// Block 1
const c = 10;
console.log(c); // c=10

console.log(c); // Throws Error, c not defined.

ES6 has a lot of new features like Template literals, Default Arguments, Arrow Functions, Array and Object Destructuring, Map, Reduce and Filter, Rest and Spread Operator, Object Literals, Classes and a lot more.

If you write code in a javascript and still not familiar with ES6 concepts. You should consider googling these topics.

Here I have written a comprehensive guide to learn ES6, please consider checking out.

Give some clap if you liked the article !!

For more content like this follow me on -> Twitter | Instagram | LinkedIn

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade