DEV Community

Pcoch
Pcoch

Posted on • Edited on

4 Ways to create an object in JS

I often get tripped up learning something new when there are many ways to achieve the same outcome.

A recent example of this I experienced was learning how to create Objects in JS.

There are several ways to create objects in JavaScript, and here are 4. My personal preference is to use the Object constructor.

Using the Object constructor:

You can use the Object constructor to create an empty object and then add properties to it. For example:

object constructor

Using object literals

You can use object literals to create objects with properties directly. For example:

object literal

Using the Object.create method

You can use the Object.create method to create an object that has a specified prototype. For example:

let obj = Object.create(Object.prototype)
obj.name = 'John'
obj.age = 30
Enter fullscreen mode Exit fullscreen mode

Using class syntax

You can use class syntax to define a class and then create objects from that class using the new operator. For example:

class syntax


A good way to learn is to play around in the console or something like RunJS to get a feel for each approach.

Top comments (0)