The const keyword in JavaScript

Originally published at kbarker.dev on Oct 12, 2020

Traditionally, we always declared variables in JavaScript using the var keyword. As of ES6/ES2015, it's possible to also use the let and const keywords. Let's focus on const for this post.

You can use the const keyword to make something constant.

This means you cannot reassign the value:

// Declare a constant
const whiskey = "Jack Daniel's";

// TypeError: Assignment to constant variable
whiskey = "Jim Beam";

You cannot redeclare the constant, either:

// Declare a constant
const whiskey = "Jack Daniel's";

// SyntaxError: Identifier 'whiskey' has already been declared
const whiskey = "Jim Beam";

There is a catch, however. The const keyword creates a read-only value, not an immutable value.

This means you can still manipulate an object's properties:

// Declare a constant
const whiskey = {
  name: "Jack Daniel's"
};

// Add a new property
whiskey.region = "Tennessee";

// {name: "Jack Daniel's", region: "Tennessee"}
console.log(whiskey);

You can still manipulate arrays, too:

// Declare a constant
const whiskeys = ["Jack Daniel's", "Jim Beam"];

// Add a new element
whiskeys.push("Maker's Mark");

// ["Jack Daniel's", "Jim Beam", "Maker's Mark"]
console.log(whiskeys);

The MDN Web Docs explain this in a little more detail:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (i.e. its properties) can be altered.

For more information, check out the const keyword in the MDN Web Docs.


To view or add a comment, sign in

More articles by Kieran Barker

  • Implicit return statements in JavaScript

    Originally published at kbarker.dev on Oct 05, 2020 Back in May, I wrote about three ways to write a function in…

  • Named access on the window object

    Originally published at kbarker.dev on Sep 28, 2020 Imagine an HTML element with the ID #app.

    2 Comments

Explore content categories