Index

Objects and Object Literals

JavaScript for Beginners

8.1 Creating Objects

In JavaScript, objects are one of the most powerful and flexible data structures. They allow you to group related data and behavior together using a key-value format.

Where arrays are ideal for ordered lists of items (like a list of names or scores), objects are best used when you want to represent structured data — like a person, a car, or a product — where each piece of data is identified by a descriptive name (a key).

What Is an Object?

An object is a collection of properties, where each property has a key (or property name) and a value. These keys are always strings (or symbols), and values can be any type of data, including strings, numbers, arrays, other objects, or functions.

Creating Objects with Object Literals (Preferred)

The most common and readable way to create an object is by using object literal syntax — simply wrap the key-value pairs inside curly braces {}.

Example – Creating a Person Object:

let person = {
  name: 'Alice',
  age: 30,
  isStudent: false
};

Here:

You can also create an empty object and add properties later:

let book = {};
book.title = 'JavaScript Basics';
book.pages = 250;

Creating Objects with new Object() Constructor

JavaScript also allows you to create objects using the new Object() constructor. This approach is more verbose and rarely used today in favor of object literals.

Example – Using Constructor:

let car = new Object();
car.make = 'Toyota';
car.model = 'Camry';
car.year = 2022;

This produces the same result as:

let car = {
  make: 'Toyota',
  model: 'Camry',
  year: 2022
};

When to Use Objects vs. Arrays

Use Case Choose... Example
Ordered list of values Array ['apple', 'banana', 'cherry']
Named pieces of related data Object { name: 'Alice', age: 30 }
Need to access items by position Array colors[0]
Need to access items by name Object person.name

Objects shine when you want to group and label data, especially when that data describes attributes or characteristics of a thing.

Summary

As you continue building JavaScript programs, you’ll use objects frequently to represent real-world entities and store flexible, descriptive data.

Index

8.2 Accessing and Updating Properties

Once you've created an object, you'll often need to read, update, add, or even delete its properties. JavaScript provides two main ways to access and modify object properties: dot notation and bracket notation.

Accessing Properties

Syntax:

object.propertyName

Example:

let person = {
  name: 'Alice',
  age: 30
};

console.log(person.name); // 'Alice'
console.log(person.age);  // 30

Dot notation is simple and readable, but it only works when:

Bracket Notation (For Dynamic or Unusual Keys)

Syntax:

object['propertyName']

Example with space in key:

let book = {
  title: 'JavaScript Guide',
  'page count': 300
};

console.log(book['page count']); // 300

Example with a dynamic key:

let key = 'name';
let person = { name: 'Bob' };

console.log(person[key]); // 'Bob'

💡 Use bracket notation when the property name is stored in a variable or contains spaces/special characters.

Updating Properties

You can change the value of an existing property using either dot or bracket notation.

Example – Updating a Property:

let car = {
  make: 'Toyota',
  year: 2020
};

car.year = 2023;
car['make'] = 'Honda';

console.log(car); // { make: 'Honda', year: 2023 }

Adding New Properties

If the property doesn’t exist, assigning a value will create it:

let user = { username: 'jsLearner' };

user.age = 25;
user['email'] = 'user@example.com';

console.log(user);
// { username: 'jsLearner', age: 25, email: 'user@example.com' }

Deleting Properties

You can remove a property using the delete operator:

let profile = {
  name: 'Charlie',
  location: 'Canada'
};

delete profile.location;

console.log(profile); // { name: 'Charlie' }

⚠️ Note: delete only removes the property from the object; it doesn't affect the prototype.

Summary

Task Preferred Notation Example
Read known property Dot notation obj.name
Read dynamic/odd key Bracket notation obj['full name'] or obj[key]
Update property Dot or bracket obj.age = 30
Add new property Dot or bracket obj.city = 'Paris'
Delete property delete operator delete obj.city

Understanding how to access and update properties is fundamental when working with objects. These skills allow you to build and manipulate data structures that represent real-world entities and change over time.

Index

8.3 Nesting Objects

In JavaScript, objects can contain other objects or arrays as property values. This is called nesting, and it's a powerful way to model complex, structured data — like user profiles, product catalogs, or app settings.

Nested objects help you organize related data in a way that mirrors real-world relationships.

Example: A User Profile Object

Let’s say we want to model a user with personal info, an address, and preferences. We can nest objects to represent each section:

let user = {
  name: 'Emily',
  age: 28,
  address: {
    street: '123 Main St',
    city: 'New York',
    zip: '10001'
  },
  preferences: {
    theme: 'dark',
    notifications: true
  }
};

Here:

Accessing Nested Properties

You can use dot notation or bracket notation to reach properties inside nested objects.

Examples:

console.log(user.address.city);          // 'New York'
console.log(user.preferences.theme);     // 'dark'

If a key has spaces or is stored in a variable, use bracket notation:

console.log(user['address']['zip']);     // '10001'

Updating Nested Properties

You can assign new values to nested properties just like top-level ones:

user.address.city = 'Los Angeles';
user.preferences.theme = 'light';

console.log(user.address.city);          // 'Los Angeles'
console.log(user.preferences.theme);     // 'light'

Adding Properties to Nested Objects

You can also add new properties at any level:

user.address.country = 'USA';
user.preferences.language = 'English';

console.log(user.address.country);       // 'USA'
console.log(user.preferences.language);  // 'English'

Nested Arrays in Objects

It’s also common to store arrays inside objects:

let product = {
  name: 'Laptop',
  price: 999,
  features: ['touchscreen', 'backlit keyboard', 'USB-C']
};

console.log(product.features[1]); // 'backlit keyboard'

Or even objects inside arrays:

let order = {
  id: 1234,
  items: [
    { name: 'Phone', quantity: 1 },
    { name: 'Charger', quantity: 2 }
  ]
};

console.log(order.items[1].name); // 'Charger'

Summary

By mastering nested structures, you’ll be able to represent rich data models and work confidently with modern APIs, user data, or configuration objects in your applications.

Index

8.4 Iterating Over Objects

In JavaScript, iterating over an object means going through its keys and values—a common task when you need to inspect, transform, or manipulate data dynamically. Unlike arrays, objects don’t have a built-in index-based loop, but JavaScript provides several ways to loop through object properties.

In this section, we’ll explore:

for...in: Looping Over Keys

The for...in loop lets you iterate over all enumerable properties of an object.

Syntax:

for (let key in object) {
  // Use key and object[key]
}

Example – Print all key-value pairs:

let person = {
  name: 'Alice',
  age: 30,
  country: 'Canada'
};

for (let key in person) {
  console.log(key + ': ' + person[key]);
}
// Output:
// name: Alice
// age: 30
// country: Canada

⚠️ Note: for...in loops also iterate over inherited properties, so it’s good practice to check ownership with hasOwnProperty() if needed.

Object.keys(): Getting All Keys

Object.keys() returns an array of property names (keys) from the object.

Example:

let car = {
  make: 'Honda',
  model: 'Civic',
  year: 2022
};

let keys = Object.keys(car);
console.log(keys); // ['make', 'model', 'year']

You can combine this with a for or forEach() loop:

Object.keys(car).forEach(key => {
  console.log(`${key}: ${car[key]}`);
});

Object.values(): Getting All Values

Object.values() returns an array of the object's values only.

Example:

let scores = {
  math: 90,
  english: 85,
  science: 95
};

let values = Object.values(scores);
console.log(values); // [90, 85, 95]

You can sum the values:

let total = Object.values(scores).reduce((sum, score) => sum + score, 0);
console.log(total); // 270

Object.entries(): Getting Key-Value Pairs

Object.entries() returns an array of [key, value] pairs, making it ideal for looping with for...of.

Example – Loop with for...of:

let user = {
  username: 'coder123',
  level: 'beginner',
  active: true
};

for (let [key, value] of Object.entries(user)) {
  console.log(`${key} => ${value}`);
}
// Output:
// username => coder123
// level => beginner
// active => true

Use Cases

Task Recommended Method
List keys Object.keys() or for...in
List values Object.values()
Loop through key-value pairs Object.entries()
Copy or transform properties Combine Object.keys() with mapping logic

Summary

Method Returns Ideal For
for...in Each key (one at a time) Simple loops (use with caution)
Object.keys(obj) Array of keys Accessing all property names
Object.values(obj) Array of values Summing or listing values
Object.entries(obj) Array of [key, value] pairs Full key-value iteration

Mastering these object iteration techniques enables you to dynamically inspect, transform, or display structured data—an essential skill when working with user profiles, configuration settings, API responses, or any real-world data structure.

Index