2.10 Module 2 · Variables, Data Types & Functions

Objects

Learn how to group related data and behaviour into a single structure using key-value pairs — the most versatile and widely used data type in JavaScript.

1

Definition

An object in JavaScript is a collection of key-value pairs, where each key (also called a property) is associated with a value. Objects are used to represent real-world entities and can also contain functions — known as methods — that describe the behaviour of that entity.

Objects are the foundation of JavaScript: arrays, dates, functions, and almost everything else you interact with is an object under the hood. Mastering objects means mastering the language itself.

2

Simple Way

An object is like a profile card — instead of separate variables for each detail, everything about one entity lives together:

{ } Curly braces create an object — { name: "Aman", age: 22 }
key The label for a piece of data — name, age, city
value The data itself — any type: string, number, boolean, array, or function
method A function stored as a property — describes what the object can do
3

Code Examples

Example 1 — Creating & Accessing an Object
let person = {
  name: "Aman",
  age:  22,
  city: "Vadodara"
};

// Dot notation — most common
console.log(person.name);

// Bracket notation — useful for dynamic keys
console.log(person["age"]);

// Access a key that doesn't exist → undefined (no error)
console.log(person.country);
Output
Click ▶ Run to execute
Explanation
  • Dot notation (person.name) — clean and most commonly used
  • Bracket notation (person["age"]) — required when the key is a variable or contains special characters
  • Accessing a non-existent property returns undefined — not an error
Example 2 — Adding & Updating Properties
let user = {
  name: "Aman"
};

user.age  = 22;       // add a new property
user.name = "Raj";    // update an existing property

console.log(user.name);
console.log(user.age);
console.log(user);
Output
Click ▶ Run to execute
Explanation
  • New properties can be added at any time by assigning to a key that doesn't yet exist
  • Assigning to an existing key updates its value in place
  • Even const objects allow property changes — only re-assigning the whole object is forbidden
Example 3 — Object with Methods
let calculator = {
  add: function(a, b) {
    return a + b;
  },
  // Shorthand method syntax (modern)
  multiply(a, b) {
    return a * b;
  }
};

console.log(calculator.add(5, 3));
console.log(calculator.multiply(4, 6));
Output
Click ▶ Run to execute
Explanation
  • A function stored as an object property is called a method
  • Methods are called with dot notation followed by parentheses: calculator.add(5, 3)
  • Modern shorthand syntax (multiply(a, b) {}) drops the function keyword
Example 4 — Nested Objects & for...in Loop
let student = {
  name: "Priya",
  marks: {
    maths:   95,
    science: 88,
    english: 91
  }
};

// Access nested property
console.log(student.marks.maths);

// Loop through all keys
for (let key in student.marks) {
  console.log(key + ": " + student.marks[key]);
}
Output
Click ▶ Run to execute
Explanation
  • Objects can be nested — a value can itself be another object
  • Access nested properties by chaining dot notation: student.marks.maths
  • for...in loops over every key in an object — ideal for dynamic key access
Example 5 — The Built-in Date Object
let now = new Date();

console.log(now.getFullYear());   // current year
console.log(now.getMonth() + 1);  // month (0-based, so +1)
console.log(now.getDate());       // day of the month
Output
Click ▶ Run to execute
Explanation
  • new Date() creates a built-in Date object with the current timestamp
  • Methods like getFullYear(), getMonth(), and getDate() extract parts of the date
  • getMonth() is zero-based — January is 0, so always add 1 for display
4

Real-Life Example

Think of a student ID card — all related details grouped in one place:

Object
The ID card itself — one container holding all student details
Property
A field on the card — Name, Age, Course, Roll Number
Method
An action the student can do — getGrade(), calculateAverage()
Nested
Marks section inside the card — an object within an object
5

HTML + JavaScript Example

Click ▶ Preview, then press the button to render a student object as a formatted profile card on the page — looping through its properties dynamically.

Live in Browser — Student Info Card
<!DOCTYPE html>
<html>
<head><title>Objects Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Student Info</h2>
  <button onclick="showInfo()"
    style="padding:8px 18px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Show
  </button>
  <div id="output" style="margin-top:16px;font-size:0.95rem"></div>

  <script>
    function showInfo() {
      const student = {
        name:   "Priya Sharma",
        age:    20,
        course: "Computer Science",
        city:   "Vadodara",
        grade:  "A+"
      };

      let html =
        "<div style='background:#fff;border:1px solid #ddd;border-radius:10px;" +
        "padding:18px 22px;max-width:340px;line-height:2.2'>";

      for (let key in student) {
        html += `<b style="text-transform:capitalize">${key}:</b> ${student[key]}<br>`;
      }

      html += "</div>";
      document.getElementById("output").innerHTML = html;
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Your profile object
Starter code
let profile = {
  name: "Your Name",
  age:  0
};
  • Replace the values with your own name and age
  • Print profile.name using dot notation
  • Print profile["age"] using bracket notation
Medium Task 2 — Product with new property
Starter code
const product = {
  name:  "Laptop",
  price: 45000
};
  • Add a new property quantity with value 3
  • Update price to 42000
  • Print the full object and confirm all three properties are present
7

MCQs

Q1
How do you correctly access an object property?
let obj = { name: "Aman", age: 22 };

console.log(obj.name);
console.log(obj["age"]);
Output
Run it to verify
  • A obj:name
  • B obj.name
  • C obj->name
  • D obj[name] without quotes
💡 B is correct. Dot notation obj.name is the standard way. Bracket notation obj["name"] also works — note the key must be a string inside quotes when used directly.
Q2
What best describes a JavaScript object?
  • A A single value
  • B An ordered list
  • C A collection of key-value pairs
  • D A function
💡 C is correct. An object is a collection of key-value pairs. Each key is a string (or Symbol) and its value can be any data type — including other objects or functions (methods).
Q3
What is the output?
let obj = { a: 10 };
console.log(obj.a);
Output
Run it to verify
  • A 10
  • B undefined
  • C Error
  • D null
💡 A is correct. obj.a accesses the value stored under the key "a", which is 10. If the key didn't exist, it would return undefined — not an error.
8

Pro Tips & Extra Knowledge

  • 01

    Use const for objects — you can still add or change properties freely; const only prevents reassigning the variable to a different object:

    const object — properties are mutable
    const user = { name: "Aman" };
    user.name = "Raj";  // ✓ allowed — property updated
    user.age  = 22;     // ✓ allowed — new property added
    console.log(user);
    
    // user = {};  // ✗ Error — cannot reassign the binding
    Output
    Click ▶ Run to execute
  • 02

    Use the in operator to check if a property exists — more reliable than comparing with undefined:

    Checking property existence
    const person = { name: "Aman", age: 22 };
    
    console.log("name" in person);    // true
    console.log("salary" in person);  // false
    
    // Avoid this — a property can exist AND equal undefined
    console.log(person.salary === undefined); // true — ambiguous!
    Output
    Click ▶ Run to execute
  • 03

    Use destructuring to extract multiple properties from an object into individual variables in one line:

    Object destructuring
    const person = { name: "Aman", age: 22, city: "Vadodara" };
    
    // Old way
    let name = person.name;
    let age  = person.age;
    
    // Modern destructuring — one line
    const { name: n, age: a, city } = person;
    
    console.log(n, a, city);
    Output
    Click ▶ Run to execute
  • 04

    Use Object.keys(), Object.values(), and Object.entries() to get arrays of an object's keys, values, or both:

    Object utility methods
    const scores = { maths: 95, science: 88, english: 91 };
    
    console.log(Object.keys(scores));    // ["maths", "science", "english"]
    console.log(Object.values(scores));  // [95, 88, 91]
    console.log(Object.entries(scores)); // [["maths",95],["science",88],...]
    Output
    Click ▶ Run to execute
Mini Challenge

A property is updated and a new one is added — what does each console.log print? Think before running.

What does this print?
let obj = {
  name: "Aman",
  age:  22
};

obj.age  = 25;
obj.city = "Delhi";

console.log(obj.age);
console.log(obj.city);
Output
Think first, then run!
Step-by-Step Explanation
// Initial object:
//   obj = { name: "Aman", age: 22 }

// Step 1: obj.age = 25
//   The key "age" already exists → its value is UPDATED
//   obj = { name: "Aman", age: 25 }

// Step 2: obj.city = "Delhi"
//   The key "city" does not yet exist → a NEW property is ADDED
//   obj = { name: "Aman", age: 25, city: "Delhi" }

// Step 3: console.log(obj.age)
//   age was updated from 22 to 25
//   Output → 25

// Step 4: console.log(obj.city)
//   city was just added
//   Output → "Delhi"

// Final output:
//   25       ← updated value
//   "Delhi"  ← newly added property

// Key takeaway:
//   Assigning to an existing key → UPDATES it
//   Assigning to a new key      → ADDS it
//   Both work identically — no special syntax needed.