You can make mere variables and even an object immutable. But, how about a humble object prop?
Making object props constant and immutable has practical usage. For e.g. consider this totally practical program to print out fruits and whether they are poisonous.
1
2
3
4
5
6
7
8
|
const eatable = {
poisonous: false,
printFruit: function(fruit) {
return "name: " + fruit + " | poison: " + this.poisonous;
}
};
console.log(eatable.printFruit("mango")); // name: mango | poison: false
|
If someone decides to play spoil-sport and update poisonous
to true, it may result in whole populations being wiped out.
1
2
3
4
|
// ..blah
eatable.poisonous = true;
console.log(eatable.printFruit("apple")); // name: apple | poison: true
|
We cannot afford to change constants midway. It turns out that the solution is simple - all we needed was to keep a constant as true constant by defining it as unwritable
.
1
2
3
4
5
6
7
8
9
10
|
const eatable = {
printFruit: function(fruit) {
return "name: " + fruit + " | poison: " + this.poisonous;
}
};
Object.defineProperty(eatable, "poisonous", {
value: false,
writable: false
});
|
Now, the logic is bulletproof and cannot unknowingly cause harm to a human.
1
2
3
4
5
6
|
console.log(eatable.printFruit("mango")); // name: mango | poison: false
eatable.poisonous = true;
// no error when not in strict mode
// .. but constant does not change
console.log(eatable.printFruit("apple")); // name: apple | poison: false
|