DeployU
Interviews / Frontend Engineering / What are the different ways to create an object in JavaScript?

What are the different ways to create an object in JavaScript?

conceptual Object-Oriented Programming Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are writing a new feature that needs to create a new object.

You are not sure which of the different ways to create an object in JavaScript you should use.

The Challenge

Explain the different ways to create an object in JavaScript. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might only be aware of one way to create an object, such as using an object literal. They might not be aware of the other ways to create an object or the trade-offs between them.

Right Approach

A senior engineer would be able to provide a detailed explanation of all the different ways to create an object in JavaScript. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.

Step 1: Understand the Different Ways to Create an Object

MethodDescription
Object LiteralThe simplest way to create an object.
new KeywordCreates a new object and sets its prototype to the constructor function’s prototype.
Object.create()Creates a new object with the specified prototype object and properties.
class KeywordSyntactic sugar on top of prototypal inheritance.

Step 2: Choose the Right Tool for the Job

Use CaseRecommended Method
Creating a simple objectObject Literal
Creating an object with a constructornew Keyword
Creating an object with a specific prototypeObject.create()
Creating a complex object with methodsclass Keyword

Step 3: Code Examples

Here are some code examples that show the difference between the different approaches:

Object Literal:

const myObject = {
  myProperty: 'myValue'
};

new Keyword:

function MyClass() {
  this.myProperty = 'myValue';
}

const myObject = new MyClass();

Object.create():

const myPrototype = {
  myMethod() {
    console.log('hello');
  }
};

const myObject = Object.create(myPrototype);

class Keyword:

class MyClass {
  constructor() {
    this.myProperty = 'myValue';
  }

  myMethod() {
    console.log('hello');
  }
}

const myObject = new MyClass();

Practice Question

You want to create a new object that inherits from another object. Which of the following would you use?