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
newkeyword. - Each call creates a new object instance.
- Makes it easy to create multiple similar objects.
- Common behavior can be moved to
Person.prototypeto save memory.
Main Differences
| Feature | Object Literal | Constructor Function |
|---|---|---|
| Creation | Defined directly with {} | Defined with a function + new |
| Reusability | Not reusable (creates one object only) | Can create multiple objects |
| Syntax | Simple and short | More verbose |
| Use Case | Single, simple objects | Multiple 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.
