Difference between an Object Constructor and an Object Literal in Javascript

Object Constructor:

  • An object constructor is a function that is used to create new objects.
  • You define an object constructor function and then create new instances of that object using the new keyword.
  • Constructor functions can have properties and methods that can be accessed by the object instances they create.
  • Constructors can also inherit properties and methods from their prototypes.

 
function Person(name, age) {
    this.name = name;
    this.age = age;
  }
  
  let person1 = new Person('John', 30);
  

Object Literal:

  • An object literal is a way of creating an object by defining it as a comma-separated list of name-value pairs within curly braces.
  • The object is created directly and does not require a constructor function.
  • The properties and methods of an object literal are unique to the single instance of the object.
  • Object literals cannot inherit properties or methods from other objects.

let person2 = {
    name: 'Jane',
    age: 25,
    sayHi: function() {
      console.log('Hi there!');
    }
  };

The primary difference between object constructors and object literals is that object constructors allow you to create multiple instances of an object with shared properties and methods, while object literals create a single instance of an object with its own unique properties and methods.