How to Create a New Instance of an Object in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a new instance of an object in several ways, including using the object literal notation, the Object constructor, and constructor functions.

Here’s an example using object literal notation:

let obj = {};

console.log(obj); // Output: {}

Here’s an example using the Object constructor:

let obj = new Object();

console.log(obj); // Output: {}

And here’s an example using a constructor function:

function MyObject() { = 42;

let obj = new MyObject();

console.log(obj); // Output: {property: 42}

In the last example, the MyObject function is a constructor function that creates an object with a property key-value pair. When you use the new keyword, a new instance of the MyObject object is created and assigned to the variable obj.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply