Four ways of creating an object in JavaScript
This article is part of a series I’m writing on learning the four ways of creating an object in JavaScript. Understand the objects is like understand JavaScript.
Let’s get this started…
JavaScript is mainly about objects and primitives. A primitive value is a value that has no properties or methods. In JavaScript, objects are variables too. But objects can contain many values. So the JavaScript object is a collection of named values.
There are four different ways to create objects in JavaScript :
1. Object literal syntax
2. ‘new’ keyword
3. Object.create()
4. Object.assign()
Let’s work with an example!
- Creating objects using object Object literal syntax literal syntax
This is the easiest way. All we have to define & create an object in one statement. In here key-value pairs separated by ‘:’ inside a set of curly braces ({ })
Like below :
- Creating objects using the ‘new’ keyword
The Second way to create an object is to use the ‘new’ keyword. It will create and return an empty object or this keyword can use as a user-defined constructor function
Look at this example :
- Using classes to create objects
Class is a template or blueprint about the capability of what an object can do in Object-Oriented Programming (OOP). The constructor functions are now replaced by classes as they are supported through ES6 specifications.
This method is more similar to using ‘new’ with the user-defined function constructor
Let’s see the code now:
- Using Object.create() to create new objects
As you can see, when we create an object using this method it creates a new object using an existing object as the prototype of the newly created object.
- Using Object.assign() to create new objects
If we want to create an object that needs to have properties from more than one object, we can use the Object, assign() method.
Here’s an example:
Conclusion
And that’s it!
I hope you found this article useful!
Thank you
See you soon… 🤓