"Variables declared with const cannot change" ... well kinda...
Austin Beaufort
Posted on November 26, 2020
You've heard it 100 times...
let is mutable
const is immutable (not mutable)
well... sort of ...
The easy part to clear up is this:
** let is mutable **
If we declare a variable using let, we can re-assign that variable:
let myName = 'Tyler';
myName = 'John';
this works just fine.
Now on to the confusing bit. (ha, no computer science pun intended.)
Basic types with const are immutable.
Examples of this:
const myName = 'Tyler';
myName = 'John'; // this line will throw an error
const myNumber = 7;
myNumber = 3; // this line will throw an error
We cannot re-assign a string or number declared with const.
... "BuT WhaT AbOuT ObJectS AnD ArRaYS???" ...
good point. Check this out:
const employee = {
id: 12345,
name: 'John Doe',
address: {
street: '123 Circle St.',
city: 'Pittsburgh',
zip: 11111,
}
}
employee.id = 99999,
employee.address = {}
console.log(employee) // { id: 99999, address: {} }
We used const, but we can still change the inside values of the object itself. We even deleted a key/value pair entirely!
The same happens with Arrays:
const employee = [99999, 'John Doe', ['Cleveland', '123 Circle Street', 11111]]
employee.pop()
employee.pop()
console.log(employee) // [ 99999 ]
Again, we used const, but we could still manipulate the inside values of the array.
This being said, we cannot re-assign the entire employee object or array, the following examples will result in an error:
const employee = [99999, 'John Doe', ['Cleveland', '123 Circle Street', 11111]]
employee = [4444, 'Jane Doe']
console.log(employee) // Error, cannot re-assign const
// example 2
const employee = {
id: 12345,
name: 'John Doe',
address: {
street: '123 Circle St.',
city: 'Pittsburgh',
zip: 11111,
}
}
employee = {}
console.log(employee) // Error, cannot re-assign const
So we have learned that we can change the insides of an object and array even though it was declared with const.
How do we stop this from happening?
One solution is to use Object.freeze().
This will work for objects and arrays that are not nested.
If an object or array is nested, the nested elements will still be able to be changed.
To "deep freeze" an object or array, we would need to create our own deep freeze function or use an external library.
Thanks for reading, for more tech content you can find me here:
Youtube => https://www.youtube.com/austinbeaufort
Twitter => https://twitter.com/AustinBeaufort
Posted on November 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.