Arrays in JavaScript Explained: Methods and Examples (Beginner 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.
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]
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:
| Method | What it does | Returns |
|---|---|---|
| push(item) | Add item to the END | New length |
| pop() | Remove item from END | Removed item |
| unshift(item) | Add item to BEGINNING | New length |
| shift() | Remove item from BEGINNING | Removed item |
| splice(i, n) | Remove n items starting at index i | Removed items array |
| slice(start, end) | Copy portion without modifying original | New array |
| indexOf(item) | Find index of first match | Index or -1 |
| includes(item) | Check if item exists | true or false |
| join(sep) | Convert array to string | String |
| reverse() | Reverse array in place | Reversed array |
| sort() | Sort items (default: alphabetical) | Sorted array |
| concat(arr) | Combine two arrays | New array |
| flat() | Flatten nested arrays one level | Flat 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
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"]
["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
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]
95Multidimensional 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)}`); });
1 6 8
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Sara: avg = 84.3
Ali: avg = 73.3
Ahmed: avg = 91.7Performance 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:
const prevents accidental reassignment while still allowing you to modify contents.[...arr1, ...arr2] is more readable and often faster than arr1.concat(arr2).const len = arr.length before a for loop avoids recalculating length on every iteration.arr.find() stops at the first match. filter()[0] scans the whole array unnecessarily.map, filter, slice which return new arrays. Avoid splice when you need the original..filter().map().reduce() is powerful but each creates a new array — avoid on very large datasets.π️ Practice Questions — Test Your Array Knowledge
✅ Complete Summary — Arrays in JavaScript
π’ 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
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!
π» for more posts
- π history of JavaScript
- π variables in JavaScript
- π data types in JavaScript
- π Functions in JavaScript
- π Conditional statements in JavaScript
- π objects in JavaScript
- π loops in JavaScript
- π operators in JavaScript
- π DOM Manipulation in JavaScript
- π What is DOM in JavaScript
- π JavaScript scope and hoisting
Comments
Post a Comment