String
, Â Math
, Â RegExp
, Â Object
, Â Function
, etc.window
, XMLHTTPRequest
, etc.Extending a built-in/native JavaScript object means adding properties/functions to its prototype
. Imagine your code uses a few libraries that both extend the Array.prototype
 by adding the same contains
 method, the implementations will overwrite each other and your code will break if the behavior of these two methods is not the same.
By combining writable: false
 and configurable: false
, you can essentially create a constant (cannot be changed, redefined or deleted) as an object property.
let myObject = {};
Object.defineProperty(myObject, 'number', {
value: 42,
writable: false,
configurable: false,
});
console.log(myObject.number); // 42
myObject.number = 43;
console.log(myObject.number); // 42
If you want to prevent an object from having new properties added to it, but otherwise leave the rest of the object’s properties alone, call Object.preventExtensions()
var myObject = {
a: 2,
};
Object.preventExtensions(myObject);
myObject.b = 3;
myObject.b; // undefined
Object.seal()
creates a sealed object, which means it takes an existing object and essentially calls Object.preventExtensions()
on it, but also marks all its existing properties as configurable: false
.
So, not only can you not add any more properties, but you also cannot reconfigure or delete any existing properties (though you can still modify their values).
Object.freeze()
 creates a frozen object, which means it takes an existing object and essentially calls Object.seal()
 on it, but it also marks all “data accessor” properties as writable:false
, so that their values cannot be changed.
This approach is the highest level of immutability that you can attain for an object itself, as it prevents any changes to the object or to any of its direct properties.
// Variable assignment.
const foo = ['one', 'two', 'three'];
const [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
// Swapping variables
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
// Variable assignment.
const o = {p: 42, q: true};
const {p, q} = o;
console.log(p); // 42
console.log(q); // true