Creating Objects

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

Common Object Creation Methods
MethodDescription
Object LiteralDefine an object with curly braces {} and key-value pairs.
Object ConstructorUse new Object() to create an empty object, then add properties.
Constructor FunctionCreate 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

JAVASCRIPT
const person = {
  name: "Alice",
  age: 30,
  greet: function() {
    console.log("Hello, " + this.name);
  }
};

person.greet();
Output
Hello, Alice

2. Object Constructor

Create an empty object, then add properties dynamically.

📌 Deep Dive: Using new Object()

JAVASCRIPT
const car = new Object();
car.make = "Toyota";
car.year = 2021;

console.log(car.make);
Output
Toyota

3. Constructor Function

Create a reusable blueprint for objects. Use new keyword to create instances.

📌 Deep Dive: Constructor Function Example

JAVASCRIPT
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();
Output
Buddy says woof!
Illustration of creating_objects
Illustration of creating_objects

💡 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

JAVASCRIPT
const animal = {
  eats: true,
  walk() {
    console.log("Walking...");
  }
};

const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.eats); // inherited property
rabbit.walk();
Output
true
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.