Different ways to create Objects in JavaScript
Knowing some handy ways to create Objects might save time in your application development workflow and keep you productive.
After Primitive types in JavaScript, Objects are another type of Variable in JavaScript. And JavaScript is Object-Oriented with the help of Prototype Inheritance. Hence Objects become the crucial construct of JavaScript.
You can save some time in your application development workflow by knowing some handy ways to create Objects in Javascript. Congratulations on A happy, productive day.
All the ways or strategies to create Objects in JS have specific uses. Of course, you can use them anywhere you want. But remember, it might not serve the purpose of readability or less complexity.
And use these methods with precaution because:
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
Table of Contents:
- Using Object Notation
- Object.assign
- Using Object Spread Operator
- Object notation with JS Variables
- Having the value of variable as the key
- Using Object.create
-
Using a Constructor Function i.e. with
new
keyword
Using Object Notation
The simplest way to create an Object in JavaScript is by using Object Notation.
Enclose the key and value pair in between the curly braces i.e. { }
const person = {
name: 'Full Name',
email: '[email protected]',
};
const employee = {
id: 123456,
person: person,
}
Object.assign
Another way to create objects is by using Object.assign
. It will also allow you to create immutable copies of any object.
const person = Object.assign({
name: 'Full Name',
email: '[email protected]',
});
const newPersonDetails = Object.assign({}, person, {
email: '[email protected]'
});
You can also change the object values with the Object.assign
. Like in the following example, we will change the email of the person
object with Object.assign
const person = Object.assign({
name: 'Full Name',
email: '[email protected]',
});
Object.assign(person, {
email: '[email protected]'
});
Using Object Spread Operator
You can use the object spread operator to spread the values of any object into another object.
And hence if the target object is using the object notation, it will create a new one. Let's see the following example:
const person = {
name: 'Full Name',
email: '[email protected]',
};
const personWithAddress = {
...person,
address: 'Somewhere on the Earth'
};
Object notation with JS Variables
With ES6+, you don’t need to write the key and then the JS variable if both names are the same.
For example, if you want to add the key named website
to the person object and you already have a variable named website
. You don’t need to write to them twice.
For example, if you want to add the key named website
to the person object. You can have a variable named website
, and then you don’t need to write them twice in the object as website: website,
const person = {
name: 'Full Name',
email: '[email protected]',
};
const website = 'https://time2hack.com';
const personWithWebsite = {
...person,
website
};
Having the value of variable as the key
Sometimes you want to create a key on the existing object, but you don’t know the name of the key; it is dynamic. In those cases, there are two ways to create an object with dynamic keys:
Access key of Object as Array and assign new value
As you know, you can access the value in an object the same way you access the Array value using indexes. You can use the same way to create those keys in the object.
const person = {
name: 'Full Name',
email: '[email protected]',
};
console.log( person.name ) // Full Name
console.log( person['name'] ) // Full Name
const fullNameKey = 'name';
console.log( person[fullNameKey] ) // Full Name
const newKey = 'phone';
const phoneNum = '00123456789';
person[newKey] = phoneNum;
console.log(person);
// ?→ { name: ..., email: ..., phone: '00123456789' }
Array index access in Object Notation and Object.assign
const person = {
name: 'Full Name',
email: '[email protected]',
};
const newKey = 'phone';
const phoneNum = '00123456789';
Object.assign(person, {
[newKey]: phoneNum,
});
console.log(person);
// ?→ { name: ..., email: ..., phone: '00123456789' }
Using Object.create
This is an interesting way to create new objects. This way, you can create a new object by using another object as a reference or prototype.
This means the new object will keep the sample object as a reference in its prototype. The prototype values are accessible the same way you can access other values.
One more thing to notice is that you can override any value in the prototype. But the new object will have its value without changing the prototype.
const person = {
name: 'Full Name',
email: '[email protected]',
};
const pankaj = Object.create(person);
console.log(pankaj); // ? → {}
console.log(pankaj.name); // ? → 'Full Name'
person.name = 'Fullest Name';
console.log(pankaj.name); // ? → 'Fullest Name'
console.log(pankaj.__proto__);
// ?→ { name: 'Fullest Name', email: '[email protected]', phone: '00123456789' }
pankaj.name = 'Pankaj';
console.log(pankaj); // ? → { name: 'Pankaj' }
console.log(pankaj.name); // ? → 'Pankaj'
console.log(pankaj.__proto__.name); //? → 'Fullest Name'
And what if you want to add some new properties to the object while creating the new object. This example shows us that:
const person = {
name: 'Full Name',
email: '[email protected]',
};
const pankaj = Object.create(person, {
website: { value: 'https://pankaj.pro/' }
});
And the final object will look like the following:
Using a Constructor Function i.e. with new
keyword
Now you would more likely define a Class and then create an object from that class with the new keyword.
For a long time, JavaScript didn’t have classes, but still, it was Object-Oriented (OO). It achieved the OO by prototypal inheritance.
And a constructor
function was a primary way to construct custom objects.
const Person = function(name, email) {
this.name = name;
this.email = email;
return this;
};
const person = new Person('Full Name', '[email protected]');
Later in ES6, JavaScript got the support of Class related keywords. And it reduced the complexity and learning curve for modern JavaScript.
Now you would more likely define a Class and then create an object from that class with the new
keyword
class Person {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
const person = new Person('Full Name', '[email protected]');
Conclusion
As you can see, among these basic ways of creating Objects in JavaScript, every approach has its use case.
So "which way do you usually use to create objects?".
Let me know through comments ? or on Twitter at @heypankaj_ and @time2hack.
If you find this article helpful, please share it with others ?
Subscribe to the blog to receive new posts right in your inbox.