All the ways you can create an object in JavaScript

All the ways you can create an object in JavaScript

Learn every way to create objects in JavaScript. Also, learn all the ways to define a property in an object.

In JavaScript, there are methods you can use to create an object.

  1. Object literals
  2. Object.create
  3. new operator or constructor
  4. Class keyword

Let's go through each of these methods and know how the objects are created.

Object literals

Object literals are the most common way a newbie learns how to create an object in JavaScript. It is a pair of curly braces {}, an opening, and a closing curly brace. It is also known as an Object initializer. It is a comma-separated set of key-value pairs. Here's how you create an object literal:

const person = {
  firstName: 'Steve',
  age: 27,
}

We store data in an object using properties. You can dynamically add properties even after you have initialized an object. We can assign properties in four different ways:

  • dot notation

Use the name of the object followed by a dot notation and then whatever the property you want to create.

person.lastName = 'Rogers'
  • Square bracket notation

We can also use a square bracket to assign a value to a dynamic property.

person['bestFriend'] = 'Bucky'
  • Object.defineProperty Method

The third way we can create properties uses the Object.defineProperty method. This was introduced with ECMAScript 5 but you can still find good support for this method in older browsers. This method accepts three arguments:

  1. The object that we need to create the property on.
  2. Second, is the string containing the name of the property that needs to be created.
  3. Descriptor object gives us a variety of options that we can use to set the value of a particular property. For example, we can make it writable or we can make it read-only. We can also make it enumerable or configurable. We can also use getters and setters.
Object.defineProperty(person, 'country', {
  value: 'USA',
});
  • Object.defineProperties

It is very similar to defineProperty. As its name implies, it allows us to create multiple properties on an object. The first argument is the object on which we need to apply the properties on. The second argument is another object that contains multiple object descriptors.

Object.defineProperties(person, {
  twitter: {
    value: 'firstAvenger',
  },
  email: {
    value: 'first@avenger.com'
  }
})

If you want to create read-only property then feel free to use the defineProperty and defineProperties methods. However, often we create a property and assign it a value in which case the dot and square bracket notation work well

Object.create()

Another way we can create objects in JavaScript is by using the create method. This was introduced in ECMAScript 5. And we use it by calling Object.create(). This is considerably longer than an object literal. But we gain a lot of power with this method. Because it allows us to create objects that are based upon other objects. The Object.prototype is equivalent to passing a foo object literal.

const foo = {};

const bar = Object.create(Object.prototype)

Let's say we have a more complex object.

const firstChemist = {
  firstName: 'Heisenberg',
  sayMyName: function() {
    return `My name is ${this.firstName}. You are goddamn, right.`
  },
};

Now technically JavaScript does not have methods. It has properties that contain a function object.

Now we have a firstChemist. Now we want secondChemist that also has a firstName property as well as a sayName method. Of course, we can copy-paste this code and make the necessary modifications or we could use the create method and use our firstChemist as a basis.

const secondChemist = Object.create(firstChemist, {
  firstName: { value: 'Jesse' }
});

We will send the firstChemist as the first argument, but also will set the new values for the firstName properties, otherwise, our secondChemist object will be the firstName of Heisenberg. So really, all we need to change is the firstName property. So we can pass a second argument, that contains all of our properties and these properties are object descriptors. The secondChemist sayName method will console log 'My name is Jesse. You are goddamn right.'

console.log(firstChemist.sayMyName());
console.log(secondChemist.sayMyName());

Screenshot 2021-10-15 at 5.13.23 PM.png

What the Object.create method does is create a prototype chain. The object that you pass as the first argument is set as a prototype for whatever object you are creating.

So the secondChemist's object prototype is firstChemist.

Constructor function or new operator

Another way that we can create an object is by using a constructor function. This is a special function that we call with the new keyword.

We use the function keyword followed by name of the function. Our name of the function start's with an Uppercase letter. This is to distinguish a constructor function from other normal functions. A constructor does not have to have any parameters but if you need to supply information to a constructor then you can have parameters as stated below.

Inside of a constructor function we use the this keyword to refer to the object that we are creating.

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.sayName = function() {
    console.log(`My name is ${this.firstName} ${this.lastName}`);
  }
}

const steveRogers = new Person('Steve', 'Rogers');
const tonyStark = new Person('Tony', 'Stark');

Class keyword

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. After checking all the three methods to create an object ES6 gave us a short and sweet way to create classes. Let's convert the above example code into a class syntax.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  sayName() {
    console.log(`My name is ${this.firstName} ${this.lastName}`);
  }
}

const steveRogers = new Person('Steve', 'Rogers');
const tonyStark = new Person('Tony', 'Stark');

Conclusion

So we learned about the four ways one can create objects in JavaScript - by using object literals, constructor function, Object.create, and the class keyword(which is almost the same as using constructor function). Object.create method is useful when you need to create an object using an existing object as a prototype.