Introduction to variable mutation and how variables can be reassigned to different values in JavaScript.
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.
var variable_1 = 500; // initalize variable_1 with value of 500console.log("variable_1: ",variable_1); // print variable_1 valuevariable_1 = 123; // assign 123 value to variable_1console.log("variable_1: ",variable_1); // print variable_1 value
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:
var variable_1 = 100;var variable_2 = 200;var variable_3 = variable_1; // assign to value of variable_1console.log("variable_1: ",variable_1); // print variable_1 valueconsole.log("variable_2: ",variable_2); // print variable_2 valueconsole.log("variable_3: ",variable_3); // print variable_3 valuevariable_1 = variable_2; // assign to value of variable_2variable_2 = 500;console.log("Values after update:");console.log("variable_1: ",variable_1); // print variable_1 valueconsole.log("variable_2: ",variable_2); // print variable_2 valueconsole.log("variable_3: ",variable_3); // print variable_3 value
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: