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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Immutability in JavaScript — When and Why Should You Use It
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript

Trending

  • DZone's Article Submission Guidelines
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Enterprise-Grade Distributed JMeter Load Testing on Kubernetes: A Scalable, CI/CD-Driven DevOps Approach
  • How You Can Use Few-Shot Learning In LLM Prompting To Improve Its Performance
  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.

By 
Dhananjay Kumar user avatar
Dhananjay Kumar
·
Dec. 04, 17 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
82.6K 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.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Immutability in JavaScript — When and Why Should You Use It
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: