Arrays in JavaScript Explained: Methods and Examples (Beginner Guide)

Arrays in JavaScript: Methods + Examples — Complete Guide (2026)
πŸ“‹ JavaScript Arrays · Complete Guide

Arrays in JavaScript:
Methods + Examples

Complete guide to JavaScript arrays — create, index, push/pop, map, filter, reduce, forEach, destructuring, spread operator, multidimensional arrays, and performance tips.

⏱️ 10 min readπŸ“‹ All MethodsπŸ’» Real ExamplesπŸ‹️ Practice

What is an Array and How to Create One?

An array is a special variable that can hold multiple values in a single container. Instead of creating separate variables for each item — fruit1 = "apple", fruit2 = "banana" — you store them all in one organized list. Arrays are one of the most powerful and most used data structures in all of JavaScript.

Arrays are zero-indexed — the first item is at position 0, not 1. They can store any data type — strings, numbers, booleans, objects, or even other arrays. They are technically objects in JavaScript, which is why typeof [] returns "object".

// Creating arrays — array literal (recommended)

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

const numbers = [10, 20, 30, 40, 50];

const mixed   = ["Sara", 22, true, null];  // mixed types

const empty   = [];                           // empty array

// Accessing by index (starts at 0)

console.log(fruits[0]);   // "apple"  — first item

console.log(fruits[2]);   // "mango"  — third item

console.log(fruits[10]);  // undefined — out of range

// Useful array properties

console.log(fruits.length);         // 4 — total items

console.log(fruits[fruits.length-1]);// "orange" — last item

// Modify a specific index

fruits[1] = "grape";

console.log(fruits);  // ["apple","grape","mango","orange"]

// Array() constructor (alternative)

const threeZeros = new Array(3).fill(0);

console.log(threeZeros);  // [0, 0, 0]
▶ Output
apple mango undefined 4 orange ["apple","grape","mango","orange"] [0, 0, 0]
[ ]

Common Array Methods — Add, Remove, Find, Sort

JavaScript arrays come with dozens of built-in methods. Here are the most important ones that you will use in almost every project:

MethodWhat it doesReturns
push(item)Add item to the ENDNew length
pop()Remove item from ENDRemoved item
unshift(item)Add item to BEGINNINGNew length
shift()Remove item from BEGINNINGRemoved item
splice(i, n)Remove n items starting at index iRemoved items array
slice(start, end)Copy portion without modifying originalNew array
indexOf(item)Find index of first matchIndex or -1
includes(item)Check if item existstrue or false
join(sep)Convert array to stringString
reverse()Reverse array in placeReversed array
sort()Sort items (default: alphabetical)Sorted array
concat(arr)Combine two arraysNew array
flat()Flatten nested arrays one levelFlat array
let arr = [10, 20, 30];

arr.push(40);          // [10,20,30,40]

arr.unshift(5);        // [5,10,20,30,40]

arr.pop();              // removes 40 → [5,10,20,30]

arr.shift();            // removes 5  → [10,20,30]

console.log(arr.indexOf(20));    // 1

console.log(arr.includes(99));   // false

console.log(arr.join(" - "));     // "10 - 20 - 30"

let names = ["Charlie", "Alice", "Bob"];

names.sort();

console.log(names);   // ["Alice","Bob","Charlie"]

// Numeric sort — must provide compare function!

let nums = [30, 5, 100, 2];

nums.sort((a, b) => a - b);

console.log(nums);    // [2, 5, 30, 100]

// slice — non-destructive copy

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

const first2 = fruits.slice(0, 2);

console.log(first2);  // ["apple","banana"] — original untouched
▶ Output
1 false "10 - 20 - 30" ["Alice","Bob","Charlie"] [2, 5, 30, 100] ["apple","banana"]
πŸ”„

map(), filter() and reduce() — The Most Powerful Methods

These three methods are the heart of modern JavaScript array programming. They are higher-order functions — they each take a callback function and apply it to the array. Mastering these three methods will make you dramatically more productive as a JavaScript developer.

const students = [

  { name: "Sara",   score: 85 },

  { name: "Ali",    score: 45 },

  { name: "Ahmed",  score: 92 },

  { name: "Zara",   score: 67 },

  { name: "Omar",   score: 38 },

];

// MAP — transform every item, returns NEW array of same length

const names = students.map(s => s.name);

console.log(names);

// ["Sara","Ali","Ahmed","Zara","Omar"]

const grades = students.map(s => ({

  name:  s.name,

  grade: s.score >= 50 ? "Pass ✅" : "Fail ❌"

}));

console.log(grades);

// FILTER — keep only items that match condition

const passed = students.filter(s => s.score >= 50);

console.log("Passed:", passed.map(s => s.name));

// Passed: ["Sara","Ahmed","Zara"]

const topStudents = students.filter(s => s.score >= 80);

console.log("Top:", topStudents.map(s => s.name));

// Top: ["Sara","Ahmed"]

// REDUCE — collapse array to single value

const totalScore = students.reduce((sum, s) => sum + s.score, 0);

const avgScore   = totalScore / students.length;

console.log("Total: " + totalScore);   // Total: 327

console.log("Average: " + avgScore);   // Average: 65.4

// Chaining methods — filter THEN map

const passedNames = students

  .filter(s => s.score >= 50)

  .map(s => s.name.toUpperCase());

console.log(passedNames);  // ["SARA","AHMED","ZARA"]
▶ Output
["Sara","Ali","Ahmed","Zara","Omar"] [{name:"Sara",grade:"Pass ✅"}, ...] Passed: ["Sara","Ahmed","Zara"] Top: ["Sara","Ahmed"] Total: 327 Average: 65.4 ["SARA","AHMED","ZARA"]
πŸ”

Iteration, Array Destructuring & Spread Operator

Iteration means looping through every item. Destructuring extracts values from arrays into named variables in one clean line. The spread operator (...) expands an array into individual elements — used for copying, merging, and passing array items as arguments.

const scores = [85, 92, 78, 95, 60];

// forEach — loop without creating new array

scores.forEach((score, index) => {

  console.log(`Student ${index+1}: ${score}`);

});

// for...of — cleanest way to iterate

for (let score of scores) {

  if (score > 90) console.log(`⭐ Excellent: ${score}`);

}

// Array DESTRUCTURING — extract values into variables

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

const [first, second, third] = fruits;

console.log(first);   // apple

console.log(second);  // banana

// Skip items in destructuring

const [, , last] = fruits;

console.log(last);    // mango

// Rest in destructuring

const [head, ...tail] = [1, 2, 3, 4, 5];

console.log(head);  // 1

console.log(tail);  // [2,3,4,5]

// SPREAD operator — expand array

const arr1 = [1, 2, 3];

const arr2 = [4, 5, 6];

// Merge arrays

const merged = [...arr1, ...arr2];

console.log(merged);   // [1,2,3,4,5,6]

// Copy array (not reference)

const copy = [...arr1];

copy.push(99);

console.log(arr1);    // [1,2,3] — original untouched!

console.log(copy);    // [1,2,3,99]

// Spread to pass as function arguments

const maxScore = Math.max(...scores);

console.log(maxScore);  // 95
▶ Output
Student 1: 85 Student 2: 92 ... ⭐ Excellent: 92 ⭐ Excellent: 95 apple banana mango 1 [2,3,4,5] [1,2,3,4,5,6] [1,2,3] [1,2,3,99] 95
[][]

Multidimensional Arrays — Arrays Inside Arrays

A multidimensional array (most commonly a 2D array) is an array where each element is itself another array. They are used to represent tables, grids, matrices, and any data that has rows and columns — like a spreadsheet, a game board, or a seating chart.

// 2D array — array of arrays (like a table)

const matrix = [

  [1, 2, 3],   // row 0

  [4, 5, 6],   // row 1

  [7, 8, 9]    // row 2

];

// Access: matrix[row][column]

console.log(matrix[0][0]);  // 1 — row 0, col 0

console.log(matrix[1][2]);  // 6 — row 1, col 2

console.log(matrix[2][1]);  // 8 — row 2, col 1

// Loop through 2D array — nested loops

for (let row of matrix) {

  console.log(row.join(" | "));

}

// 1 | 2 | 3

// 4 | 5 | 6

// 7 | 8 | 9

// Real use case — student grade table

const grades = [

  ["Sara",  85, 90, 78],

  ["Ali",   72, 68, 80],

  ["Ahmed", 95, 88, 92],

];

grades.forEach(student => {

  const [name, ...scores] = student;

  const avg = scores.reduce((s, n) => s + n, 0) / scores.length;

  console.log(`${name}: avg = ${avg.toFixed(1)}`);

});
▶ Output
1 6 8 1 | 2 | 3 4 | 5 | 6 7 | 8 | 9 Sara: avg = 84.3 Ali: avg = 73.3 Ahmed: avg = 91.7

Performance Tips — Write Faster, More Efficient Array Code

As your programs grow larger, array performance becomes important. Here are key tips that professional developers follow to keep array operations fast and memory-efficient:

✅ Use const for arrays
Declaring arrays with const prevents accidental reassignment while still allowing you to modify contents.
✅ Prefer spread over concat
[...arr1, ...arr2] is more readable and often faster than arr1.concat(arr2).
✅ Cache array length in loops
const len = arr.length before a for loop avoids recalculating length on every iteration.
✅ Use find() instead of filter()[0]
arr.find() stops at the first match. filter()[0] scans the whole array unnecessarily.
✅ Avoid mutating original arrays
Use map, filter, slice which return new arrays. Avoid splice when you need the original.
✅ Chain methods carefully
Chaining .filter().map().reduce() is powerful but each creates a new array — avoid on very large datasets.

πŸ‹️ Practice Questions — Test Your Array Knowledge

Q1: ["a","b","c"].indexOf("b")Answer: 1
Q2: [1,2,3].map(x => x * x)Answer: [1, 4, 9]
Q3: [10,3,7,5].filter(n => n > 5)Answer: [10, 7]
Q4: [1,2,3,4].reduce((s,n) => s+n, 0)Answer: 10
Q5: const [a,,c] = [1,2,3]a = 1, c = 3
Q6: [...["a","b"], ...["c","d"]]Answer: ["a","b","c","d"]

✅ Complete Summary — Arrays in JavaScript

πŸ”΅ Create: const arr = [item1, item2] — zero-indexed, can hold any data type
🟒 Add/Remove: push/pop (end), unshift/shift (start), splice (any position)
🟑 Search: indexOf, includes, find, findIndex — locate items efficiently
🟣 map(): Transform every item — returns new array of same length
🟠 filter(): Keep matching items — returns new array of same or fewer items
🩷 reduce(): Collapse to single value — totals, averages, object building
🩡 Destructuring: const [a, b, ...rest] = arr — extract into named variables
Spread ...arr: Copy, merge, and pass arrays as function arguments
πŸ“Œ Important Note

The three most important array methods to master first are map(), filter(), and reduce(). These three methods alone replace 90% of array loops in modern JavaScript. Once you can use them confidently, add find(), some(), and every() to your toolkit. Practice each method with real examples — build a student grade calculator, a shopping cart, or a task filter using only these methods!

Comments