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.
You can create an object using the object literal syntax, which involves enclosing key-value pairs within curly braces {}.
// Creating an object using object literal syntax
let Human = {
name: "Rohit",
age: 25,
city: "India"
};
You can create an object using the Object constructor and adding properties and methods to it.
// Creating an object using the Object constructor
let Human = new Object();
Human.name = "Altaf";
Human.age = 24;
Human.city = "German";
We can use the Object.create() method to create a new object with a specified prototype object and properties.
// 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";
You can use the ES6 class syntax to create objects with constructors and methods.
// 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");