In JavaScript, objects are collections of related data and functionality. Creating objects allows you to group variables (properties) and functions (methods) together.
Ways to Create Objects
| Method | Description |
|---|---|
| Object Literal | Define an object with curly braces {} and key-value pairs. |
| Object Constructor | Use new Object() to create an empty object, then add properties. |
| Constructor Function | Create a function to initialize new objects with new. |
| Object.create() | Create a new object with a specified prototype object. |
1. Object Literal
The simplest and most common way to create objects.
📌 Deep Dive: Object Literal Syntax
const person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet();
2. Object Constructor
Create an empty object, then add properties dynamically.
📌 Deep Dive: Using new Object()
const car = new Object();
car.make = "Toyota";
car.year = 2021;
console.log(car.make);
3. Constructor Function
Create a reusable blueprint for objects. Use new keyword to create instances.
📌 Deep Dive: Constructor Function Example
function Dog(name, breed) {
this.name = name;
this.breed = breed;
this.bark = function() {
console.log(this.name + " says woof!");
};
}
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.bark();

💡 Important
When using constructor functions, always use new to create objects. Omitting new can cause unexpected behavior.
4. Object.create()
Create a new object with a specified prototype, useful for inheritance.
📌 Deep Dive: Object.create() Usage
const animal = {
eats: true,
walk() {
console.log("Walking...");
}
};
const rabbit = Object.create(animal);
rabbit.jumps = true;
console.log(rabbit.eats); // inherited property
rabbit.walk();
Walking...
⚠️ Common Pitfall
Do not confuse the Object.create() method with constructor functions. Object.create() directly sets the prototype, while constructors initialize new objects.
Summary
- Object Literal: Quick and easy syntax.
- Object Constructor: Create empty objects and add properties.
- Constructor Function: Blueprint for multiple similar objects.
- Object.create(): Create objects with a given prototype chain.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method creates an object with a specified prototype?
Question 2 of 2
What keyword do you use to create an instance from a constructor function?
Loading results...