Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Objects

Objects are the most common data structure in JavaScript for representing structured data.

They store information as key-value pairs and can include methods.

Why We Need It

Most app data looks like objects: users, settings, products, and more.

Understanding objects is essential for working with real-world JavaScript code.

Syntax

const obj = { key: value }
obj.key
obj['key']

Basic Example

1. Create an object

const user = {
  name: "Ava",
  age: 22,
};

console.log(user.name);

Objects group related data under named keys.

Real World Example

2. Add and update

const user = { name: "Ava" };
user.age = 22;
user.name = "Riya";

console.log(user);

You can add or update properties anytime.

Multiple Use Cases

Key-Value Data

Objects store data in key-value pairs, making them great for structured information.

They power most real-world data models in JavaScript.

  • Use objects for named fields.
  • Access values by key.
  • Nest objects for deeper structures.

Properties and Methods

Properties store values and methods store functions.

Methods often use the this keyword to access other properties.

Modern Utilities

Use Object.keys, Object.values, and Object.entries to inspect objects.

Use Object.assign and spread to copy or merge objects.

Destructuring

Destructuring lets you unpack object properties into variables.

It reduces repetition and makes code cleaner.

More Examples

3. Methods

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

console.log(user.greet());

Methods are functions stored on objects.

4. Destructuring

const user = { name: "Ava", role: "admin" };
const { name, role } = user;

console.log(name, role);

Destructure to avoid repeated user.name access.

Comparison

Without

const name = user.name;
const role = user.role;

With

const { name, role } = user;

Common Mistakes and Fixes

Using dot for dynamic keys

Use bracket notation for dynamic property names.

Mutating shared objects

Clone with spread or Object.assign when needed.

Forgetting this in methods

Use this.property to access other fields inside methods.

Interview Questions

What is an object?

A collection of key-value pairs.

Dot vs bracket access?

Dot for static keys, bracket for dynamic keys.

How do you add a property?

Assign with obj.newKey = value or obj['newKey'] = value.

Practice Problem

Practice: Create an object for a book with title and author, then log both.

// TODO: create book object

One Possible Solution

const book = { title: "Clean Code", author: "Robert Martin" };
console.log(book.title, book.author);

Frequently Asked Questions

Are objects ordered?

Property order exists but should not be relied on for logic.

How do I copy an object?

Use spread: const copy = { ...obj }.

What is a method?

A function stored as a property of an object.

Try It Yourself

Try adding and updating properties on the object.