5 Ways to Create Objects in JavaScript

1. Object Literal

This is the simplest way to create an object in JavaScript. You define key-value pairs within curly braces {}.

const obj = { key: value };

2. Constructor Functions

Constructor functions are traditional functions used to initialize objects. Inside the constructor function, you assign properties using this keyword.

You create instances of objects using the new keyword.

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

const person1 = new Person("John", 30);

3. Object.create() method

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

It allows us to create objects with a specified prototype, which can be useful for prototypal inheritance.

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten

me.printIntroduction();
// output: "My name is Matthew. Am I human? true"

4. Class Syntax (introduced in ES6)

Classes are syntactical sugar over JavaScript's existing prototype-based inheritance.

They provide a more familiar and convenient syntax for creating objects and dealing with inheritance. Under the hood, classes are still based on prototypes.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const person1 = new Person("John", 30);

5. Factory Functions

Factory functions are functions that return objects.

They encapsulate the object creation process and allow you to create multiple instances with different initializations. They are useful for creating similar objects without the need for a constructor function.

function createPerson(name, age) {
  return {
    name: name,
    age: age,
  };
}

const person1 = createPerson("John", 30);

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda