HomeJAVASCRIPTDifference between object literal and constructor function.

Difference between object literal and constructor function.

1. Object Literal

An object literal is the simplest way to create an object in JavaScript.
You directly define the object and its properties in curly braces {}.

// Object Literal
const person = {
  name: "John",
  age: 25,
  greet: function () {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet(); // Hello, my name is John

🔹 Key Points:

  • Quick and easy to create.
  • All properties and methods are defined inline.
  • Creates a single object instance.
  • No reusable “template” for multiple objects.

2. Constructor Function

A constructor function is a special function used to create multiple objects of the same “type.”
By convention, the function name starts with a capital letter.

// Constructor Function
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function () {
    console.log("Hello, my name is " + this.name);
  };
}

const person1 = new Person("Alice", 30);
const person2 = new Person("Bob", 40);

person1.greet(); // Hello, my name is Alice
person2.greet(); // Hello, my name is Bob

🔹 Key Points:

  • Used with the new keyword.
  • Each call creates a new object instance.
  • Makes it easy to create multiple similar objects.
  • Common behavior can be moved to Person.prototype to save memory.

Main Differences

FeatureObject LiteralConstructor Function
CreationDefined directly with {}Defined with a function + new
ReusabilityNot reusable (creates one object only)Can create multiple objects
SyntaxSimple and shortMore verbose
Use CaseSingle, simple objectsMultiple objects of same type (blueprint)

✅ Summary:

  • Use object literals for one-off objects.
  • Use constructor functions (or modern class) when you need a reusable blueprint for creating many similar objects.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *