Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
•4 min read•View as Markdown
Understanding Objects in JavaScript
S
I like to make complex technical topics easy.

Introduction

If you're learning JavaScript, you've likely used primitive data types like strings, numbers, and booleans. But what happens when you need to group related data together? That's where Objects come in.

In this guide, we will break down what JavaScript objects are, why we need them, how to use them, and how they differ from arrays.


What are Objects and Why Do We Need Them?

An Object in JavaScript is a non-primitive data type used to store collections of related data in a structured key-value pair format.

Why Do We Need Objects?

Imagine you are building a system to store information about a user. Using standalone variables quickly becomes messy and unmanageable:

let userName = "Alex";
let userAge = 22;
let userCity = "Delhi";

If you have 100 users, managing individual variables is impossible. Objects allow you to group related details under a single, organized variable name:

const person = {
  name: "Alex",
  age: 22,
  city: "Delhi"
};

Key Difference: Objects vs. Arrays

Both objects and arrays hold collections of data, but they serve different purposes:

  • Arrays are ordered lists indexed by numbers (0, 1, 2...). Use them when order matters (e.g., a list of high scores).

  • Objects are unordered collections indexed by custom string keys. Use them when describing an entity with distinct properties (e.g., a person or product).

ARRAY (Ordered List)
+-------+-------+-------+
|  "a"  |  "b"  |  "c"  |
+-------+-------+-------+
    0       1       2    (Numbered Indices)

OBJECT (Key-Value Structure)
+-----------------------+
|  name  : "Alex"       |
|  age   : 22           |
|  city  : "Delhi"      |
+-----------------------+
(Descriptive Named Keys)

Creating Objects

The simplest and most common way to create an object is using Object Literal Notation ({}):

const person = {
  name: "Alex",
  age: 22,
  city: "Delhi"
};

You can also create an empty object first and populate it later:

const person = {};
person.name = "Alex";

Accessing Object Properties

There are two main ways to retrieve values from an object: Dot Notation and Bracket Notation.

A. Dot Notation (.)

The cleanest and most common syntax.

console.log(person.name); // Output: Alex
console.log(person.age);  // Output: 22

B. Bracket Notation (['key'])

Use bracket notation when:

  1. The property key is stored in a dynamic variable.

  2. The key contains spaces or special characters.

// Example 1: Dynamic property lookup
const keyToFind = "city";
console.log(person[keyToFind]); // Output: Delhi

// Example 2: Property key with spaces
const user = {
  "first name": "John"
};
console.log(user["first name"]); // Output: John

Updating Object Properties

Updating an existing property is as simple as re-assigning its value using dot or bracket notation:

const person = {
  name: "Alex",
  age: 22,
  city: "Delhi"
};

// Update age
person.age = 23;

console.log(person.age); // Output: 23

Adding and Deleting Properties

Objects in JavaScript are mutable, meaning you can modify them even after creation (even if declared with const).

Adding a New Property

Assign a value to a key that doesn't exist yet:

person.isStudent = true;

console.log(person);
// Output: { name: 'Alex', age: 23, city: 'Delhi', isStudent: true }

Deleting a Property

Use the delete keyword to completely remove a key-value pair:

delete person.city;

console.log(person);
// Output: { name: 'Alex', age: 23, isStudent: true }

Looping Through Object Keys

To iterate over all the properties of an object, you can use the for...in loop or standard helper methods like Object.keys() and Object.entries().

Using for...in Loop

const person = {
  name: "Alex",
  age: 23,
  isStudent: true
};

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

/* Output:
name: Alex
age: 23
isStudent: true
*/

Useful Object Methods

  • Object.keys(obj): Returns an array of all key names.

  • Object.values(obj): Returns an array of all values.

  • Object.entries(obj): Returns an array of [key, value] pairs.

console.log(Object.keys(person));   // ['name', 'age', 'isStudent']
console.log(Object.values(person)); // ['Alex', 23, true]

Summary

  • Objects store key-value pairs for related data.

  • Dot notation (obj.key) is preferred for simple lookups, while bracket notation (obj[key]) handles dynamic keys.

  • You can easily add, update, or delete properties dynamically.

  • Use for...in or Object.keys() to loop through object contents.