Preparing for an interview or just refreshing your Object manipulation skills? This is all you’ll need.
Introduction
JavaScript is a versatile programming language that provides developers with a range of powerful tools to work with. One such tool is an Object.
With this cheat sheet, you’ll be able to quickly and easily reference the most important object functions in JavaScript. Let’s dive straight into it then.
Pre-requisites
What is an Object?
Objects are essential for creating complex data structures and organizing code in Javascript and are the building blocks of any JavaScript program. They allow developers to perform various operations on objects, including adding or removing properties, looping through object properties, and checking for the existence of properties.What are enumerables in Javascript?
In JavaScript, enumerable is a property attribute that determines whether a property can be iterated over in a for…in loop. If a property is enumerable, it will be listed when you loop through an object’s properties using a for…in loop. The default value of the enumerable property is true. Any property you define on an object is enumerable by default unless you specify otherwise.
Object.defineProperties()
Object.defineProperties()
is a built-in JavaScript function that allows you to define multiple properties for an object at once. This function takes two arguments: the object you want to define the properties for, and an object that defines the properties.
There’s a Object.defineProperty()
method too, it works similar way for similar use cases just that it can define a single property at a time.
const myObj = {};
Object.defineProperties(myObj, {
name: {
value: "Max",
writable: false
},
age: {
value: 30,
writable: true
}
});
console.log(myObj); // prints {name: "Max", age: 30}
myObj.name = "John"; // throws an error
myObj.age = 31;
console.log(myObj.age); // prints 31
Now, how is it different than assigning properties with dot notation, you might ask :
Object.defineProperties()
allows you to define multiple properties at once, whereas assigning key and values with dot notation can only set one property at a time.Object.defineProperties()
provides greater control over the behavior of properties. For example, you can set properties to be read-only or non-enumerable, which is not possible with dot notation.
Object.keys()
Object.keys()
is a built-in JavaScript function that returns an array of a given object’s property names. Object.keys()
can be useful when you need to loop through an object's properties or access a specific property by name. It's also a handy way to check if an object has any properties at all, as the returned array will be empty if the object has no enumerable properties.
There’s a method Object.getOwnPropertyNames()
which returns an array of all the object’s property names, regardless of whether they are enumerable or not. This includes properties created using Object.defineProperty()
.
const myObj = { name: "Sarvesh", age: 24};
const keys = Object.keys(myObj); //returns ["name", "age"]
Object.defineProperty(myObj, "city", {
value: "Mumbai",
enumerable: false,
});
console.log(Object.getOwnPropertyNames(obj)); // Output: ["name", "age", "city"]
Object.values()
Object.values()
is a built-in function in JavaScript that allows you to extract the values of an object’s properties and return them in an array.
const myObj = { name: "Sarvesh", age: 24, city: "Mumbai" };
const values = Object.values(myObj); // returns [ 'Sarvesh', 24, 'Mumbai' ]
Object.entries()
Object.entries()
method is a built-in function in JavaScript that allows you to get an array of all the property key-value pairs of an object. The returned array contains sub-arrays, where each sub-array represents a property of the object and consists of two elements: the property name (key) and the corresponding value.
const myObj = { name: "Sarvesh", age: 24, city: "Mumbai" };
const entries= Object.entries(myObj);
// returns [[ 'name', 'Sarvesh' ], [ 'age', 24 ], [ 'city', 'Mumbai' ]]
Object.fromEntries()
Object.fromEntries()
is a built-in JavaScript function that creates an object from an array of key-value pairs. It takes an iterable (such as an array) containing key-value pairs and returns a new object with those pairs as properties. So basically, it's just the reverse of Object.entries()
.
const entries = [["name", "Max"], ["age", 30], ["city", "Mumbai"]];
const obj = Object.fromEntries(entries);
console.log(obj); // output: { name: "Max", age: 30, city: "Mumbai" }
Object.assign()
Object.assign()
is a way to combine the properties of different objects into a new object without changing the original objects. This function is useful when you need to merge two or more objects into a single object.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = Object.assign(obj1, obj2);
// returns {a: 1, b: 2, c: 3, d: 4}
Object.freeze()
Object.freeze()
is a built-in function that freezes an object, preventing any modifications to its properties. This function is useful when you want to prevent accidental changes to an object.
const myObj = { name: "John", age: 30, city: "New York" };
Object.freeze(myObj);
myObj.name = "Jane";
// throws an error because the object is frozen
Object.isFrozen()
Object.isFrozen()
determines if an object is frozen.
const obj = {}
Object.isFrozen(obj) // false
Object.freeze(obj)
Object.isFrozen(obj) //true
Object.seal()
Object.seal()
is a built-in function that seals an object, preventing the addition or removal of properties.
Now how is this different from Object.freeze()
, you might ask:
Object.freeze()
is more restrictive thanObject.seal()
When an object is frozen, its properties cannot be added, deleted, or modified in any way. When an object is sealed, its properties can still be modified, but they cannot be added or deleted.Object.freeze()
affects all levels of an object’s properties, whileObject.seal()
only affects the object’s immediate properties. This means that if an object has nested objects as properties,Object.freeze()
will prevent changes to those nested objects as well.
In layman's language, freezing an object means that its properties cannot be changed, while sealing an object only prevents the addition or deletion of properties.
const myObj = { name: "Sarvesh", age: 24, city: "Mumbai" };
Object.seal(myObj);
myObj.name = "Max"; // allowed with seal, not with freeze
myObj.gender = "Male"; // throws an error because the object is sealed
Object.isSealed()
Object.isSealed()
determines if an object is sealed.
const obj = {}
Object.isSealed(obj) // false
Object.seal(obj)
Object.isSealed(obj) // true
Object.create()
Object.create()
is a built-in function in JavaScript that creates a new object with the specified prototype object and properties.
const person = {
name: "",
age: 0,
greet: function() {
console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
const john = Object.create(person);
john.name = "Max";
john.age = 24;
john.greet(); // Output: Hi, my name is Max and I'm 24years old.
In this example, we create an object person with three properties: name, age, and greet. We then create a new object john using Object.create(person)
, which sets person as the prototype object for john. This means that john inherits all the properties and methods of person.
We then set the name and age properties of john, and call the greet method, which outputs a message using the name and age properties of the john object.
Object.getPrototypeOf()
As Object.create()
creates a new object with the specified prototype, Object.getPrototypeOf()
returns the prototype of an object. Therefore, we can say that Object.getPrototypeOf()
is the reverse of Object.create()
const proto = { a: 1 }
const obj = Object.create(proto)
obj.b = 2 // obj = { b: 2 }
Object.getPrototypeOf(obj) // { a: 1 }
Object.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptor()
is a built-in function in JavaScript that returns an object containing the descriptor for a specific property of an object. The descriptor provides information about the property, such as whether it is writable or enumerable.
There’s a Object.getOwnPropertyDescriptors()
method too, it works similar way for similar use cases just that it can define multiple properties of the object at a time.
const myObj = {
name: 'Max',
age: 30,
city: 'Mumbai'
};
const descriptor = Object.getOwnPropertyDescriptor(myObj, 'name');
console.log(descriptor);
//returns { value: 'Max', writable: true, enumerable: true, configurable: true }
const descriptorS = Object.getOwnPropertyDescriptors(myObj)
console.log(descriptors)
//Outputs
{
// name: { value: 'Max', writable: true, enumerable: true, configurable: true },
// age: { value: 30, writable: true, enumerable: true, configurable: true },
// city: { value : "Mumbai", writable:true, enumerable: true, configurable: true }
// }
Object.preventExtensions()
Object.preventExtensions()
is a built-in function in JavaScript that prevents new properties from being added to an object.
const obj = { a: 1 }
Object.preventExtensions(obj)
Object.defineProperty(obj, 'b', { value: 2 }) //throws an error
Object.isExtensible()
Object.isExtensibles()
is a built-in function in JavaScript that determines whether an object can have new properties added to it.
const obj = {}
Object.isExtensible(obj) // true
Object.preventExtensions(obj)
Object.isExtensible(obj) // false
Object.prototype.hasOwnProperty()
Object.prototype.hasOwnProperty()
is a built-in function in JavaScript that returns boolean indicating whether an object has the specified property.
const obj = { a: 1 }
obj.hasOwnProperty('a') // true
obj.hasOwnProperty('b') // false
Object.prototype.isPrototypeOf()
Object.prototype.isPrototypeOf()
is a built-in function in JavaScript that checks if an object exists in another object’s prototype chain.
const proto = { a: 1 }
const obj = Object.create(proto)
proto.isPrototypeOf(obj) // true
Object.prototype.propertyIsEnumerable()
Object.prototype.propertyIsEnumerable()
is a built-in function in JavaScript that checks if object exists in another object’s prototype chain.
const obj = { a: 1 }
const arr = ['a']
obj.propertyIsEnumerable('a') // true
arr.propertyIsEnumerable(0) // true
arr.propertyIsEnumerable('length') // false
Resources
You may check if an Object method is still supported by a range of browsers or is redundant on :
Can I use... Support tables for HTML5, CSS3, etc
Conclusion
In conclusion, understanding the various methods available on the Object prototype in JavaScript is essential for writing clean and efficient code.
In this blog post, we’ve covered a wide range of methods available on the Object prototype, including Object.keys()
, Object.values()
, Object.entries()
, Object.assign()
, Object.freeze()
, Object.seal()
, Object.create()
, Object.defineProperty()
, Object.defineProperties()
, Object.getPrototypeOf()
, Object.setPrototypeOf()
, and Object.is(). By understanding the purpose and functionality of each of these methods, developers can make more informed decisions about which methods to use in their code.
Subscribe to my (free) weekly newsletter about writing and web development — https://sarveshh.beehiiv.com/subscribe
If you liked this, you might enjoy:
Top comments (0)