How to Create Objects in Javascript

There are several ways to create JavaScript objects:

1. Object Literals

const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  }
}

Benefits

Downsides

2. Object.create()

const person = Object.create(null);
person.name = 'John';
person.age = 30;

Benefits

Downsides

3. Factory Functions

function createPerson(name, age) {
  return {
    name,
    age,
    sayHello() {
      console.log(`Hello, my name is ${this.name}.`);
    }
  };
}

const john = createPerson('John', 30);

Benefits

Downsides

4. Constructor functions

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

const john = new Person('John', 30);

Benefits

Downsides

5. Prototype

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

const john = new Person('John', 30)

Benefits

Downsides

6. Class syntax

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

const john = new Person('John', 30);

Benefits

Downsides