Four Ways to Create Objects in JavaScript

In JavaScript, there are four methods to use to create an object:

  1. Object literals
  2. New operator or constructor
  3. Object.create method
  4. Class

In this post, we will learn each of these methods.

Object literals

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:


var car = {
model: 'bmw',
color: 'red',
price: 2000
}
console.log(JSON.stringify(car));

You can add properties dynamically in an object, including after you have created the object. Here we add the dynamic property car.type:


var car = {
model: 'bmw',
color: 'red',
price: 2000
}
console.log(JSON.stringify(car));
car.type = 'manual'; // dynamic property console.log(JSON.stringify(car));

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:


var car = {
model: 'bmw',
color: 'red',
price: 2000
}
Object.defineProperty(car, "type", {
writable: true,
enumerable: true,
configurable: false,
value: 'gas'
});
console.log(car.type); //gas

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:

Learn full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com