JAVASCRIPT Tutorial

Creating Objects in JS

Object Literal

  • An object literal is a way to create an object by listing its properties and values directly.
  • Syntax:
const object = { property1: value1, property2: value2, ... };

Constructor Function

  • A constructor function is a special function that is used to create and initialize objects.
  • The new keyword is used to call a constructor function and create an object.
  • Syntax:
function ConstructorFunction() {
  // Object properties and methods
}

const object = new ConstructorFunction();

Class

  • A class is a syntactic sugar for creating objects in a more structured way.
  • Classes use constructor functions to create objects, but they also provide additional features such as inheritance and encapsulation.
  • Syntax:
class ClassName {
  constructor() {
    // Object properties and methods
  }
}

const object = new ClassName();

new Keyword

  • The new keyword is an operator that creates a new object and sets its properties and methods.
  • It calls the constructor function and sets the this keyword to the newly created object.
  • Syntax:
const object = new ConstructorFunction();

Example

// Object Literal
const person = { name: "John", age: 30 };

// Constructor Function
function Person(name, age) {
  this.name = name;
  this.age = age;
}
const person2 = new Person("Jane", 25);

// Class
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
const person3 = new Person("Bob", 40);