2.9 Module 2 · Variables, Data Types & Functions

Arrays

Learn how to store, access, and manipulate ordered collections of values — the most essential data structure in JavaScript for handling lists of any kind.

1

Definition

An array in JavaScript is a special type of object used to store multiple values in a single variable, where each value is stored at a specific index starting from 0. Arrays can hold elements of any data type — numbers, strings, booleans, objects, or even other arrays.

Arrays are ordered, meaning the position of each element is meaningful and preserved. They come with a rich set of built-in methods for adding, removing, searching, and transforming their contents.

2

Simple Way

An array is like a numbered list — instead of creating a separate variable for each value, you put them all in one place:

[] Square brackets create an array — ["red", "blue", "green"]
index Each item has a position — first element is always at index 0
.length The number of elements — last index is always length - 1
methods Built-in tools to add, remove, search, and loop through items
3

Code Examples

Example 1 — Creating & Accessing an Array
let fruits = ["apple", "banana", "mango"];

console.log(fruits);      // full array
console.log(fruits[0]);   // "apple"  — first element
console.log(fruits[2]);   // "mango"  — last element
console.log(fruits.length); // 3
Output
Click ▶ Run to execute
Explanation
  • Indices start at 0 — the first element is fruits[0], the last is fruits[length - 1]
  • length is always one more than the last valid index
  • Accessing an index that doesn't exist returns undefined — no error
Example 2 — push(), pop(), shift(), unshift()
let numbers = [1, 2, 3];

numbers.push(4);      // add at END   → [1, 2, 3, 4]
console.log(numbers);

numbers.pop();        // remove from END → [1, 2, 3]
console.log(numbers);

numbers.unshift(0);   // add at START → [0, 1, 2, 3]
console.log(numbers);

numbers.shift();      // remove from START → [1, 2, 3]
console.log(numbers);
Output
Click ▶ Run to execute
Explanation
  • push() / pop() — add and remove at the end
  • unshift() / shift() — add and remove at the start
  • All four methods mutate the original array — they change it in place
Example 3 — Looping Through an Array
let colors = ["red", "green", "blue"];

// Classic for loop
for (let i = 0; i < colors.length; i++) {
  console.log(i + ": " + colors[i]);
}

// Modern for...of loop
for (let color of colors) {
  console.log(color.toUpperCase());
}
Output
Click ▶ Run to execute
Explanation
  • The classic for loop uses an index — useful when you need the position
  • for...of gives each element directly — cleaner when you only need the value
  • Always use array.length as the loop boundary — never hardcode the count
Example 4 — includes(), indexOf(), join()
let fruits = ["apple", "banana", "mango"];

console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape"));  // false

console.log(fruits.indexOf("mango"));   // 2
console.log(fruits.indexOf("grape"));   // -1 (not found)

console.log(fruits.join(", ")); // "apple, banana, mango"
Output
Click ▶ Run to execute
Explanation
  • includes() → returns true/false — great for existence checks
  • indexOf() → returns the position, or -1 if not found
  • join(separator) → converts the array to a single string with each element separated by the given character
Example 5 — Multi-Dimensional Array
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[0][1]); // row 0, col 1 → 2
console.log(matrix[1][2]); // row 1, col 2 → 6
console.log(matrix[2][0]); // row 2, col 0 → 7
Output
Click ▶ Run to execute
Explanation
  • An array of arrays — the outer index selects the row, the inner index selects the column
  • Used for grids, tables, game boards, and matrix-style data
  • Access pattern: array[row][column]
4

Real-Life Example

Think of an array like a shopping list — one place to hold all related items:

[ ]
The list itself — one container holding all your items
index
Item number on the list — Milk is item 0, Bread is item 1
push()
Adding a new item at the bottom of the list
pop()
Crossing off the last item once you've picked it up
includes()
Checking whether "Eggs" is already on the list
join()
Reading the whole list aloud as one sentence
5

HTML + JavaScript Example

Click ▶ Preview, then press the button to render an array of fruits as a live list on the page — using join() and a loop.

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

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

  <script>
    function showFruits() {
      let fruits = ["Apple", "Banana", "Mango", "Grapes"];

      let listHtml = "<b>Fruits array:</b> [" + fruits.join(", ") + "]<br><br>";
      listHtml += "<b>Each fruit:</b><ul style='margin:6px 0 0 20px'>";

      for (let i = 0; i < fruits.length; i++) {
        listHtml += `<li>[${i}] ${fruits[i]}</li>`;
      }

      listHtml += "</ul>";
      listHtml += `<br><b>Total items:</b> ${fruits.length}`;

      document.getElementById("output").innerHTML = listHtml;
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Colors array
Starter code
let colors = ["red", "green", "blue"];
  • Print the first element using index 0
  • Print the last element using colors.length - 1
  • Print the total count using colors.length
Medium Task 2 — Modify an array
Starter code
let nums = [10, 20, 30];
  • Add 40 to the end using push() — print the array
  • Remove the last element using pop() — print the array again
  • Print the final length and confirm it is back to 3
7

MCQs

Q1
What is the index of the first element in an array?
let arr = ["a", "b", "c"];
console.log(arr[0]);
Output
Run it to verify
  • A 1
  • B 0
  • C -1
  • D undefined
💡 B is correct. Array indexing in JavaScript starts at 0. The first element is always at index 0, the last at length - 1.
Q2
What does push() do?
let arr = [1, 2, 3];
arr.push(4);
console.log(arr);
Output
Run it to verify
  • A Removes an element
  • B Adds an element at the start
  • C Adds an element at the end
  • D Sorts the array
💡 C is correct. push() appends one or more elements to the end of the array and returns the new length. To add at the start, use unshift() instead.
Q3
What is the output?
let arr = [1, 2, 3];
console.log(arr[1]);
Output
Run it to verify
  • A 1
  • B 2
  • C 3
  • D Error
💡 B is correct. Index 1 refers to the second element — 2. Index 0 is 1, index 2 is 3.
8

Pro Tips & Extra Knowledge

  • 01

    Arrays can store mixed data types — numbers, strings, booleans, objects, or even other arrays all in one:

    Mixed type array
    let data = [1, "Aman", true, null, { score: 95 }];
    
    console.log(data[0]);         // 1
    console.log(data[1]);         // "Aman"
    console.log(data[4].score);  // 95
    Output
    Click ▶ Run to execute
  • 02

    Use the spread operator (...) to copy an array without mutation — never use arr2 = arr1 if you want an independent copy:

    Safe array copy with spread
    let original = [1, 2, 3];
    let copy = [...original]; // independent copy
    
    copy.push(4);
    
    console.log(original); // [1, 2, 3] — unchanged
    console.log(copy);     // [1, 2, 3, 4]
    Output
    Click ▶ Run to execute
  • 03

    Avoid assigning values to arbitrary high indices — it creates sparse arrays with empty slots that cause unexpected undefined values:

    Sparse array warning
    let arr = [1, 2, 3];
    arr[9] = "value"; // creates slots 3–8 as empty
    
    console.log(arr.length); // 10 — not 4!
    console.log(arr[5]);     // undefined — empty slot
    Output
    Click ▶ Run to execute
  • 04

    Use Array.isArray() — not typeof — to correctly detect arrays in your validation logic:

    Detecting arrays reliably
    let arr = [1, 2, 3];
    let obj = { a: 1 };
    
    console.log(typeof arr);          // "object" — not helpful!
    console.log(Array.isArray(arr));  // true  — correct
    console.log(Array.isArray(obj));  // false — correct
    Output
    Click ▶ Run to execute
Mini Challenge

An element is added then removed — trace the array at each step before running.

What does this print?
let arr = [10, 20, 30];

arr.push(40);
arr.pop();

console.log(arr.length);
console.log(arr[2]);
Output
Think first, then run!
Step-by-Step Explanation
// Start:  arr = [10, 20, 30]   length = 3
//          idx:   0   1   2

// Step 1: arr.push(40)
//         Adds 40 at the end
//         arr = [10, 20, 30, 40]   length = 4

// Step 2: arr.pop()
//         Removes the last element (40)
//         arr = [10, 20, 30]   length = 3

// Step 3: console.log(arr.length)
//         push added one, pop removed one — net change: zero
//         Output → 3

// Step 4: console.log(arr[2])
//         Index 2 holds the value 30
//         Output → 30

// Final output:
//   3    ← length is back to its original value
//   30   ← arr[2] is the third element, unchanged

// Key takeaway:
//   push() and pop() are mirror operations —
//   performing both in sequence leaves the array unchanged.