Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
8 min read
Understanding Objects in JavaScript

Introduction:

In JavaScript, objects are a fundamental data type used to store collections of related data and functionality. They are composed of properties, which are key-value pairs, and methods, which are functions stored as properties. Nearly all JavaScript values, except for primitives (like strings, numbers, booleans, null, undefined, and symbols), are objects or behave like objects.

Core Concepts

  • Properties: These define the characteristics or state of an object. A property has a name (key), which must be a string or a Symbol, and a value, which can be any data type, including another object or an array.

    javascript

    const person = {
      firstName: "Jane",
      lastName: "Doe",
      age: 30
    };
    
  • Methods: These are actions or behaviors that can be performed on an object. Methods are functions assigned as the value of a property.

    javascript

    const person = {
      firstName: "Jane",
      lastName: "Doe",
      greet: function() {
        return `Hello, my name is \({this.firstName} \){this.lastName}`;
      }
    };
    

this Keyword: Inside an object's method, the this keyword refers to the current object itself, allowing access to its properties and other methods.

Creating Objects:

There are several ways to create objects in JavaScript:

  • Object Literals: The simplest and most common way, using curly braces {}.

    javascript

    const myCar = { make: "Ford", model: "Mustang", year: 1969 };
    
  • Constructor Functions: Defining a function that acts as a blueprint, then creating instances using the new keyword.

    javascript

    function Car(make, model, year) {
      this.make = make;
      this.model = model;
      this.year = year;
    }
    const myCar = new Car("Nissan", "300ZX", 1992);
    
  • Classes (ES6): Modern JavaScript provides the class keyword as a cleaner, syntactical "sugar" over the prototype-based inheritance system, offering a more structured approach to OOP.

    javascript

    class Car {
      constructor(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
      }
    }
    const myCar = new Car("Mazda", "Miata", 1990);
    

Object.create(): This method creates a new object using an existing object as the prototype for the new object.

Accessing Properties:

Properties can be accessed in two primary ways:

  • Dot Notation: The most common and readable method (e.g., object.propertyName).

    javascript

    const person = {
      firstName: "Jane",
      lastName: "Doe",
      age: 30
    };
    
    console.log(person.firstName); 
    
    //Output
    Jane
    
    === Code Execution Successful ===
    
  • Bracket Notation: Used for property names that are not valid JavaScript identifiers (e.g., contain spaces or hyphens), or when accessing property names stored in a variable (e.g., object["propertyName"]).

    javascript

    const person = {
      firstName: "Jane",
      lastName: "Doe",
      age: 30
    };
    
    let prop = "lastName";
    console.log(person[prop]); 
    
    // Output: 
    Doe
    
    === Code Execution Successful ===
    

Updating object properties:

Updating object properties in JavaScript means changing the value of a property that already exists inside an object, or adding a new property to it.

Let’s break it down simply.

1. Updating a Property (By dot Notation)

You can update a property using dot notation.

let user = {
  name: "Mohit",
  age: 20
};

user.age = 21;

console.log(user);

Output

{ name: "Mohit", age: 21 }

=== Code Execution Successful ===

Here:

  • user.age originally = 20

  • After update = 21

2. Updating a Property (Bracket Notation)

You can also update using bracket notation.

let user = {
  name: "Mohit",
  age: 20
};

user["age"] = 22;

console.log(user);

Output:

{ name: 'Mohit', age: 22 }

=== Code Execution Successful ===

This also updates the value of age.

3. Updating Multiple Properties

You can update more than one property.

let car = {
  brand: "BMW",
  year: 2020
};

car.brand = "Audi";
car.year = 2024;

console.log(car);

Output

{ brand: "Audi", year: 2024 }

=== Code Execution Successful ===

4. Adding a New Property

If the property does not exist, JavaScript will create it automatically.

let student = {
  name: "Rahul"
};

student.age = 19;

console.log(student);

Output

{ name: "Rahul", age: 19 }

=== Code Execution Successful ===

5. Updating Using a Variable Key

Sometimes the property name is stored in a variable.

let user = {
  name: "Mohit",
  age: 20
};

let key = "age";

user[key] = 25;

console.log(user);

Output:

{ name: 'Mohit', age: 25 }

=== Code Execution Successful ===

Adding and deleting properties:

In JavaScript, objects store data in key–value pairs. You can add new properties or delete existing properties easily. Let’s understand both:

1. Adding Properties

You can add a property by assigning a value to a new key.

Using Dot Notation

let user = {
  name: "Mohit",
  age: 20
};

user.city = "Delhi";

console.log(user);

Output

{ name: "Mohit", age: 20, city: "Delhi" }

=== Code Execution Successful ===

Here:

  • city did not exist before

  • JavaScript automatically created the property.

Using Bracket Notation

let user = {
  name: "Mohit"
};

user["age"] = 21;

console.log(user);

Output

{ name: "Mohit", age: 21 }

=== Code Execution Successful ===

Bracket notation is useful when the property name is dynamic.

2. Deleting Properties

To remove a property from an object, use the delete keyword.

let student = {
  name: "Rahul",
  age: 19,
  city: "Mumbai"
};

delete student.city;

console.log(student);

Output

{ name: "Rahul", age: 19 }

=== Code Execution Successful ===

Here:

  • city property is removed from the object.

3. Deleting with Bracket Notation

let car = {
  brand: "BMW",
  year: 2022
};

delete car["year"];

console.log(car);

Output

{ brand: "BMW" }

=== Code Execution Successful ===

Looping through object keys:

When working with objects in JavaScript, you often need to loop through all the keys (property names) to access their values. This is useful when you want to display or process all data inside an object. Here are the main ways to do it.

1. Using for...in Loop (Most Common)

The for...in loop is specifically designed to iterate through object keys.

let user = {
  name: "Mohit",
  age: 21,
  city: "Delhi"
};

for (let key in user) {
  console.log(key);
}

Output

name
age
city

=== Code Execution Successful ===

Here:

  • key represents each property name of the object.

2. Accessing Values While Looping : Usually, we want both key and value.

let user = {
  name: "Mohit",
  age: 21,
  city: "Delhi"
};

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

Output

name: Mohit
age: 21
city: Delhi

=== Code Execution Successful ===

Notice:

  • We use user[key] to access the value.

3. Using Object.keys() : Object.keys() returns an array of all keys, which you can loop through.

let user = {
  name: "Mohit",
  age: 21,
  city: "Delhi"
};

let keys = Object.keys(user);

for (let key of keys) {
  console.log(key);
}

Output

name
age
city

=== Code Execution Successful ===

4. Using Object.entries() (Key + Value) : If you want both key and value directly:

let user = {
  name: "Mohit",
  age: 21
};

for (let [key, value] of Object.entries(user)) {
  console.log(key, value);
}

Output

name Mohit
age 21

=== Code Execution Successful ===

Difference between array and object:

Feature Array Object
Structure Ordered list Key–value pairs
Access method Index (numbers) Keys (names)
Use case Similar items Structured data
Syntax [] {}

Here's an assignment Idea you can try yourself:

  1. Create an object representing a student

  2. Add properties like name, age, course

  3. Update one property

  4. Print all keys and values using a loop

Here's an solution of the assignment:

let student = {
  name: "Mohit",
  age: 21,
  course: "Backend Development"
};

student.course = "Full Stack Development";

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

Output:

name: Mohit
age: 21
course: Full Stack Development

=== Code Execution Successful ===

Conclusion: Understanding Objects in JavaScript

Objects are one of the most important data structures in JavaScript. They allow developers to store and organize data using key–value pairs, making it easy to represent real-world entities such as users, products, or students.

By learning objects, you understand how to group related data together instead of storing values in separate variables. Objects also allow you to add, update, or delete properties, which makes them flexible for handling dynamic data in applications.

Another key concept is looping through object properties using loops like for...in or methods like Object.keys(). This helps when you need to process or display all the data stored inside an object.

In modern JavaScript development, objects are used everywhere-from API responses and configuration settings to database data and application state. Because of this, a strong understanding of objects is essential for building scalable and maintainable applications.

In short, mastering objects helps you write cleaner, more organized, and more powerful JavaScript code, and it forms a foundation for advanced concepts such as JSON, classes, and frameworks like React or Node.js.