For more questions and answers visit our website at Frontend Interview Questions

In JavaScript, an object is a fundamental data type that represents a collection of key-value pairs. Objects in JavaScript can encapsulate both primitive data types (like strings, numbers, booleans) and other objects, making them powerful and flexible data structures.

An object is defined using curly braces {}, and each key-value pair inside the object is separated by a colon :. The key represents a unique identifier, while the value can be any valid JavaScript data type, including other objects or functions.

Ways to create object

  1. Simple function

function vehicle(name,maker,engine){ 
    this.name = name; 
    this.maker = maker; 
    this.engine = engine; 
} 
//new keyword to create an object 
let car  = new vehicle('GT','BMW','1998cc'); 
//property accessors 
console.log(car.name);

2. Creating JS Objects with object literal


//creating js objects with object literal 
let car = { 
    name : 'GT', 
    maker : 'BMW', 
    engine : '1998cc'
};

3. Creating object with Object.create() method:

The Object.create() method in JavaScript is utilized to create a new object, and it takes an existing object as a parameter to serve as the prototype for the newly generated object. This process enables inheritance, where the new object inherits properties and methods from its prototype. Example:


const coder = { 
 isStudying : false, 
 printIntroduction : function(){ 
  console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}`); 
 } 
}; 
const me = Object.create(coder); 
me.name = 'Mukul'; 
me.isStudying = true; 
me.printIntroduction();

4. Using ES6 Classes


//using es6 classes 
class Vehicle { 
  constructor(name, maker, engine) { 
    this.name = name; 
    this.maker =  maker; 
    this.engine = engine; 
  } 
} 
  
let car1 = new Vehicle('GT', 'BMW', '1998cc'); 
  
console.log(car1.name);  //GT