Learn JavaScript ES6 and Beyond: Mutating Const

Learn JavaScript ES6 and Beyond: Mutating Const

Written by Charles Vines, Jr. on May 20th, 2021 Views Report Post

Just like the let keyword const can be used in many different scenarios. Like I said in the previous post when using const you want to make sure that you are not using a variable that will be altered later on in your code. Some developers take it a step farther and they declare every variable as a const unless they know 100% that the variable will be altered then they use the let.

While changing a declared value like a string or number will result in a console error, in certain situations the const keyword is not the end all be all.

When you declare a const value as an object or an array it is important to understand that objects (including arrays and functions) assigned to a variable using const are still mutable. const only prevents reassignment of the variable identifier.

const CITIES = ["New York", "Philadelphia", "Miami"];
CITIES = ["Milwaukee", "Tulsa", "Austin"];
CITIES[2] = "Los Angeles";
console.log(CITIES); 

CITIES = ["Milwaukee", "Tulsa", "Austin"]; will result in an error. Console will display ["New York", "Philadelphia", "Los Angeles"]

In the console you can see the original object has been mutated to add LA on cities[2]. This shows that the elements in CITIES are mutable, but because const has been used you are unable to use the variable identifier CITIES to point to a different array using the assignment operator.

Comments (0)