ES6: Mutability of const
When first hearing about const
in ES6, I was excited about the possibility of having immutability in native JavaScript. For developers programming in the functional style, this would have come in handy, but it turns out const
is not actually immutable. It allows mutable properties. For example, all of the below is valid:
const obj = {
prop: 'red'
}
obj.prop = 'blue'
delete obj.prop;
obj.newProp = 'yellow';
while the below is not valid:
const anotherObj = {
prop: 'red'
}
anotherObj = {
prop: 'blue'
};
So the object cannot be reassigned, but the value of the property can be changed and properties can be added and removed. It seems so similar to immutability, but it's not and it's an important distinction to make.
It's probably known by now that if you need to make an object's values immutable, you can use Object.freeze(), but be aware that this freezes the object entirely. You can't add more properties or remove properties after it's been frozen.
It's probably a good idea to use const
as much as possible as it discourages unnecessary re-assignment and forces the developer to think about how the variable will be used. If you need true immutability, you can use the Immutable" library by Facebook.
This post is part of a continuing series on practical application of ES6 features. To view the first in this series, check out this link. More are on the way.