Common static methods of Object in JS
1. Object.create(proto, [propertiesObject])
Creates a new object with the specified prototype and optionally adds properties.
const proto = { greet() { return "Hello!"; } };
const obj = Object.create(proto);
console.log(obj.greet()); // "Hello!"
2. Object.assign(target, ...sources)
Copies the enumerable properties of one or more source objects to a target object.
const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
3. Object.keys(obj)
Returns an array of the object's own enumerable property names.
const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ["a", "b"]
4. Object.values(obj)
Returns an array of the object's own enumerable property values.
const obj = { a: 1, b: 2 };
console.log(Object.values(obj)); // [1, 2]
5. Object.entries(obj)
Returns an array of the object's own enumerable property [key, value]
pairs.
const obj = { a: 1, b: 2 };
console.log(Object.entries(obj)); // [["a", 1], ["b", 2]]
6. Object.freeze(obj)
Prevents any modifications to an object.
But it only work with 1 level depth
const obj = { a: 1, b: { c: 1 } };
Object.freeze(obj);
obj.a = 2; // No effect
console.log(obj.a); // 1
obj.b.c = 2; // Has effect
console.log(obj.b.c); // 2
7. Object.seal(obj)
Prevents new properties from being added to an object, but allows modification of existing properties
const obj = { a: 1 };
Object.seal(obj);
obj.b = 2; // Cannot add new property
obj.a = 3; // Allowed
console.log(obj); // { a: 3 }
8. Object.is(value1, value2)
Determines whether two values are the same value (similar to ===
but handles NaN
and -0
differently).
console.log(Object.is(0, -0)); // false
console.log(Object.is(NaN, NaN)); // true
9. Object.getPrototypeOf(obj)
Returns the prototype of the specified object.
const obj = {};
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
10. Object.hasOwn(obj, prop)
Checks if the object has the specified property as its own (introduced in ES2022).
const obj = { a: 1 };
console.log(Object.hasOwn(obj, "a")); // true
console.log(Object.hasOwn(obj, "b")); // false