5 object methods you must know as a javascript Developer
Suraj Auwal
Posted on April 6, 2020
Almost everything is an object in javascript and unfortunately, not all of us know the goodies that it comes with.
In this article, i will show you the five most used Object methods and their examples.
1. Object.assign()
This is perhaps the most used object method in javascript. So basically, this method copies all the values from one or more source to a targeted object.
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
const honda = Object.assign(chevrolet);
console.log(honda);
// {type: "sedan", price: 10000, isLuxury: true}
In the above code block, we created a new object chevrolet that hold some data in it.
And for some reason we want another object with the same data. So we basically copy the data inside of chevrolet to honda using the assign method.
2. Object.create()
This method is quite similar to Object.assign() — you can make a new object base on a reference object. However, the difference is that objects created with the assign() method are linked with the reference object. Changes made to one of them will affect the other (inheritance chain).
// with assign
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
const honda = Object.assign(chevrolet);
honda.price = 2000; // this will overwrite both
// the price property in honda
// and chevrolet
console.log(chevrolet);
// {type: "sedan", price: 2000, isLuxury: true}
// with object.create
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
const honda = Object.create(chevrolet);
honda.price = 2000;
// change will not affect reference object (chevrolet)
console.log(chevrolet);
// {type: "sedan", price: 10000, isLuxury: true}
console.log(honda);
// {type: "sedan", price: 2000, isLuxury: true}
3. Object.entries()
The entries.() method return an array with all the data (key/values) inside of an object.
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
const chevArr = Object.entries(chevrolet);
console.log(chevArr);
// [ [type,sedan,], [price,10000,], [isLuxury,true,]]
4. Object.freeze()
This method literally freeze an object making it immutable. Properties can not be changed or deleted.
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
Object.freeze(chevrolet);
chevrolet.price = 20000;
console.log(chevrolet.price);
// 10000 instead of 20000.
5. Object. is()
This method compares two objects and return a boolean.
const chevrolet = {
type: 'sedan',
price: 10000,
isLuxury: true,
};
const honda = Object.assign(chevrolet);
const isEqual = Object.is(honda, chevrolet);
console.log(isEqual);
// true
Update: if you like this, you should checkout my article on array methods
That is it guys and i hope you learn something from this.
Happy coding.
Posted on April 6, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 20, 2019