JavaScript Arrays

1. What is an Array?

An array is a special variable that can store multiple values in a single variable. Arrays can store any type of data (numbers, strings, objects, etc.). In JavaScript, arrays are dynamic, meaning they can grow or shrink in size.

2. Creating Arrays

There are two common ways to create an array:

A. Array Literal (Recommended)

let fruits = ["Apple", "Banana", "Mango"];
        

B. Array Constructor

let numbers = new Array(1, 2, 3, 4, 5);
        

3. Accessing & Modifying Elements

You access array elements by referring to the index number. Array indexes start with 0.

let colors = ["Red", "Green", "Blue"];

// Accessing
document.write(colors[0]); // "Red"
document.write(colors[2]); // "Blue"

// Modifying
colors[1] = "Yellow";
document.write(colors); // ["Red", "Yellow", "Blue"]

// Length Property
document.write(colors.length); // 3
        
Output will appear here...

4. Basic Array Methods

These methods allow you to add or remove elements from an array.

let stack = ["A", "B", "C"];

stack.push("D");    // ["A", "B", "C", "D"]
stack.pop();        // ["A", "B", "C"]
stack.unshift("Z"); // ["Z", "A", "B", "C"]
stack.shift();      // ["A", "B", "C"]

document.write(stack);
        
Output will appear here...

5. Modifying & Searching

let months = ["Jan", "March", "April", "June"];

// Insert "Feb" at index 1
months.splice(1, 0, "Feb"); 

// Search
document.write(months.includes("March")); // true
document.write(months.indexOf("June"));   // 4

document.write(months);
        
Output will appear here...

6. Iterating Over Arrays

You can loop through arrays using standard loops or modern methods.

let heroes = ["Batman", "Superman", "Ironman"];

// 1. for loop
for(let i=0; i < heroes.length; i++) {
    document.write(heroes[i]);
}

// 2. for...of loop (Modern)
for(let hero of heroes) {
    document.write(hero);
}

// 3. forEach method
heroes.forEach((hero, index) => {
    document.write(`${index}: ${hero}`);
});
        
Output will appear here...

7. High-Order Methods (ES6)

These methods are powerful for transforming data without mutating the original array.

let nums = [1, 2, 3, 4, 5];

// Map: Square each number
let squared = nums.map(n => n * n);
document.write("Squared:", squared);

// Filter: Keep only even numbers
let evens = nums.filter(n => n % 2 === 0);
document.write("Evens:", evens);

// Reduce: Sum of all numbers
let sum = nums.reduce((total, n) => total + n, 0);
document.write("Sum:", sum);
        
Output will appear here...

8. Comparison Table: Array Methods

Method Purpose Modifies Original?
push() Add element at end Yes
pop() Remove last element Yes
shift() Remove first element Yes
unshift() Add element at start Yes
splice() Add/remove element anywhere Yes
slice() Extract portion No
map() Transform elements No
filter() Filter elements No
reduce() Reduce to single value No
✅ Best Practice: Use map, filter, reduce for functional programming and push/pop/splice for direct modifications.

Practice Questions

Test your understanding of JavaScript Arrays.

Easy

Q1: Create an array and add an element to the end.

  • Create an array named colors containing "red", "green", and "blue".
  • Use the appropriate array method to add "yellow" to the end of the array.
  • Log the updated array to the console.
Easy

Q2: Remove the first element from an array.

  • Declare an array: let numbers = [1, 2, 3];.
  • Use the correct array method to remove the first element.
  • Log both the modified array and the removed element to the console.
Medium

Q3: Find the index of an item in an array.

  • Declare an array: let fruits = ["banana", "apple", "orange"];.
  • Find and log the index of "apple".
  • Find and log the index of an item that doesn't exist (e.g., "grape") to see what it returns.
Medium

Q4: Transform an array using the map() method.

  • Start with an array of numbers: let nums = [1, 2, 3, 4];.
  • Use the map() method to create a new array.
  • Inside the map function, multiply each number by 2.
  • Log the new doubled array to the console.
Hard

Q5: Calculate the sum of an array using reduce().

  • Declare an array of prices: let prices = [10, 20, 30];.
  • Use the reduce() method to calculate the total sum.
  • Pass a reducer function that adds the current value to an accumulator (start at 0).
  • Log the final total to the console.

Answer

Code: