Variable Mutation
Explore variable mutation in JavaScript by learning how to reassign values and copy variables. Understand how reassignment affects stored values and memory usage. This lesson helps you grasp a key concept in managing and manipulating data in your code.
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: