What are the possible ways to create objects in JavaScript?
Object: In JavaScript, an object is a standalone entity, with properties and type.
There are a number of ways to create an object in JavaScript:
- Object literal syntax: This is the easiest way to create an object. This syntax wraps a comma-separated set of key-value pairs in curly braces.
const object1 = {
name: 'Sneha Kumari', // property value may be a string
course: 'ICAI', // property key can be an identifier
marks: 70, // property value may be a number
hobbies: ['Painting', 'Singing'], // property value can be an array
"obj key" : {
1: 'mango',
2: 'banana',
} // property value can be an object as well
5: 'Taste' // property key can be a number,
"property new": 30000 // Property key can be a string
};
Object literal property values can be of any data type. Object key literal can be literal, string or number.
- The object's create method (function):
In this syntax, we use the create method of Object to create the object by passing the prototype object as a parameter
const object2 = Object.create(null);
- Function constructor:
In this syntax, we need to create an object which is responsible to create the object.
function Car(name, color) {
this.name = name;
this.color = color;
}
const hyundaiObj = new Car("Hyundai", "Red")
- ES6 Class object syntax:
This syntax is introduced in ECMA Script 6 in which a class is declared with the OOPs concept and we can create a new object in a conventional way using the new keyword.
class Car{
constructor(name) {
this.name = name;
}
}
const object = new Car("Hyundai");
- Object constructor syntax:
In this syntax, we use the new keyword with using Object constructor. This syntax was used in past and is not in use nowadays as well as in a non-recommended way.
const object3 = new Object();