JavaScript

Ways to Create Objects in JavaScript

Last updated: 21.02.2026
Views: 274

There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain other objects.

1. Literal notation

const someObject1 = {};

Perhaps the most common and easiest way. Let’s add properties and methods

someObject1.name = "John";
someObject1.age = 25;
someObject1.run = function() {
    console.log("run");
}

And now the same thing, but we will set properties and methods when creating

const someObject1 = {
    name: "John",
    age: 25,
    run: function() {
        console.log("run");
    }
};

2. Object constructor

This method is not recommended for use, and it is better to use the previous one. Nevertheless, it exists. But the probability of meeting him is extremely small

const someObject2 = new Object();

After that we also set properties and methods.

someObject2.name = "Nick";
someObject2.age = 30;
someObject2.jump = function() {
    console.log("jump");
}

3. Function constructor

We can write our constructor function and create objects using the new operator

function SomeObject3(name, age) {
    this.name = name;
    this.age = age;
}
 
SomeObject3.prototype.run = function() {
    console.log("run");
}

Create an object

const someObject3 = new SomeObject3("Alex", 20);

4. Object.create() method

There is another way to create objects – using the Object.create() method. The first parameter, the required parameter, is the prototype of the created object, and the second optional parameter is the list of object properties. In order to create an object without a prototype, you must call the Object.create() method with the null parameter.

const someObject4 = Object.create(Object.prototype);
 
// the full analogue of Object.create (Object.prototype) is
const otherObject1 = {};
 
//object without prototype
const otherObject2 = Object.create(null);

5. Using classes

ES6 syntax provides writing classes in JavaScript. At its core, this is an analog of the third method – using the constructor function. Only with a simpler and clearer record.

class SomeObject5 {
     
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
 
    run() {
        console.log("run");
    }
}

Let’s now create an object, or more precisely an instance of a class

const someObject5 = new SomeObject5("Alex", 20);
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *