Academic Block

JavaScript Objects Get Certified

Objects are one of the core building blocks of JavaScript. They let you group related data and behavior together using key-value pairs.

In this lesson, you will learn how to create objects, access and update their properties, define methods, work with nested data, and use helpful built-in methods like Object.keys(), Object.values(), and Object.entries().

Creating Objects

The most common way to create an object is with an object literal — curly braces containing properties.

What this code does: An object literal creates a new object with key-value pairs. You can mix different value types (strings, numbers, booleans) in the same object.

const book = {
    title: "The Silent River",
    author: "Maya Chen",
    pages: 312,
    isAvailable: true
};
console.log(book);

Accessing Properties

You can read a property with dot notation or bracket notation.

What this code does: Dot notation is the usual way to read a property. Bracket notation is useful when the key is stored in a variable or contains special characters.

const car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2021
};
console.log(car.brand);
console.log(car["model"]);
const key = "year";
console.log(car[key]);

Adding and Updating Properties

You can add new properties or change existing ones at any time.

What this code does: Assigning to a property updates it if it exists, or creates it if it doesn’t. Both color and the updated year appear when the object is logged.

const phone = {
    brand: "Samsung",
    model: "Galaxy S23"
};
phone.color = "black";
phone.year = 2023;
console.log(phone);

Deleting Properties

The delete operator removes a property from an object.

What this code does: delete removes a property completely. After deletion, the key no longer exists on the object.

const user = {
    name: "Alex",
    age: 29,
    tempToken: "xyz-123"
};
delete user.tempToken;
console.log(user);

Methods

When a property’s value is a function, it is called a method.

What this code does: A method is a function stored as a property. Calling greeter.sayHello() runs the function and prints the greeting.

const greeter = {
    sayHello: function () {
        console.log("Hello from the object!");
    }
};
greeter.sayHello();

Method Shorthand

Modern JavaScript lets you write methods more concisely by omitting the function keyword.

What this code does: Method shorthand omits the function keyword. checkAvailability() is cleaner and behaves the same as the longer form.

const library = {
    booksInStock: 128,
    checkAvailability() {
        return this.booksInStock > 0;
    }
};
console.log(library.checkAvailability());

Using this Inside Methods

Inside a regular method, this refers to the object the method was called on, letting you access that object’s other properties.

What this code does: Methods can update the object’s own state via this. Spending 50 reduces the balance; trying to spend 500 returns an insufficient-funds message.

const wallet = {
    balance: 200,
    spend(amount) {
        if (amount > this.balance) {
            return "Insufficient funds";
        }
        this.balance -= amount;
        return "New balance: " + this.balance;
    }
};
console.log(wallet.spend(50));
console.log(wallet.spend(500));

Nested Objects

An object’s property value can itself be another object, allowing you to model more complex, structured data.

What this code does: Objects can contain other objects (nesting). Access nested values by chaining: employee.address.city.

const employee = {
    name: "Priya Nair",
    department: "Engineering",
    address: {
        city: "Austin",
        state: "TX"
    }
};
console.log(employee.address.city);

Checking If a Property Exists

The in operator checks whether a property exists on an object, and hasOwnProperty() checks whether it exists directly on the object itself (not inherited).

What this code does: Check whether a property exists with the in operator or hasOwnProperty(). Both return true/false without throwing if the key is missing.

const ticket = {
    eventName: "Jazz Night",
    seatNumber: "12B"
};
console.log("eventName" in ticket);
console.log("price" in ticket);
console.log(ticket.hasOwnProperty("seatNumber"));

Property Shorthand

If a variable’s name matches the property name you want, you can skip repeating it.

What this code does: Property shorthand lets you write { orderId, total } when the variable names match the desired keys. The function returns a compact order object.

function createOrder(orderId, total) {
    return { orderId, total };
}
console.log(createOrder("ORD-501", 89.99));

Computed Property Names

You can use an expression as a property name by wrapping it in square brackets inside an object literal.

What this code does: Computed property names use brackets in the object literal. The value of fieldName becomes the key, so the promo object gets a discountCode property.

const fieldName = "discountCode";
const promo = {
    [fieldName]: "SUMMER25",
    validUntil: "2026-09-01"
};
console.log(promo);

Object.keys(), Object.values(), and Object.entries()

These built-in methods let you extract an object’s keys, values, or both as arrays, which is especially useful for looping over an object’s contents.

What this code does: Object.keys, Object.values, and Object.entries turn an object’s contents into arrays you can inspect or loop over.

const scoreboard = {
    Alice: 92,
    Ben: 87,
    Chloe: 95
};
console.log(Object.keys(scoreboard));
console.log(Object.values(scoreboard));
console.log(Object.entries(scoreboard));

What this code does: Loop over key-value pairs with for...of and Object.entries. Each iteration gives you the name and score to print.

const scoreboard = {
    Alice: 92,
    Ben: 87,
    Chloe: 95
};
for (const [name, score] of Object.entries(scoreboard)) {
    console.log(name + ": " + score);
}

Copying Objects

Simply assigning an object to a new variable copies the reference, not the object itself. To create an actual independent copy, use the spread operator (...) or Object.assign().

What this code does: The spread operator creates a shallow copy. Changing copiedSettings.fontSize does not affect the original object.

const originalSettings = { theme: "dark", fontSize: 14 };
const copiedSettings = { ...originalSettings };
copiedSettings.fontSize = 18;
console.log(originalSettings.fontSize);
console.log(copiedSettings.fontSize);

Note that this creates a shallow copy — if a property’s value is itself an object, both copies will still share a reference to that nested object.

Practical Example

Let’s build a small product catalog entry using several object features together.

What this code does: A factory function builds objects with properties and methods. getTotalValue uses this to multiply price by quantity for the product.

function createProduct(name, price, quantity) {
    return {
        name,
        price,
        quantity,
        getTotalValue() {
            return this.price * this.quantity;
        }
    };
}
const product = createProduct("Wireless Mouse", 25, 40);
console.log(product.getTotalValue());

Common Mistakes With Objects

  • Using an arrow function for a method that needs this to refer to the object.
  • Forgetting that copying an object with = otherObject copies the reference, not the actual data.
  • Using dot notation with a property name that contains spaces or special characters, instead of bracket notation.
  • Assuming a shallow copy also duplicates nested objects, when it only copies references to them.
  • Forgetting quotes around string keys that include spaces or start with a number.

Best Practices for Objects

  • Use const for objects you don’t intend to reassign, since their contents can still be modified.
  • Prefer method shorthand syntax for cleaner object method definitions.
  • Use Object.keys(), Object.values(), or Object.entries() instead of manually looping over properties with for...in.
  • Use the spread operator for simple shallow copies, and a dedicated deep-clone approach when nested objects also need to be copied independently.
  • Keep related data grouped together in an object instead of scattering it across many separate variables.

Quick Summary

  • Objects store data as key-value pairs, created using object literal syntax.
  • Properties can be accessed with dot notation or bracket notation.
  • A property whose value is a function is called a method, and this refers to the object the method belongs to.
  • Object.keys(), Object.values(), and Object.entries() help you work with an object’s contents.
  • Copying an object with = copies a reference; use the spread operator for an actual (shallow) copy.
  • Object property values can be nested objects, arrays, or even other functions.

Try It Yourself

Modify the object below. Try adding a new property, a new method, or looping over its entries with Object.entries().

What this code does: Practice example: add properties or methods, or try Object.entries(), then click Test My Code to see the result.

const recipe = {
    name: "Tomato Soup",
    servings: 4,
    scaleServings(multiplier) {
        return this.servings * multiplier;
    }
};
console.log(recipe.scaleServings(2));
Tip: If you find yourself managing several separate variables that all describe the same “thing” — like a name, price, and quantity for one product — that’s usually a strong signal they belong together in a single object.

Understanding objects is essential before moving on to arrays, classes, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close