How to create a constant or non-reassignable variable in JavaScript?

August 23, 2021 - 2 min read

To create a constant or non-reassignable variable in JavaScript, we can use the const keyword followed by the name we need to call the variable then the assignment operator (or equal sign), and finally the value to store in that variable.

TL;DR

// Create a constant variable
const name = "John Doe";

console.log("Here the value is: ", name); // Here the value is: John Doe

// reassigning the name variable value
// to the value of `Lily Roy` results in an Error
name = "Lily Roy"; // 🔴 TypeError: Assignment to constant variable.

For example, let's say we have a value called John Doe and we want to create a constant variable called name to store this.

To do that we can use the const keyword followed by the name we need to call the variable, then the assignment operator (or equal sign), and finally the value to be assigned to that variable in our case it is John Doe.

It can be done like this,

// Create a constant variable
const name = "John Doe";

Now if we try to change the value of the variable name from John Doe to Lily Roy it will result in a TypeError: Assignment to constant variable.

// Create a constant variable
const name = "John Doe";

console.log("Here the value is: ", name); // Here the value is: John Doe

// reassigning the name variable value
// to the value of `Lily Roy` results in an Error
name = "Lily Roy"; // 🔴 TypeError: Assignment to constant variable.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.