Object Immutability

by MorningLit

JavaScript

const a = {aa: "bb", ab: 1};
Object.preventExtensions(a);

a.foo = "bar"; // Addition Will not work!

console.log(a); // {aa: "bb", ab: 1}
delete a.aa; // Deletion still works
console.log(a); // {ab:1}
a.ab = 99; // Modification still works
console.log(a); // {ab:99}

console.log(Object.isExtensible(a)); // false


const b = {aa: "bb", ab: 1};
Object.seal(b);

b.foo = "bar"; // Addition will not work!
delete b.aa; // Deletion will not work!

console.log(b); // {aa: "bb", ab: 1}
b.ab = 99; // Modification still works
console.log(b); // {aa: "bb", ab: 99}

console.log(Object.isExtensible(b)); // false
console.log(Object.isSealed(b)); // true


const c = {aa: "bb", ab: 1};
Object.freeze(c);

c.foo = "bar"; // Addition will not work!
delete c.aa; // Deletion will not work!
c.ab = 99; // Modification will not work!

console.log(c); // {aa: "bb", ab: 1}

console.log(Object.isExtensible(c)); // false
console.log(Object.isSealed(c)); // true
console.log(Object.isFrozen(c)); // true