In JavaScript, there are several ways to create a new object:
-
Object literal notation:
You can create an object using curly braces
{}
and adding key-value pairs separated by colons:
.For example:
const car = { model: "S", avg_speed: 60, };
-
Constructor function:
You can create an object using a constructor function, which is a special function that creates and initializes objects.
For example:
function Car(model, avg_speed) { this.model = model; this.avg_speed = avg_speed; } const car = new Car("S", 60);
-
Object.create() method:
You can create an object using the
Object.create()
method, which creates a new object with the specified prototype object and properties.For example:
const car = Object.create(null); car.model = "S"; car.avg_speed = 60;
-
Class syntax:
You can create an object using the class syntax, which is a new way to define objects in JavaScript introduced in ECMAScript 6.
For example:
class Car { constructor(model, avg_speed) { this.model = model; this.avg_speed = avg_speed; } } const car = new Car(model, avg_speed);
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.