Six Ways to Create Objects in JavaScript

Learn six different ways to create an object in JavaScript.

image by Dawid Zawiła

There are multiple ways to create Object in Javascript, I have listed six of them which I learned while reading. So I would like to share that with all JavaScript geeks here.

First Way → Using Assignment

This is how most of us create objects in JavaScript,

var user = {
   name : "Tony",
   age : 50
}

Second Way → Using new operator on function.

function User(name, age) {
  this.name = name
this.age = age;
   this.print = function() {
console.log(`Hi , I am ${this.}`);
};
}

// Create Object
var tony = new User('Tony', 50);
tony.print(); // Hi, I am Tony
// we can also add new properties to tony object
tony.wife = "Pepper pots";

Third Way → Using Object constructor

// Create Object
var user = new Object();
user.name = "Tony";
user.age = 50;

Fourth way → Passing object to Object Constructor

var user = {
name : "Tony",
age : 50
};
var tony = new Object(user);
// Be careful that if we change property of tony it get affected in user object
tony.age = 51;
user.age; // 51

Fifth Way → Using Object create method

var user = {
name : "Tony",
age : 50
};
var tony = Object.create(user);
tony.age; //50
// we can change value , but it is not reflected in source , only if the value is not object
tony.age = 51;
user.age; // 50

Sixth Way → Using ES6 class Syntax

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

sayHi() {
console.log(`Hi 👋 from ${this.name}`);
}
}
var tony = new User("tony", 50);
tony.sayHi(); // Hi 👋 from tony

Thanks for Reading 📖 . Hope you like this. If you found any typo or mistake send me a private note 📝 thanks 🙏 😊 .

Follow me JavaScript Jeep🚙💨 .

Please make a donation here. 98% of your donation is donated to someone needs food 🥘. Thanks in advance.

Leave a comment

Design a site like this with WordPress.com
Get started