Skip to main content
JavaScript Basics
CHAPTER 11 Beginner

JavaScript Objects

Updated: May 12, 2026
25 min read

# JavaScript Objects

In the real world, an object is a tangible thing—like a car. A car has properties (like weight and color) and methods (like start and stop).

In JavaScript, objects work exactly the same way. They are the most important data type in the language. If you understand objects, you understand JavaScript.

1. Introduction

While arrays are great for lists, Objects are used to store structured data that represents a single entity. Instead of accessing data via numerical indexes ([0], [1]), objects store data in Key-Value pairs. You ask the object for a specific "key", and it gives you the "value".

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Create objects using the Object Literal syntax {}.
  • Access and modify object properties using dot notation and bracket notation.
  • Add methods (functions) to objects.
  • Understand the this keyword inside an object.
  • Iterate over an object's properties.
  • Build a working Product Catalog mini-project.

3. Creating an Object

The easiest way to create an object is using curly braces {}. Inside, you define properties as key: value pairs, separated by commas.

javascript
1234567
// Syntax
const car = {
    brand: "Fiat", // Key: "brand", Value: "Fiat"
    model: "500",
    weight: "850kg",
    color: "white"
};

*Note: Just like arrays, objects are usually declared with const.*

4. Accessing Object Properties

There are two ways to access data inside an object:

  1. 1. Dot Notation: objectName.propertyName (Most common)
  1. 2. Bracket Notation: objectName["propertyName"] (Used when the key name has spaces, or when using variables as keys)

javascript
123
// Example JavaScript
console.log(car.brand);       // Output: Fiat (Dot notation)
console.log(car["color"]);    // Output: white (Bracket notation)

5. Object Methods

Objects can also contain functions. When a function is attached to an object, it is called a Method.

javascript
12345678910
// Syntax
const person = {
    firstName: "John",
    lastName: "Doe",
    sayHello: function() {
        console.log("Hello there!");
    }
};

person.sayHello(); // Output: Hello there!

---

6. Real-world Examples & Code Snippets

Example 1: Creating a User Profile

javascript
123456789
// Example JavaScript
const user = {
    username: "coder99",
    email: "coder99@email.com",
    isActive: true,
    age: 24
};

console.log(user.username);

Example 2: Modifying an Object

You can easily change the value of an existing property, or add a brand new one dynamically.

javascript
1234567891011121314
// Example JavaScript
const settings = {
    theme: "light",
    notifications: true
};

// Modifying an existing property
settings.theme = "dark";

// Adding a brand new property
settings.language = "English";

console.log(settings); 
// Output: { theme: 'dark', notifications: true, language: 'English' }

Example 3: Deleting a Property

You can completely remove a property from an object using the delete keyword.

javascript
12345678910
// Example JavaScript
const employee = {
    name: "Sarah",
    role: "Developer",
    salary: 80000
};

delete employee.salary; // Salary data is removed

console.log(employee.salary); // Output: undefined

Example 4: The this Keyword

Inside an object method, this refers to the object itself. It allows the method to access sibling properties within the same object.

javascript
1234567891011
// Example JavaScript
const user = {
    firstName: "John",
    lastName: "Doe",
    getFullName: function() {
        // Without 'this', JavaScript wouldn't know where to find firstName
        return this.firstName + " " + this.lastName;
    }
};

console.log(user.getFullName()); // Output: John Doe

Example 5: Arrays of Objects

This is the most common data structure in all of web development (especially when fetching data from an API or Database).

javascript
123456789
// Example JavaScript
const usersList = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" }
];

// Accessing Bob's name
console.log(usersList[1].name); // Output: Bob

Example 6: Iterating over an Object (for...in loop)

You cannot use a standard for loop with i++ on an object because objects don't have numbered indexes or a .length property. Instead, you use for...in.

javascript
12345678910
// Example JavaScript
const stats = {
    health: 100,
    mana: 50,
    stamina: 80
};

for (let key in stats) {
    console.log("Stat Name: " + key + " | Value: " + stats[key]);
}

Output Explanation: It loops through every key. Notice we *must* use bracket notation stats[key] inside the loop, because stats.key would literally look for a property named "key", which doesn't exist.

Example 7: Nested Objects

An object can contain other objects.

javascript
1234567891011121314
// Example JavaScript
const order = {
    id: 9942,
    customer: {
        name: "David",
        address: {
            city: "New York",
            zip: "10001"
        }
    }
};

// Chaining dot notation to go deeper
console.log(order.customer.address.city); // Output: New York

Example 8: Optional Chaining (?.)

If you try to access a property deep inside an object that doesn't exist, your app will crash. Optional chaining safely checks if the property exists before proceeding.

javascript
1234567
// Example JavaScript
const order = { id: 1 }; // No customer data!

// console.log(order.customer.name); // ERROR: Cannot read properties of undefined (reading 'name')

// Safe way:
console.log(order.customer?.name); // Output: undefined (no error!)

Example 9: Object.keys() and Object.values()

These built-in JavaScript methods extract just the keys or just the values into an Array.

javascript
12345678
// Example JavaScript
const car = { brand: "Ford", model: "Mustang" };

let keysArray = Object.keys(car);
console.log(keysArray); // Output: ["brand", "model"]

let valuesArray = Object.values(car);
console.log(valuesArray); // Output: ["Ford", "Mustang"]

Example 10: Using Variables as Keys

If you want to use a variable as a key name, you *must* use bracket notation.

javascript
12345678910
// Example JavaScript
let dynamicKey = "email";

const person = {
    name: "Emma",
    email: "emma@test.com"
};

// console.log(person.dynamicKey); // Output: undefined (looks for actual 'dynamicKey')
console.log(person[dynamicKey]);   // Output: emma@test.com

---

7. Common Mistakes for Beginners

  1. 1. Using = instead of : inside an object: const obj = { name = "John" } is a syntax error.
  1. 2. Forgetting commas between properties: const obj = { name: "John" age: 25 } is a syntax error.
  1. 3. Using this inside an Arrow Function: We will cover arrow functions later, but note that this breaks if used inside an arrow function attached to an object. Always use the standard function() syntax for object methods.

8. Best Practices

  • Always declare objects with const.
  • Keep object properties logically related. Don't put user data and database configuration strings into the same object.
  • Use Dot Notation obj.name for readability, and only use Bracket Notation obj["name"] when absolutely necessary (like dynamic keys).

9. Mini Project: Product Catalog

Let's use an Array of Objects to dynamically render a shopping catalog to the screen.

HTML:

html
1234567891011121314151617181920
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 20px; background: #f0f0f0;}
        #catalog { display: flex; gap: 15px; }
        .product-card { background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); width: 150px; text-align: center; }
        .price { color: #28a745; font-weight: bold; font-size: 18px; }
    </style>
</head>
<body>

    <h2>Store Catalog</h2>
    <div id="catalog"></div>

    <script src="store.js"></script>
</body>
</html>

store.js:

javascript
1234567891011121314151617181920212223242526272829303132
// Example JavaScript

// 1. Array of Objects (Database mockup)
const products = [
    { id: 1, name: "Laptop", price: 999.99, inStock: true },
    { id: 2, name: "Mouse", price: 25.50, inStock: true },
    { id: 3, name: "Keyboard", price: 45.00, inStock: false }
];

// 2. Target the DOM
const catalogDiv = document.getElementById("catalog");
let htmlContent = "";

// 3. Loop through array, access object properties
for (let i = 0; i < products.length; i++) {
    let p = products[i]; // Get the current object
    
    // Check stock status for label
    let stockLabel = p.inStock ? "In Stock" : "<span style=&#039;color:red&#039;>Out of Stock</span>";

    // Build HTML string
    htmlContent += `
        <div class="product-card">
            <h3>${p.name}</h3>
            <p class="price">$${p.price.toFixed(2)}</p>
            <p><small>${stockLabel}</small></p>
        </div>
    `;
}

// 4. Render
catalogDiv.innerHTML = htmlContent;

*(Note: We used backticks ` ` to create multi-line strings. We will officially cover this in Chapter 12: Strings).*

10. Exercises

  1. 1. Create an object called book with properties: title, author, and pages.
  1. 2. Add a new property to the book object called isRead and set it to true.
  1. 3. Add a method to the book object called getSummary that returns the string: "(Title) was written by (Author)".

11. MCQs (Multiple Choice Questions)

Q1: How do you access the age property of a person object? A) person[age] B) person.age C) person->age D) Both A and B are correct if A has quotes person["age"] *Answer: D*

Q2: What is a function called when it is attached to an object? A) A Procedure B) A Property C) A Method D) A Class *Answer: C*

Q3: What keyword refers to the current object inside an object's method? A) it B) self C) current D) this *Answer: D*

12. Interview Questions

Q: Explain the difference between Dot Notation and Bracket Notation. *A: Dot notation (obj.key) is cleaner and easier to read, but the key must be a valid JavaScript identifier (no spaces, doesn't start with a number). Bracket notation (obj["key"]) accepts any string, and is strictly required when evaluating dynamic variables (e.g., obj[dynamicVar]).*

Q: What does Object.keys() return? *A: It returns an Array containing all the enumerable property names (keys) of an object as strings.*

13. FAQs

Q: What is the difference between JSON and a JavaScript Object? *A: They look identical, but JSON is strictly a text string format used for transmitting data over the network. A JS Object is a live entity in memory. JSON keys MUST be wrapped in double quotes. (We will cover JSON deeply in Chapter 23).*

14. Summary

  • Objects store data in Key-Value pairs.
  • Access data using . or [].
  • Functions inside objects are called Methods.
  • Use this to access sibling properties inside methods.
  • Arrays of Objects are the standard way to represent lists of complex data.

15. Next Chapter Recommendation

We have used text (Strings) constantly in our
console.logs` and HTML injections, but Strings have their own superpowers! In the next chapter, JavaScript Strings, we will learn how to search, slice, format, and manipulate text efficiently.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·