javascript

Creating An Object


There are various ways to creae an object in JavaScript.

 

Creating An Object:

 

1. Using Object Literals:

It is the simplest way to create an object just by using object literal notation `{}`.
 

// object notation-{}
let person = {
    name: "Wasif",
    age: 23,
    city: "India"
};

 

2. Using object Constructor:

We can create an object through the object constructor.

 

// object constructor
let person = new Object();
person.name = "Wasif";
person.age = 23;
person.city = "India";

 

3. Using function Constructor:

We also create a object by using function Constructor.
 

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

let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");

 

4. Using ES6 Classes:

Now JavaScript also supports class bases syntax for creating object.
 

// ES6 classes
class Person {
    constructor(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
}

let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");