JAVASCRIPT

Set Object Type


Setting an object in JavaScript involves defining and initializing an instance of an object, which is a composite data type representing a collection of key-value pairs.

This can be achieved using various methods, including object literal syntax, the Object constructor, Object.create() method, or ES6 class syntax.

 

1. Object Literal Syntax:

You can create an object using the object literal syntax, which involves enclosing key-value pairs within curly braces {}.

 

Example:

// Creating an object using object literal syntax
let Human = {
    name: "Rohit",
    age: 25,
    city: "India"
};

 

2. Using the Object Constructor:


You can create an object using the Object constructor and adding properties and methods to it.

 

Example:

// Creating an object using the Object constructor
let Human = new Object();
Human.name = "Altaf";
Human.age = 24;
Human.city = "German";

 

3. Using Object.create():

We can use the Object.create() method to create a new object with a specified prototype object and properties.

 

Example:

// Creating an object using Object.create()
let HumanPrototype = {
    name: "",
    age: 0,
    city: ""
};
let Human = Object.create(HumanPrototype);
Human.name = "Wasif";
Human.age = 30;
Human.city = "Egypt";

 

4. Using ES6 Class Syntax:

You can use the ES6 class syntax to create objects with constructors and methods.

 

Example:


// Creating an object using ES6 class syntax
class Human {
    constructor(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
}
let Human = new Human("Shoaib", 23, "UAE");