Different ways to create Objects in Javascipt

imranshaik012

Imran Shaik

Posted on November 19, 2024

Different ways to create Objects in Javascipt

There are multiple ways to create an objects in javascript.

1. Object Literals: This is the simplest way to create an object in javascript

const obj = {
      name: "John", 
      age: 30,
      greet: function(){
      console.log("Object Literal Example")
}
}
Enter fullscreen mode Exit fullscreen mode

2. Using Object Constructor: Create an Object using the Object Constructor

const obj = new object();
obj.name = "john";
obj.age = 30;
obj.greet = function(){
   console.log("Object Creation using Object Constructor");
}

Enter fullscreen mode Exit fullscreen mode

3. Using Constructor Function:
Define a custom constructor function and use it to create an objects

function person(name, age){
  this.name= name;
  this.age = age;
  this.greet = function(){
  console.log(`Hello this object creation using constructor function ${this.name}`);
};
}
const john = new Person("John", 30)
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
imranshaik012
Imran Shaik

Posted on November 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related