MSDN Documentation

Learn and Explore

JavaScript Objects: The Building Blocks of Your Applications

Objects are fundamental in JavaScript. They are collections of properties, where each property is a name-value pair. These properties can be primitive data types (like strings, numbers, booleans), other objects, or even functions.

What is a JavaScript Object?

Think of an object as a real-world entity. For example, a "car" object could have properties like:

Creating a Simple Object


const car = {
    color: "blue",
    make: "Honda",
    model: "Civic",
    year: 2022,
    isElectric: false,
    startEngine: function() {
        console.log("Engine started!");
    }
};
            

Accessing Object Properties

You can access an object's properties using dot notation (.) or bracket notation ([]).

Accessing Properties


console.log(car.color);      // Output: blue
console.log(car['make']);    // Output: Honda
console.log(car.year);       // Output: 2022

// You can also access methods
car.startEngine();           // Output: Engine started!
            

Modifying Object Properties

Object properties are mutable. You can change their values or add new properties after the object has been created.

Modifying and Adding Properties


// Modify an existing property
car.color = "red";
console.log(car.color);      // Output: red

// Add a new property
car.mileage = 15000;
console.log(car.mileage);    // Output: 15000

// Add a new method
car.honk = function() {
    console.log("Beep beep!");
};
car.honk();                  // Output: Beep beep!
            

The `this` Keyword in Objects

Inside an object's method, the this keyword refers to the object itself. This is crucial for creating dynamic and self-aware objects.

Using `this`


const person = {
    firstName: "Jane",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

console.log(person.fullName()); // Output: Jane Doe
            

Object Literals vs. Constructors

While object literals are great for creating individual objects, JavaScript also provides constructor functions and classes for creating multiple objects with similar structures and behaviors.

Constructor Functions

A constructor function is a regular function that is used to create new objects. The keyword new is used to instantiate an object from a constructor.

Constructor Function Example


function Book(title, author, yearPublished) {
    this.title = title;
    this.author = author;
    this.yearPublished = yearPublished;
    this.getInfo = function() {
        return `${this.title} by ${this.author} (${this.yearPublished})`;
    };
}

const book1 = new Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979);
const book2 = new Book("Pride and Prejudice", "Jane Austen", 1813);

console.log(book1.getInfo()); // Output: The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)
console.log(book2.title);     // Output: Pride and Prejudice
            

JavaScript Classes (ES6+)

Classes provide a cleaner syntax for creating constructor functions and managing inheritance. They are syntactic sugar over JavaScript's existing prototype-based inheritance.

Class Example


class Animal {
    constructor(name, species) {
        this.name = name;
        this.species = species;
    }

    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name, "Canine"); // Call the parent constructor
        this.breed = breed;
    }

    speak() {
        console.log(`${this.name} barks.`);
    }

    fetch() {
        console.log(`${this.name} is fetching the ball.`);
    }
}

const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.name);      // Output: Buddy
console.log(myDog.species);   // Output: Canine
myDog.speak();                // Output: Buddy barks.
myDog.fetch();                // Output: Buddy is fetching the ball.
            

Key Concepts to Remember

Mastering JavaScript objects is essential for building dynamic and interactive web applications. Continue practicing and exploring different ways to use them!