Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
•3 min read•View as Markdown
Understanding Objects in JavaScript
B
I write funny shayaris and sad code.

In our previous look at Arrays, we learned how to store a list of items in a specific order. But what if you need to store data that describes a single thing in detail? For example, if you want to store a student's information, an array like ["Rahul", 20, "Computer Science"] doesn't tell you what the number 20 actually represents.

This is where Objects come in. Objects allow us to store data in key-value pairs, making our code much more descriptive and readable.


What Objects Are and Why They Are Needed

An Object is a collection of related data and/or functionality. Instead of just a list of values, an object uses "keys" (labels) to identify each "value."

The Difference: Array vs. Object

  • Array: Use when the order of items matters (e.g., a list of high scores).

  • Object: Use when the label of the data matters (e.g., a profile of a user).


Creating Objects

In JavaScript, we create objects using curly braces {}. Inside, we define the property name (key), followed by a colon, and then the value.

JavaScript

// Creating a student object
let student = {
  name: "Rahul",
  age: 20,
  course: "Computer Science"
};

Accessing Properties

There are two main ways to get data out of an object:

  1. Dot Notation (.): The most common and readable way.

  2. Bracket Notation ([]): Useful if your key has spaces or is stored in a variable.

JavaScript

console.log(student.name);      // Output: Rahul (Dot notation)
console.log(student["course"]); // Output: Computer Science (Bracket notation)

Updating, Adding, and Deleting Properties

Objects are flexible. You can change them at any time after they have been created.

  • To Update: Simply assign a new value to an existing key.

  • To Add: Assign a value to a key that doesn't exist yet.

  • To Delete: Use the delete keyword.

JavaScript

// 1. Update age
student.age = 21;

// 2. Add a new property
student.isGraduated = false;

// 3. Delete a property
delete student.course;

console.log(student); 
// Output: { name: "Rahul", age: 21, isGraduated: false }

Looping Through Objects

To look at every piece of data inside an object, we use a special loop called the for...in loop. This loop iterates over every key in the object.

JavaScript

let student = {
  name: "Rahul",
  age: 21,
  city: "Jaipur"
};

for (let key in student) {
  // Use bracket notation to get the value dynamically
  console.log(key + ": " + student[key]);
}

/* Output:
name: Rahul
age: 21
city: Jaipur
*/

Summary Checklist

  • Objects store data as key-value pairs.

  • Dot notation is the go-to for accessing properties.

  • Bracket notation is the "backup" for dynamic or complex keys.

  • The for...in loop is the standard way to browse through an object's contents.