How to create a reassignable variable in JavaScript?

Published August 22, 2021

To create a reassignable variable, we can use the let keyword followed by the name we need to call the variable in JavaScript.

TL;DR

// Create a reassignable variable
let name = "John Doe";

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

// change the value of the variable name
// again to the value of `Lily Roy`
name = "Lily Roy";

console.log("Here the value is: ", name); // Here the value is: Lily Roy

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

To do that we can use the let 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 reassignable variable
let name = "John Doe";

By reassignable, we mean that the value of John Doe can be changed to anything other value during the runtime of the program.

For example, Later if we want to change the name to Lily Roy all we have to do is use the variable name then use the assignment operator followed by the new value. It can be done like this,

// Create a reassignable variable
let name = "John Doe";

// change the value of the variable name
// to the value of `Lily Roy`
name = "Lily Roy";

To understand the process let's log the variable value after each assignment using the console.log() method like this,

// Create a reassignable variable
let name = "John Doe";

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

// change the value of the variable name
// again to the value of `Lily Roy`
name = "Lily Roy";

console.log("Here the value is: ", name); // Here the value is: Lily Roy

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter