In our last session, we learned how to access individual items in an array using their index, like
planets[1]
.
What if we made a mistake or want to update an item in the array?
Engagement Message
Do you think we can change it?
Yes, you can! JavaScript arrays are mutable, meaning their contents can be changed after they are created.
You can replace an item at a specific index with a new value using the assignment operator =
.
Engagement Message
How is this similar to assigning a new value to a simple variable?
The syntax is:
arrayName[index] = newValue;
If we have
let planets = ["Mercury", "Venus", "Earth"];
we can change "Venus" to "Mars" like this:
planets[1] = "Mars";
Engagement Message
What index would you use to change "Mercury"?
After running
planets[1] = "Mars";
the planets
array would now contain
["Mercury", "Mars", "Earth"]
.
The original value at that index ("Venus") is replaced by the new one ("Mars").
