DEV Community

Cover image for How to create a reassignable variable in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create a reassignable variable in JavaScript?

Originally posted here!

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

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

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

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
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 😃.


Discussion (0)