let vs const in JavaScript

Hemil Patel
2 min readSep 13, 2020

--

const vs let

There are three different ways to declare a variable in JavaScript: var, let, and const keywords. In ES5 and earlier versions, there was only one way to declare a variable by using the var keyword. In ES6, JavaScript got a makeover and got two more keywords, let and const. So, if you are new to JavaScript and are yet to pickup a keyword, avoid using var.

Let’s focus on let and const.

//example showing the let keyword
let myDogsName = "cujo";

//example showing the const keyword
const myDogsName = "cujo";

The main difference between let and const keywords is that variables declared using let can be reassigned with a new value. This means that you can use = operator to reassign a new value to the same variable. Here is an example:

let myDogsName = "cujo";

myDogsName = "dogo";

The const keyword doesn’t allow your variable to have a new value.

const myDogsName = "cujo"; 

myDogsName = "dogo"; //Uncaught TypeError: Assignment to constant variable.

So, the question is when should you use let and const. When you want the variable to hold the same value, you should use const. It will refrain accidental reassigning of values. A key thing to understand here is that reassigning value doesn’t mean modifying the value. Therefore, you can mutate the value without replacing it.

const nums = [1,2,3];

nums.push(4);

console.log(nums) // [1,2,3,4]

This is one of the most commonly asked basic JavaScript interview question. I highly recommend sharing with JavaScript beginner developers or anyone who would like to understand the differences between let and const.

--

--

Hemil Patel
Hemil Patel

Written by Hemil Patel

I am a front-end programmer and I love JavaScript!

No responses yet