JavaScript(JS) JS create objects in different ways

In JavaScript, there are several ways to create objects:

  1. Object Literal Notation: This is the simplest and most common way to create an object. It involves defining an object with key-value pairs enclosed in curly braces.
re‮ ref‬to:theitroad.com
const person = {
  name: 'John',
  age: 30,
  gender: 'male',
  sayHello: function() {
    console.log('Hello, my name is ' + this.name);
  }
};
  1. Constructor Function: This involves defining a function that will act as a template for creating objects. The new keyword is used to create instances of the object.
function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
  this.sayHello = function() {
    console.log('Hello, my name is ' + this.name);
  };
}

const person1 = new Person('John', 30, 'male');
  1. Object.create(): This involves using the Object.create() method to create an object and setting its prototype to another object.
const personProto = {
  sayHello: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

const person = Object.create(personProto);
person.name = 'John';
person.age = 30;
person.gender = 'male';
  1. Class Syntax: This involves defining a class with the class keyword and creating objects using the new keyword.
class Person {
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  
  sayHello() {
    console.log('Hello, my name is ' + this.name);
  }
}

const person1 = new Person('John', 30, 'male');

All of the above methods create objects, but they differ in their syntax and use cases. The choice of method will depend on the specific needs of your application.