Lesson 6 • Intermediate

    Arrays and Objects

    Master JavaScript's most important data structures for organizing, storing, and manipulating data.

    What You'll Learn in This Lesson

    • Create and access arrays by index
    • Add and remove items with push/pop/shift
    • Transform arrays with map, filter, reduce
    • Create objects with key-value pairs
    • Nest objects inside arrays (real data patterns)
    • Use Object.keys(), values(), entries()

    💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

    • Download Node.js to run JavaScript on your computer
    • Use your browser's Developer Console (Press F12) to test code snippets
    • Create a .html file with <script> tags and open it in your browser

    🗂️ Real-World Analogy: Arrays and Objects are like different storage systems:

    • Arrays = A numbered list (like a shopping list: item 1, item 2, item 3...)
    • Objects = A labeled filing cabinet (look up by name: "age", "email", "address")
    • • You can put arrays inside objects and objects inside arrays!

    🧠 Introduction

    Every real JavaScript application—websites, games, APIs, mobile apps—heavily relies on arrays and objects. They are the foundation of data representation, making them one of the most important concepts you will ever master.

    Data StructureAccess ByBest ForExample
    ArrayIndex (0, 1, 2...)Ordered lists["apple", "banana"]
    ObjectKey nameNamed properties{name: "Alice"}

    If variables are single boxes that hold one value… Arrays and objects are storage containers, folders, databases, and flexible multi-value structures that allow your program to organize information just like real-world systems do.

    By the end of this lesson, you'll understand how to use arrays and objects, how to transform them with map, filter, reduce, and how to think like a real developer when structuring data.

    🍇 Working With Arrays

    Arrays are ordered collections of items.

    You can store:

    • Numbers
    • Strings
    • Booleans
    • Objects
    • Other arrays
    • A mix of everything

    Example:

    const fruits = ["apple", "banana", "orange"];

    Indexes start at 0, not 1:

    • fruits[0] → "apple"
    • fruits[1] → "banana"
    • fruits[2] → "orange"

    ➕ Adding & Removing Items

    JavaScript gives you powerful array methods:

    const fruits = ["apple", "banana", "orange"];
    
    ▶️ Add to end (push)
    fruits.push("grape");
    
    ◀️ Remove from end (pop)
    fruits.pop();
    
    ⬆️ Add to start (unshift)
    fruits.unshift("mango");
    
    ⬇️ Remove from start (shift)
    fruits.shift();

    These are your essential tools for managing lists dynamically.

    🔍 Finding Items

    fruits.indexOf("banana")   // returns index
    fruits.includes("apple")   // true or false

    🔁 Looping Through Arrays

    forEach – run code for every item

    numbers.forEach(n => console.log(n));

    map – transform every item

    const doubled = numbers.map(n => n * 2);

    filter – select only matching items

    const evens = numbers.filter(n => n % 2 === 0);

    🧮 Array Reduction

    Combine values into a single output.

    Example: Sum all numbers

    const numbers = [1, 2, 3, 4];
    const sum = numbers.reduce((total, n) => total + n, 0);

    Output: 10

    reduce is extremely powerful—used for:

    • Totals
    • Statistics
    • Combining text
    • Processing API data
    • Creating analytics

    🧱 Objects — Key-Value Data

    Objects store properties (keys) with values.

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };

    Access values:

    person.name
    person["age"]

    Objects can store:

    • Strings
    • Numbers
    • Arrays
    • Functions
    • Other objects

    🧩 Object Methods

    JavaScript gives you tools to explore an object:

    Object.keys(person)    // ["name", "age", "city"]
    Object.values(person)  // ["Alice", 30, "New York"]
    Object.entries(person) // [["name","Alice"], ...]

    🧱 Nested Objects

    const student = {
      name: "Bob",
      grades: [90, 85, 95],
      address: {
        city: "Boston",
        zip: "02101"
      }
    };

    Access nested values:

    student.address.city
    student.grades[2]

    🛒 Array of Objects

    Very common in real apps.

    const users = [
      { name: "Alice", age: 30 },
      { name: "Bob", age: 25 },
      { name: "Charlie", age: 35 }
    ];

    Loop through:

    users.forEach(user => {
        console.log(`${user.name} is ${user.age} years old`);
    });

    🎓 REAL WORLD EXAMPLES

    Arrays + objects together represent real data.

    Example: Products in shopping cart

    const cart = [
      { name: "Shoes", price: 40, quantity: 2 },
      { name: "T-Shirt", price: 20, quantity: 1 }
    ];

    Example: API response

    const response = {
      status: 200,
      data: [
        { id: 1, title: "Post A" },
        { id: 2, title: "Post B" }
      ]
    };

    📘 ESSENTIAL ARRAY METHODS CHEAT SHEET

    map() – transform items

    [1,2,3].map(n => n * 2)

    filter() – keep items that match

    [1,2,3,4].filter(n => n > 2)

    reduce() – combine into one

    [1,2,3].reduce((sum, n) => sum + n, 0)

    find() – return first match

    users.find(u => u.age > 30)

    some() – at least one match

    numbers.some(n => n < 0)

    every() – all items match

    numbers.every(n => n > 0)

    🧠 Best Practices

    ✔️ Use const for arrays & objects

    They can still be modified; const prevents reassigning.

    ✔️ Avoid deeply nested structures

    They become hard to maintain.

    ✔️ Use descriptive keys

    Instead of:

    { n: 12, a: true }

    Use:

    { name: "Alice", isActive: true }

    ✔️ Use map/filter instead of loops

    They are cleaner, faster, and used by all modern JavaScript developers.

    🎮 Mini Project — Data Dashboard Simulation

    You have a list of users:

    const users = [
      { name: "Alice", age: 30, online: true },
      { name: "Bob", age: 25, online: false },
      { name: "Charlie", age: 35, online: true }
    ];

    1. Filter online users

    const onlineUsers = users.filter(u => u.online);

    2. Get list of names

    const names = users.map(u => u.name);

    3. Average age using reduce

    const avgAge = users.reduce((sum, u) => sum + u.age, 0) / users.length;

    This is exactly how real dashboards, analytics systems, and UIs calculate data.

    Arrays and Objects Practice

    Work with arrays, objects, and their powerful methods!

    Try it Yourself »
    JavaScript
    // Arrays and Objects Practice
    const students = [
      { name: "Alice", grade: 90 },
      { name: "Bob", grade: 75 },
      { name: "Charlie", grade: 85 }
    ];
    
    // Get all names using map()
    const names = students.map(s => s.name);
    console.log("Names:", names);
    
    // Find students with grade > 80 using filter()
    const topStudents = students.filter(s => s.grade > 80);
    console.log("Top students:", topStudents);
    
    // Calculate average grade using reduce()
    const avgGrade = students.reduce((sum, s) => sum + s.grade, 
    ...

    🎯 Practice Challenge

    Try these tasks:

    • 1️⃣ Create an array of numbers - Use map() to square each number.
    • 2️⃣ Use filter() - Get numbers greater than 10.
    • 3️⃣ Create an object representing a book - Include: title, author, year
    • 4️⃣ Create an array of objects - Use forEach() to print each one.
    • 5️⃣ Use reduce() - Calculate the sum of an array.

    🏁 Recap

    You learned:

    • ✅ Arrays (push, pop, map, filter, reduce)
    • ✅ Objects (keys, values, entries, nested structures)
    • ✅ Array of objects (most common real-world data format)
    • ✅ Real development patterns
    • ✅ How arrays & objects work together in every real application

    Arrays and objects are 80% of JavaScript data handling. Once you master them, you can build anything.

    📋 Quick Reference — Arrays & Objects

    MethodWhat It Does
    map(fn)Transform every item, return new array
    filter(fn)Keep items where fn returns true
    reduce(fn, init)Combine all items into one value
    Object.keys(obj)Array of all property names
    arr.push(item)Add to end of array

    Lesson 6 Complete — Arrays & Objects!

    You now know how to store ordered data with arrays and named data with objects — the foundation of almost all JavaScript applications.

    Up next: ES6+ Modern JavaScript — supercharge your code with the latest JS features! 🚀

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service