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:

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:

Learn full article on the Infragistics blog

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s