DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Logging Best Practices Revisited [Video]
  • Playwright JavaScript Tutorial: A Complete Guide
  • What Is Test Pyramid: Getting Started With Test Automation Pyramid
  • Build a Simple Chat Server With gRPC in .Net Core
  1. DZone
  2. Coding
  3. Languages
  4. Easy JavaScript Part 13: Four Ways to Create Objects in JavaScript

Easy JavaScript Part 13: Four Ways to Create Objects in JavaScript

We continue our exploration of the ins and outs of JavaScript, by taking a look at the several ways devs can create objects.

Dhananjay Kumar user avatar by
Dhananjay Kumar
·
Dec. 04, 17 · Tutorial
Like (6)
Save
Tweet
Share
79.45K Views

Join the DZone community and get the full member experience.

Join For Free

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:

function Car(model, color) {
    this.model = model;
    this.color = color;
}

var c1 = new Car('BMW', 'red');
console.log(c1.model);

This method of creating an object is also called the Constructor Invocation Pattern. There are two steps to work with the constructor function:

  1. Create a function, which will define the object type.
  2. Create an instance of an object using a new operator.

To create a Student object, first, create a function as shown below. In this example, this represents the object being created, so name and age will be properties of the newly created object.

function Student(name, age) {
    this.name = name;
    this.age = age;
}

Next, create instances of the Student object type as shown below:

var s1 = new Student('foo', 7);
console.log(s1.name);
var s2 = new Student('koo', 9);
console.log(s2.name);

You can use the instanceof operator to find types of the instance and determine whether s1 is an instance of the Student object, as shown below:

var s1 = new Student('foo', 9);
console.log(s1 instanceof Student);

You can also use Object.defineProperty to create properties in the constructor function, as shown below:

function Car(model) {
    Object.defineProperty(this, "model", {
        writable: true,
        enumerable: true,
        configurable: false,
        value: model
    });
}

var myCar = new Car("Audi A3");
console.log(myCar.model);    // Audi  A3

The main advantage of using Object.defineProperty is that you can set values for object property descriptors. You can learn more about Object Property Descriptors here.

Object.create Method

You can also create new objects using the Object.create() method, which allows you to specify the prototype object and the properties. For example:

var Car = {
    model: 'BMW',
    color: 'red'
}

You can use the Car object as a prototype to create another object, as shown below:

var ElectricCar = Object.create(Car);
console.log(ElectricCar.model); // BMW

In this example, you have created an object called ElectricCar using the Car  object as a prototype, so the ElectricCar object will have all the properties of the Car object. You can also add properties as shown below:

var ElectricCar = Object.create(Car, {
    type: {
        value: 'Electric',
        writable: true,
        configurable: false,
        enumerable: true
    }
});
console.log(ElectricCar.type); // Electric

Properties should be passed as objects and can be set using the property descriptor. You can also use the Object.create method to create inheritance between objects.

Class

ECMAScript 6 introduced the class keyword to create classes in JavaScript. Now you can use the class attribute to create a class in JavaScript instead of a function constructor, and use the new operator to create an instance. Consider the following code:

class Car {

    constructor(maker, price) {
        this.maker = maker;
        this.price = price;
    }

    getInfo() {
        console.log(this.maker + " costs : " + this.price);
    }
}

You can use the Car class to create objects as shown below:

var car1 = new Car("BMW", 100);
car1.getInfo();
var car2 = new Car("Audi", 150);
car2.getInfo();

You can learn more about class here.

Conclusion

There are four ways to create an object in JavaScript - using object literals, using the function constructor, using the Object.create method, and using the class keyword (which is almost the same as using a function constructor). The Object.create method is very useful when you need to create an object using an existing object as a prototype.

In the next post, we will dive into other aspects of JavaScript! 

Object (computer science) JavaScript Property (programming)

Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Logging Best Practices Revisited [Video]
  • Playwright JavaScript Tutorial: A Complete Guide
  • What Is Test Pyramid: Getting Started With Test Automation Pyramid
  • Build a Simple Chat Server With gRPC in .Net Core

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: