Variable Mutation
Explore how variable mutation works in JavaScript by learning to reassign values using the assignment operator. Understand how variables lose previous values upon reassignment, how to copy values between variables, and how JavaScript manages memory by removing unreferenced data.
We'll cover the following...
Mutation
Variable mutation is reassigning a variable to another value. This is simply done with the assignment operator =.
The above slides show how assigning a variable into another value will reassign it to a new value while losing the link to the previous value.
NOTE: When a variable is reassigned, it no longer holds its previous value. That previous value may still exist if it was assigned to another variable. However, if no variables reference that value anymore, JavaScript’s memory management will automatically remove it to free up memory.
You can see that we initialize the value of variable_1 with the value of 500. In line 3, we reassign or mutate the variable variable_1 with the value of 123 using the = operator.
Copy values
We can use values through variables and assign them to other variables. We do this by assigning the variable to the other variable directly.
In this case, there are no duplicates being created for the value. Now the same value can be accessed through two different variables.
Let’s see this translated in the code below:
In the above code, we initialize variables variable_1, variable_2 and variable_3. Notice that in line 3 we assign variable_3 to variable_1. When we print the values of the three variables, the values of variable_1 and variable_3 are the same because of the assignment done on line 3. These values can be assigned to another variable on any part of the program. For instance, look at line 9. We assign the value of variable_2 to variable_1. Meanwhile, the value of variable_3 remains unchanged.
Before proceeding to the next lesson, please answer the following question:
Hey there! I'm Ed, your mentor here to help you lock in what you learned about Variable Mutation. Here's your question:
If a variable's value is reassigned, can the previous value be retrieved? Why or why not?
Give it a try!