- Object literals
- New operator or constructor
- Object.create method
In this post, we will learn each of these methods.
An object literal, also called an object initializer, is a comma-separated set of paired names and values. You can create an object literal as shown below:
You can add properties dynamically in an object, including after you have created the object. Here we add the dynamic property car.type:
The object literal is a simple expression that creates an object each time the statement that it appears in is executed in the code. You can also use Object.defineProperty to create properties in the object literal as shown below:
The main advantage of using Object.defineProperty is that you can set values for object property descriptors or modify existing properties. You can learn more about Object Property Descriptor here.
New Operator or Constructor
The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object. Consider the following code: