Keyword var, let, and const in Javascript

There are three different keyword you can use when declaring a variable(or constant) in Javascript. They are var, let, and const. Shortly, you can use either var or let if you want to define a changeable variable. A variable define with var or let keyword is mutable. You can change their value as needed. Keyword const in other hand is used to define a constant as the name implied. A value assign to a constant is immutable. It can never be change.

Go Deeper

Keyword var:

Before ES6, var is the only keyword you can use when defining a variable. A variable defined with var keyword is accessible to entire script(global) when it defines outside a function. See below example:

var name = "Josh";

function greetings(){
  //name is accessible here
  console.log("Hi, ",name,"!")
}

greetings();
//name is accessible here as well
console.log("Your name is ", name);

From code above we will say that the variable name is scoped globally, because it is defined outside a function. If it is defined wherever in a function body it has function scope, and it's accessible to the entire function where it's defined. Below is the sample script:

function count(){
  for (var i = 0; i < 5; i++) { 
      if(i==0) {
        // define counter in this if scope
        var counter = 1;
      } 
      else {
         // counter is accessible here
         counter += 1;
      }
      // counter is accessible here
    console.log("Inside the loop:", counter);
  }
  // counter is accessible here
  console.log("Outside the loop:", counter);
}
count();

You can see that even though you define the variable counter inside the if block, it is accessible to the whole function. That's one of the characteristic of the var. Another thing about var is you can re-declare same variable multiple times with var keyword:

  var name = "James";
  var name = "Albert";
  var name = 5;

Keyword let:

let keyword is introduced in ES6 as a new way to declare variable in Javascript. What makes it different and better than var is that a variable defined with let keyword is a block scoped variable. It's only accessible in block where it's defined. With that, you can avoid unintentionally assign wrong value to another variable with same name as it may happen with var keyword. Here is sample script of let usage:

for (let count = 0; count < 5; count++) {
    // count is accessible here
    console.log("Inside the loop:", count);
}

// here count is inaccessible      
console.log("Outside the loop:", count);

Keyword const:

Like let, keyword const is introduced in ES6 as well, and has block scope precisely like let has although it has different purpose. It use to define constant variables. Once you define a constant, its values will stay the same throughout its scope. It will throw an error if you try to change it. Here is the example:

const PI = 3.14;
shouldChange = true;
if (shouldChange){
  //try to change const value will result an error
  PI = 2.5;
}

Though it's clear that you cannot change a const variable's value for scalar data types like number, boolean, or string, it's a bit tricky to understand how it works when using const to define an array or an object.

const in array or object context

When you define an array or an object using const, the variable will hold the reference to that object or array, so the reference is unchangeable, but its content is changeable. See code below:

/* Array example */
const arr1 = [1, 2, 3, 4];
//reassign value to arr1 will throw an error
//arr1 = [1,2,3,4,5]

//but change the arr1 content is ok
arr1.push(5);
/* Object example */
const person = {name:"Bob", age: 34}
//change content of person is ok
person["hobby"] = "badminton";
person.lastName = "Marley";

//reassign person will throw an error
//person = {name:"Bob", lastName:"Marley", age:34, hobby:"badminton"}

Those are var, let, const with similarities and differences. Here are the key notes about those three:

varletconst
Available before ES6Come as new feature in ES6Come as new feature in ES6
Global and functional scopeBlock scopeBlock scope
Use to hold changeable valuesUse to hold changeable valuesUse to hold constant values
0
Subscribe to my newsletter

Read articles from Eklemis Santo Ndun directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Eklemis Santo Ndun
Eklemis Santo Ndun

Hi there, I'm a developer from Indonesia. I love learning new things especially technology. Now, not only do i love learning new things, but also to write about what i've learnt. In regular work day, i deal a lot with Images files, SQL Server, MS Access and Excel as well. To make my daily target reached with high quality and shorter time, i automate many of my task with help of Python. In some months where my regular task is not much, i spent time develop web apps to automate my colleagues regular task as well. Out of regular work time, i spend time learning and creating project with Javascript (and Html and CSS), learn UI/UX design with Figma, code Python scripts(Machine Learning), and Rust programming language. To help better remembering all things i've learnt, now i learn to write about them as well.