What are the various ways to create objects in JavaScript?
Answer
Objects in JavaScript can be created in several ways:
- Object Literals:
const obj = { key: 'value' };
- Object.create():
const obj = Object.create(proto);
- Constructor Functions:
function Obj() {
this.key = 'value';
}
const obj = new Obj();
- ES6 Classes:
class Obj {
constructor() {
this.key = 'value';
}
}
const obj = new Obj();
- Using new Object():
const obj = new Object();
obj.key = 'value';
- Factory Functions:
function createObj() {
return { key: 'value' };
}
const obj = createObj();