Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
2 min readView as Markdown

Introduction

JavaScript objects are used to store data in the form of key–value pairs. They help organize related information together and represent real-world entities such as a person, student, or product. Objects make programs easier to manage and are widely used in web development.

1. What Objects Are and Why They Are Needed

An object in JavaScript is a collection of key–value pairs used to store related data and functions.

Objects help organize data in a structured way. Instead of storing information in separate variables, we can group related data together.

Example

let person = {
  name: "Rahul",
  age: 21,
  city: "Mysore"
};

Here:

  • name, age, city → keys (properties)

  • Rahul, 21, Mysore → values

Why Objects Are Needed

  • Store related data together

  • Make code organized and readable

  • Represent real-world entities like student, car, product, user


2. Creating Objects

Objects can be created using object literal syntax.

Example

let student = {
  name: "Aman",
  age: 20,
  course: "BCA"
};

We can also create an empty object and add values later.

let car = {};
car.brand = "Toyota";
car.model = "Innova";

3. Accessing Properties

Object properties can be accessed in two ways.

1. Dot Notation

console.log(student.name);

2. Bracket Notation

console.log(student["age"]);

Difference

  • Dot notation → simple and common

  • Bracket notation → useful when property name is dynamic

Example:

let key = "course";
console.log(student[key]);

4. Updating Object Properties

Object values can be changed easily.

Example

student.age = 21;

After update:

{
 name: "Aman",
 age: 21,
 course: "BCA"
}

5. Adding and Deleting Properties

Adding a Property

student.city = "Bangalore";

Deleting a Property

delete student.course;

6. Looping Through Object Keys

We can use a for...in loop to go through object properties.

Example

for (let key in student) {
  console.log(key + ": " + student[key]);
}

Output:

name: Aman
age: 21
city: Bangalore

Conclusion

JavaScript objects are powerful data structures used to store and manage related information. They use key-value pairs, making them useful for representing real-world entities like users, students, and products.