JavaScript Arrays
An array is a special variable that can hold multiple values in a single container. Instead of creating separate variables for each item, an array stores them all in an ordered list.
Real-life analogy: Think of an array like a numbered shelf. Each shelf slot has a position number (index), and each slot holds one item.
Creating an Array
Arrays are created using square brackets [ ]. Items are separated by commas.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]Arrays can hold any type of data — strings, numbers, booleans, objects, and even other arrays.
let mixed = [42, "Hello", true, null, { name: "Raj" }];
console.log(mixed);Accessing Array Elements
Each item in an array has a position called an index. Indexing starts at 0 — so the first item is at index 0, the second at index 1, and so on.
let cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"];
console.log(cities[0]); // Delhi
console.log(cities[1]); // Mumbai
console.log(cities[3]); // Kolkata
console.log(cities[10]); // undefined (no item at index 10)Array Length
The length property returns the number of items in an array.
let numbers = [10, 20, 30, 40, 50];
console.log(numbers.length); // 5
// Access last element using length
console.log(numbers[numbers.length - 1]); // 50Modifying Array Elements
Array elements can be changed by assigning a new value to a specific index.
let colors = ["Red", "Green", "Blue"];
colors[1] = "Yellow";
console.log(colors); // ["Red", "Yellow", "Blue"]Adding and Removing Elements
push() — Add to the End
let animals = ["Dog", "Cat"];
animals.push("Bird");
console.log(animals); // ["Dog", "Cat", "Bird"]pop() — Remove from the End
let animals = ["Dog", "Cat", "Bird"];
let removed = animals.pop();
console.log(removed); // Bird
console.log(animals); // ["Dog", "Cat"]unshift() — Add to the Beginning
let numbers = [2, 3, 4];
numbers.unshift(1);
console.log(numbers); // [1, 2, 3, 4]shift() — Remove from the Beginning
let numbers = [1, 2, 3, 4];
let first = numbers.shift();
console.log(first); // 1
console.log(numbers); // [2, 3, 4]Common Array Methods
indexOf() — Find the Position of an Element
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.indexOf("Grape")); // -1 (not found)includes() — Check if an Element Exists
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Mango")); // true
console.log(fruits.includes("Grapes")); // falsesplice() — Add or Remove at a Specific Position
let letters = ["A", "B", "D", "E"];
// Insert "C" at index 2, remove 0 elements
letters.splice(2, 0, "C");
console.log(letters); // ["A", "B", "C", "D", "E"]
// Remove 1 element at index 3
letters.splice(3, 1);
console.log(letters); // ["A", "B", "C", "E"]slice() — Copy a Portion of an Array
let numbers = [10, 20, 30, 40, 50];
// slice(start, end) — end is not included
let part = numbers.slice(1, 4);
console.log(part); // [20, 30, 40]
console.log(numbers); // Original unchanged: [10, 20, 30, 40, 50]join() — Convert Array to String
let words = ["Hello", "World", "JavaScript"];
console.log(words.join(" ")); // Hello World JavaScript
console.log(words.join("-")); // Hello-World-JavaScript
console.log(words.join("")); // HelloWorldJavaScriptreverse() — Reverse the Array
let nums = [1, 2, 3, 4, 5];
nums.reverse();
console.log(nums); // [5, 4, 3, 2, 1]sort() — Sort the Array
let fruits = ["Banana", "Apple", "Cherry", "Mango"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]
// For numbers, always use a compare function
let numbers = [40, 100, 5, 25, 10];
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers); // [5, 10, 25, 40, 100]
numbers.sort((a, b) => b - a); // Descending
console.log(numbers); // [100, 40, 25, 10, 5]concat() — Merge Two Arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4, 5, 6]flat() — Flatten Nested Arrays
let nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]Looping Through Arrays
Using for Loop
let scores = [85, 90, 78, 92, 88];
for (let i = 0; i < scores.length; i++) {
console.log("Score " + (i + 1) + ":", scores[i]);
}Using for...of (Recommended)
let scores = [85, 90, 78, 92, 88];
for (let score of scores) {
console.log(score);
}
// Output: 85, 90, 78, 92, 88forEach() Method
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
// Output:
// 0: Apple
// 1: Banana
// 2: MangoSpread Operator with Arrays
The spread operator ... expands an array into individual elements.
let nums = [3, 5, 1, 9, 2];
let max = Math.max(...nums);
console.log(max); // 9
// Copy an array
let original = [1, 2, 3];
let copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] — unchanged
console.log(copy); // [1, 2, 3, 4]Array Destructuring
Destructuring is a clean way to extract values from an array into individual variables.
let colors = ["Red", "Green", "Blue"];
let [first, second, third] = colors;
console.log(first); // Red
console.log(second); // Green
console.log(third); // BluePractical Example — Student Score Tracker
let scores = [75, 88, 62, 91, 70];
let total = 0;
for (let score of scores) {
total += score;
}
let average = total / scores.length;
let highest = Math.max(...scores);
let lowest = Math.min(...scores);
console.log("Total:", total); // 386
console.log("Average:", average); // 77.2
console.log("Highest:", highest); // 91
console.log("Lowest:", lowest); // 62Key Points to Remember
- Arrays store multiple values in one variable using square brackets
[ ] - Array indexing starts at 0
- Use
push()/pop()to add/remove from the end - Use
unshift()/shift()to add/remove from the beginning splice()modifies an array in place;slice()returns a copy- Use
for...oforforEach()for clean array iteration - The spread operator
...is great for copying and merging arrays - Destructuring allows extracting values into variables in a single line
