An object in JavaScript is a collection of key-value pairs where keys are properties and values can be any data type. JavaScript provides several ways to create objects, including object literals, constructor functions, Object.create(), and ES6 classes.
- Object literals provide the simplest way to create an object.
- Constructor functions and classes are useful for creating multiple similar objects.
- Object.create() creates an object with a specified prototype.
Approach 1: Using Object Literals
Object literals provide the simplest and most common way to create an object in JavaScript. Properties are defined as key-value pairs inside curly braces {}.
const car = {
name: "GT",
maker: "BMW",
engine: "1998cc"
};
console.log(car.name);
console.log(car["maker"]);
Output
GT BMW
Here, dot notation and bracket notation are used to access object properties.
You can also add properties and methods after creating the object:
const car = {
name: "GT",
maker: "BMW",
engine: "1998cc"
};
// Add a property
car.brakesType = "All Disc";
// Add a method
car.start = function () {
console.log("Starting the engine...");
};
console.log(car);
car.start();
Output
{
name: 'GT',
maker: 'BMW',
engine: '1998cc',
brakesType: 'All Disc',
start: [Function (anonymous)]
}
Starting the engine...
Approach 2: Using Constructor Functions
A constructor function can be used with the new keyword to create multiple objects with the same structure.
function Vehicle(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
const car = new Vehicle("GT", "BMW", "1998cc");
console.log(car.name);
console.log(car.maker);
console.log(car.engine);
Output
GT BMW 1998cc
- The constructor function defines the object's properties.
- The new keyword creates a new object from the constructor.
- Multiple objects can be created using the same constructor.
Approach 3: Using Object.create()
The Object.create() method creates a new object using an existing object as its prototype. This allows the new object to inherit properties and methods from the prototype.
const coder = {
isStudying: false,
printIntroduction() {
console.log(
`My name is ${this.name}. Am I studying?: ${this.isStudying}`
);
}
};
const me = Object.create(coder);
me.name = "Mike";
me.isStudying = true;
me.printIntroduction();
Output
My name is Mike. Am I studying?: true
Here, me inherits the printIntroduction() method from coder.
Approach 4: Using ES6 Classes
ES6 classes provide a structured syntax for creating objects and are commonly used when working with object-oriented programming.
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
}
const car = new Vehicle("GT", "BMW", "1998cc");
console.log(car.name);
console.log(car.maker);
console.log(car.engine);
Output
GT BMW 1998cc
- The class defines the structure and behavior of objects.
- The constructor() initializes object properties.
- The new keyword creates an instance of the class.