DEV Community

Cover image for How to create a constant or non-reassignable variable in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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.
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)