JavaScript Arrays

This lesson introduces JavaScript arrays, covering how to create and access arrays, use common methods like push, pop, shift, and unshift, iterate through elements efficiently, and work with multi-dimensional arrays for structured data handling.

What Are Arrays in JavaScript?

An array is a special variable that can hold multiple values at once, organized in a list. Instead of creating separate variables for each item, you store them all in one array.

Think of arrays like:

  • A shopping list with multiple items
  • A playlist containing many songs
  • A photo album with multiple pictures
  • A contact list with many names

Why Use Arrays?

Arrays solve a common problem: storing and managing collections of related data.

Without arrays (repetitive and messy):
javascript
let fruit1 = "apple";
let fruit2 = "banana";
let fruit3 = "orange";
let fruit4 = "grape";
// Hard to manage!

With arrays (clean and organized):

javascript
let fruits = ["apple", "banana", "orange", "grape"];
// All fruits in one place!

Creating and Accessing Arrays

How to Create Arrays

There are two main ways to create arrays:

javascript
// Method 1: Array literal (most common)
let colors = ["red", "green", "blue"];

// Method 2: Array constructor (rarely used)
let numbers = new Array(1, 2, 3, 4, 5);

// Empty array
let emptyArray = []
Example 1: Creating Your First Array
javascript
// Create an array of favorite foods
let favoriteFoods = ["pizza", "tacos", "sushi", "burger"];

console.log(favoriteFoods);  
// Output: ["pizza", "tacos", "sushi", "burger"]

// Check how many items
console.log("I have " + favoriteFoods.length + " favorite foods");
// Output: I have 4 favorite foods

Accessing Array Elements

Access items using their index (position number), starting from 0:

javascript
let colors = ["red", "green", "blue", "yellow"];

// Access by index
console.log(colors[0]);  // red (first item)
console.log(colors[1]);  // green (second item)
console.log(colors[2]);  // blue (third item)
console.log(colors[3]);  // yellow (fourth item)

You can change values by accessing their index:

You can change values by accessing their index:
javascript
let fruits = ["apple", "banana", "orange"];

// Change the second item
fruits[1] = "mango";
console.log(fruits);  // ["apple", "mango", "orange"]

// Add item at specific index
fruits[3] = "grape";
console.log(fruits);  // ["apple", "mango", "orange", "grape"]

// Change first item
fruits[0] = "strawberry";
console.log(fruits);  // ["strawberry", "mango", "orange", "grape"]

Common Array Methods: Adding and Removing Items

JavaScript provides built-in methods to manipulate arrays easily.

Push: Add to End

push() adds one or more items to the end of an array.

javascript
let fruits = ["apple", "banana"];

fruits.push("orange");
console.log(fruits);  // ["apple", "banana", "orange"]

// Add multiple items
fruits.push("grape", "mango");
console.log(fruits);  // ["apple", "banana", "orange", "grape", "mango"]

// push() returns new length
let newLength = fruits.push("kiwi");
console.log(newLength);  // 6
console.log(fruits);     // ["apple", "banana", "orange", "grape", "mango", "kiwi"]

Pop: Remove from End

pop() removes and returns the last item from an array.

javascript
let fruits = ["apple", "banana", "orange"];

let removed = fruits.pop();
console.log(removed);  // "orange"
console.log(fruits);   // ["apple", "banana"]

// Keep popping
fruits.pop();
console.log(fruits);  // ["apple"]

fruits.pop();
console.log(fruits);  // []

Shift: Remove from Beginning

shift() removes and returns the first item from an array.

javascript
let fruits = ["apple", "banana", "orange"];

let removed = fruits.shift();
console.log(removed);  // "apple"
console.log(fruits);   // ["banana", "orange"]

// Keep shifting
fruits.shift();
console.log(fruits);  // ["orange"]

Unshift: Add to Beginning

javascript
let fruits = ["banana", "orange"];

fruits.unshift("apple");
console.log(fruits);  // ["apple", "banana", "orange"]

// Add multiple items
fruits.unshift("grape", "mango");
console.log(fruits);  // ["grape", "mango", "apple", "banana", "orange"]

Iterating Through Arrays

Iterating means going through each item in an array to read or process it.

Method 1: For Loop (Traditional)
javascript
let fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// Output:
// apple
// banana
// orange

Method 2: For...of Loop (Modern)
javascript
let fruits = ["apple", "banana", "orange"];

fruits.forEach(function(fruit) {
  console.log(fruit);
});

// With arrow function (shorter)
fruits.forEach(fruit => console.log(fruit));

// Output:
// apple
// banana
// orange

Multi-Dimensional Arrays

A multi-dimensional array is an array that contains other arrays. Think of it as a grid or table with rows and columns.
Understanding 2D Arrays
javascript
let row = [1, 2, 3];

// Array of arrays (2D)
let grid = [
  [1, 2, 3],    // Row 0
  [4, 5, 6],    // Row 1
  [7, 8, 9]     // Row 2
];

// Visualize as:
// 1  2  3
// 4  5  6
// 7  8  9

Accessing 2D Array Elements

javascript
Use two indices: [row][column]
let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Access elements
console.log(grid[0][0]);  // 1 (row 0, column 0)
console.log(grid[0][1]);  // 2 (row 0, column 1)
console.log(grid[1][2]);  // 6 (row 1, column 2)
console.log(grid[2][0]);  // 7 (row 2, column 0)

// Get entire row
console.log(grid[0]);  // [1, 2, 3]
console.log(grid[1]);  // [4, 5, 6]
Example 1: Classroom Seating Chart
javascript
let classroom = [
  ["Alice", "Bob", "Charlie"],     // Row 1
  ["Diana", "Eve", "Frank"],       // Row 2
  ["Grace", "Henry", "Iris"]       // Row 3
];

// Who sits in row 2, seat 1?
console.log(classroom[1][0]);  // Diana

// Who sits in row 3, seat 3?
console.log(classroom[2][2]);  // Iris

// Get all students in row 1
console.log("Row 1:", classroom[0]);
// Row 1: ["Alice", "Bob", "Charlie"]

Iterating Through 2D Arrays

Use nested loops to go through all elements:,/p

javascript
let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Nested for loops
for (let row = 0; row < grid.length; row++) {
  for (let col = 0; col < grid[row].length; col++) {
    console.log("Position [" + row + "][" + col + "] = " + grid[row][col]);
  }
}

// Output:
// Position [0][0] = 1
// Position [0][1] = 2
// Position [0][2] = 3
// Position [1][0] = 4
// ... and so on

Frequently Asked Questions

This comes from how computers store data in memory. Arrays are stored as memory offsets from a starting point. The first item is 0 positions away, the second is 1 position away, etc. Most programming languages use zero-indexing.

JavaScript returns undefined (it doesn't crash). Always check array length or use proper bounds

Yes! JavaScript arrays can mix types

push() adds to the end (faster), unshift() adds to the beginning (slower, shifts all elements). Use push when order doesn't matter for better performance.