const and let statements in JavaScript

June 01, 2022

Before ES2015 was introduced, you could only declare a variable using var statement. Now we got multiple declaration options that provide more flexibility.

const

A constant is a variable that cannot be redefined later. Once declared, you cannot change its value. Such variables are often used in JavaScript. Same as in other languages, constants appeared in JavaScript with the release of ES6.

Before they appeared in JS, all variables could be easily reassigned values:

var beer = true;
beer = false;
console.log(beer); // returns false

Value of a constant cannot be reassigned, and if you try to do so, you will get an error in the console:

const beer = true;
beer = false;
// Uncaught TypeError: Assignment to constant variable.

let

Modern JavaScript has scopes for all variables. Different blocks of code are separated using curly braces ({}). In functions, these curly braces limit the scope of any variable declared with var. If a variable is defined inside an if...else block, it will not be scoped to the block:

var topic = "Vue";

if (topic) {
  var topic = "React";
  console.log(topic); // React
}

console.log(topic); // React

So we modified the value of topic variable within the conditional block.

With the let keyword, we can scope (restrict) any variable to any block of code. Therefore, let allows us to protect values of global variables:

var topic = "Vue";

if (topic) {
  let topic = "React";
  console.log(topic); // React
}

console.log(topic); // Vue

This time, the global topic variable didn’t get its value updated, it remained unaffected.

Another scenario where curly braces do not offer scoping of a variable is in for loops:

var button, body = document.getElementById("container");

for (var i = 0; i < 3; i++) {
    button = document.createElement("button");
    button.onclick = () => alert("This is box #" + i);
    body.appendChild(button);
}

Here we created three <button> elements and added them to the HTML body. If you click on any one of them, a callback will be triggered and it will display the element number. However, since we used var keyword here, it will display 3 for all of them since it was the last value in the loop and all 3 elements essentially use the same variable.

Now simply replace var with let and you get a completely different result:

var button, body = document.getElementById("container");

for (let i = 0; i < 3; i++) {
    button = document.createElement("button");
    button.onclick = () => alert("This is box #" + i);
    body.appendChild(button);
}

Now every button will display a different number because every iteration of the loop had a scoped, individual variable. You can think of it as of a brand-new variable!


Published by NinaCoder who lives and works in Mexico DF building useful things.