JavaScript Arrays 101 — A Complete Beginner Guide
Learn how to create, access, modify, and loop through JavaScript arrays with practical, real-world examples

In the real world, we constantly deal with lists — a list of groceries, a playlist of songs, a leaderboard of top scorers. JavaScript arrays let you store and manage ordered collections of data in exactly the same way.
If you've been following the JavaScript Decoded series, you already know about storing data in variables, making decisions with Control Flow, building reusable Functions, and repeating actions with Loops.
Arrays are the next essential building block — they let you work with lists of multiple values using a single variable.
In this guide, you'll learn:
✅ What JavaScript arrays are and why they matter
✅ How to create arrays (3 different ways)
✅ How to access, add, update, and delete elements
✅ Essential array methods every beginner must know
✅ How to loop through arrays (5 ways)
✅ Destructuring, spread operator, and rest parameters
✅ Common beginner mistakes and how to avoid them
Let's get started! 🚀
What Is an Array in JavaScript?
An array is an ordered collection of values. Each value is called an element, and each element has a numeric position called an index (starting from 0).
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[2]); // "Mango"
Think of an array like a numbered shelf 🗄️ — each slot has a position, and you can access any item by its number.
Why Are Arrays Important?
Without arrays, you'd need separate variables for every item in a list:
// ❌ Without arrays — messy and unscalable
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
// ✅ With arrays — clean and scalable
let fruits = ["Apple", "Banana", "Mango"];
Arrays let you:
Store multiple values in a single variable
Loop through items efficiently
Sort, filter, and transform data easily
Model real-world lists — users, products, messages, etc.
How to Create Arrays in JavaScript
JavaScript gives you three main ways to create arrays. Let's explore each one.
1. Array Literal (Most Common)
The simplest and most common way — just use square brackets [].
let colors = ["Red", "Green", "Blue"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["Debesh", 22, true, null];
console.log(colors); // ["Red", "Green", "Blue"]
console.log(mixed); // ["Debesh", 22, true, null]
💡 Best Practice: Array literals are the go-to approach for creating arrays in day-to-day JavaScript.
2. Using new Array()
You can also create an array using the Array constructor.
let fruits = new Array("Apple", "Banana", "Mango");
console.log(fruits); // ["Apple", "Banana", "Mango"]
⚠️ Watch out! Passing a single number creates an array with that many empty slots, not an array with that number:
let arr = new Array(3);
console.log(arr); // [empty × 3]
console.log(arr.length); // 3
3. Using Array.from()
Array.from() creates a new array from any iterable or array-like object (like a string or a NodeList).
let letters = Array.from("Hello");
console.log(letters); // ["H", "e", "l", "l", "o"]
let nums = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(nums); // [1, 2, 3, 4, 5]
💡
Array.from()is especially useful when converting DOM collections (likedocument.querySelectorAll()) into real arrays.
How to Access and Modify Array Elements
Accessing Elements by Index
Array indices start at 0. The last element is at array.length - 1.
let fruits = ["Apple", "Banana", "Mango", "Grapes"];
console.log(fruits[0]); // "Apple" (first)
console.log(fruits[3]); // "Grapes" (last)
console.log(fruits[fruits.length - 1]); // "Grapes" (dynamic last)
console.log(fruits[10]); // undefined (out of bounds)
Using at() for Negative Indexing (ES2022)
The at() method supports negative indices — count from the end!
let fruits = ["Apple", "Banana", "Mango", "Grapes"];
console.log(fruits.at(0)); // "Apple"
console.log(fruits.at(-1)); // "Grapes" (last element)
console.log(fruits.at(-2)); // "Mango" (second to last)
💡
at(-1)is much cleaner thanarr[arr.length - 1]to get the last element.
Updating Elements
Simply assign a new value to a specific index.
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Strawberry";
console.log(fruits); // ["Apple", "Strawberry", "Mango"]
Checking the Length of an Array
The .length property tells you how many elements an array has.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length); // 3
How to Add and Remove Elements from Arrays
These are the most commonly used array methods for modifying arrays.
Adding Elements
| Method | What It Does | Modifies Original? |
|---|---|---|
push() |
Adds to the end | ✅ Yes |
unshift() |
Adds to the beginning | ✅ Yes |
let fruits = ["Apple", "Banana"];
fruits.push("Mango"); // Add to end
console.log(fruits); // ["Apple", "Banana", "Mango"]
fruits.unshift("Grapes"); // Add to beginning
console.log(fruits); // ["Grapes", "Apple", "Banana", "Mango"]
Removing Elements
| Method | What It Does | Modifies Original? |
|---|---|---|
pop() |
Removes from the end | ✅ Yes |
shift() |
Removes from the beginning | ✅ Yes |
let fruits = ["Grapes", "Apple", "Banana", "Mango"];
let last = fruits.pop(); // Removes "Mango"
console.log(last); // "Mango"
console.log(fruits); // ["Grapes", "Apple", "Banana"]
let first = fruits.shift(); // Removes "Grapes"
console.log(first); // "Grapes"
console.log(fruits); // ["Apple", "Banana"]
Using splice() — Add, Remove, or Replace at Any Position
splice() is the Swiss Army knife of array modification.
Syntax: array.splice(startIndex, deleteCount, ...itemsToAdd)
let fruits = ["Apple", "Banana", "Mango", "Grapes"];
// Remove 1 element at index 1
fruits.splice(1, 1);
console.log(fruits); // ["Apple", "Mango", "Grapes"]
// Insert "Strawberry" at index 1 (delete 0 items)
fruits.splice(1, 0, "Strawberry");
console.log(fruits); // ["Apple", "Strawberry", "Mango", "Grapes"]
// Replace element at index 2
fruits.splice(2, 1, "Pineapple");
console.log(fruits); // ["Apple", "Strawberry", "Pineapple", "Grapes"]
💡
splice()modifies the original array and returns the removed elements as a new array.
Essential Array Methods Every JavaScript Developer Must Know
These methods are the heart and soul of working with arrays in JavaScript. They don't mutate the original array — they return new arrays.
map() — Transform Every Element
Creates a new array by applying a function to each element.
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// Practical example: format user names
let users = ["debesh", "ankit", "priya"];
let formatted = users.map(name => name.charAt(0).toUpperCase() + name.slice(1));
console.log(formatted); // ["Debesh", "Ankit", "Priya"]
filter() — Keep Only Matching Elements
Creates a new array with elements that pass a condition.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]
// Practical example: filter active users
let users = [
{ name: "Debesh", active: true },
{ name: "Ankit", active: false },
{ name: "Priya", active: true }
];
let activeUsers = users.filter(user => user.active);
console.log(activeUsers);
// [{ name: "Debesh", active: true }, { name: "Priya", active: true }]
reduce() — Reduce to a Single Value
Reduces an entire array down to one value — a sum, an object, a string, anything.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // 15
// Practical example: count occurrences
let votes = ["yes", "no", "yes", "yes", "no", "yes"];
let tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc;
}, {});
console.log(tally); // { yes: 4, no: 2 }
💡
reduce()is the most powerful array method. If you can master it, you can solve almost any data transformation problem.
find() — Get the First Match
Returns the first element that matches a condition (or undefined if none).
let users = [
{ id: 1, name: "Debesh" },
{ id: 2, name: "Ankit" },
{ id: 3, name: "Priya" }
];
let user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Ankit" }
findIndex() — Get the Index of the First Match
Returns the index of the first matching element (or -1 if none).
let numbers = [10, 20, 30, 40, 50];
let index = numbers.findIndex(num => num > 25);
console.log(index); // 2 (the element 30 at index 2)
includes() — Check if an Element Exists
Returns true or false.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana")); // true
console.log(fruits.includes("Grapes")); // false
some() and every() — Test Conditions
let numbers = [1, 2, 3, 4, 5];
// some() — does at least ONE element pass?
console.log(numbers.some(n => n > 4)); // true
// every() — do ALL elements pass?
console.log(numbers.every(n => n > 0)); // true
console.log(numbers.every(n => n > 3)); // false
Quick Reference Table
| Method | Returns | Mutates? | Use Case |
|---|---|---|---|
map() |
New array | ❌ No | Transform each element |
filter() |
New array | ❌ No | Keep elements matching a condition |
reduce() |
Single value | ❌ No | Aggregate data |
find() |
Single element | ❌ No | Get first match |
findIndex() |
Index (number) | ❌ No | Get index of first match |
includes() |
Boolean | ❌ No | Check existence |
some() |
Boolean | ❌ No | At least one passes? |
every() |
Boolean | ❌ No | All pass? |
How to Sort and Reverse Arrays in JavaScript
sort() — Sort Elements
By default, sort() sorts elements as strings (alphabetically).
let fruits = ["Mango", "Apple", "Banana"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango"] ✅
⚠️ Gotcha: Sorting numbers alphabetically gives wrong results!
let numbers = [10, 5, 40, 25, 100];
numbers.sort();
console.log(numbers); // [10, 100, 25, 40, 5] ❌ — sorted as strings!
Fix: Always pass a compare function for numbers:
// Ascending order
numbers.sort((a, b) => a - b);
console.log(numbers); // [5, 10, 25, 40, 100] ✅
// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 25, 10, 5] ✅
reverse() — Reverse the Order
let letters = ["a", "b", "c", "d"];
letters.reverse();
console.log(letters); // ["d", "c", "b", "a"]
⚠️ Both
sort()andreverse()mutate the original array. UsetoSorted()andtoReversed()(ES2023) for immutable alternatives:
let numbers = [3, 1, 2];
let sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted); // [1, 2, 3] (new array)
console.log(numbers); // [3, 1, 2] (unchanged ✅)
How to Loop Through Arrays in JavaScript
There are 5 main ways to loop through arrays. Here's when to use each.
1. for Loop (Classic)
Use when you need full control over the index.
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(`\({i}: \){fruits[i]}`);
}
// 0: Apple
// 1: Banana
// 2: Mango
2. for...of Loop (Modern)
The cleanest way to iterate over values.
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
// Apple
// Banana
// Mango
3. forEach() Method
Executes a function for each element. Cannot break or return early.
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach((fruit, index) => {
console.log(`\({index}: \){fruit}`);
});
// 0: Apple
// 1: Banana
// 2: Mango
4. map() — Loop + Transform
Use when you want to create a new array from the loop.
let numbers = [1, 2, 3];
let squares = numbers.map(n => n * n);
console.log(squares); // [1, 4, 9]
5. for...in Loop (⚠️ Not Recommended for Arrays)
for...in iterates over property keys (indices as strings). It can include inherited properties too.
let fruits = ["Apple", "Banana", "Mango"];
for (let index in fruits) {
console.log(index, typeof index); // "0" string, "1" string, "2" string
}
⚠️ Don't use
for...infor arrays. Usefor...oforforEach()instead.for...inis designed for objects.
Which Loop Should You Use?
| Loop | Best For | Can Break? |
|---|---|---|
for |
When you need the index | ✅ Yes |
for...of |
Simple iteration over values | ✅ Yes |
forEach() |
Running a function on each item | ❌ No |
map() |
Transforming into a new array | ❌ No |
for...in |
❌ Don't use for arrays | ✅ Yes |
Slice vs Splice — Understanding the Difference
These two methods sound similar but work very differently.
slice() — Extract a Portion (Non-Mutating)
Returns a new array containing a portion of the original.
Syntax: array.slice(startIndex, endIndex) — end is not included.
let fruits = ["Apple", "Banana", "Mango", "Grapes", "Pineapple"];
let sliced = fruits.slice(1, 3);
console.log(sliced); // ["Banana", "Mango"]
console.log(fruits); // ["Apple", "Banana", "Mango", "Grapes", "Pineapple"] (unchanged ✅)
// Negative indices count from the end
let lastTwo = fruits.slice(-2);
console.log(lastTwo); // ["Grapes", "Pineapple"]
splice() — Modify in Place (Mutating)
Adds, removes, or replaces elements in the original array.
let fruits = ["Apple", "Banana", "Mango", "Grapes"];
let removed = fruits.splice(1, 2); // Remove 2 elements starting at index 1
console.log(removed); // ["Banana", "Mango"]
console.log(fruits); // ["Apple", "Grapes"] (modified ❗)
Comparison Table
| Feature | slice() |
splice() |
|---|---|---|
| Mutates array? | ❌ No | ✅ Yes |
| Returns | New array (extracted part) | Array of removed elements |
| Can add items? | ❌ No | ✅ Yes |
| Can remove? | ❌ No (just extracts) | ✅ Yes |
| Use case | Get a sub-array safely | Modify array in place |
Array Destructuring in JavaScript
Destructuring lets you extract values from an array into individual variables — a clean, modern syntax.
Basic Destructuring
let fruits = ["Apple", "Banana", "Mango"];
let [first, second, third] = fruits;
console.log(first); // "Apple"
console.log(second); // "Banana"
console.log(third); // "Mango"
Skipping Elements
let colors = ["Red", "Green", "Blue", "Yellow"];
let [, , thirdColor] = colors;
console.log(thirdColor); // "Blue"
Default Values
let [a, b, c = "Default"] = [1, 2];
console.log(c); // "Default" (since the third element doesn't exist)
Swapping Variables
One of the coolest destructuring tricks!
let x = 10;
let y = 20;
[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10
Rest Pattern with Destructuring
Use ...rest to collect the remaining elements.
let [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]
💡 Destructuring is used everywhere in modern JavaScript — React hooks, API responses, function arguments. Master it early!
The Spread Operator with Arrays (...)
The spread operator lets you expand, copy, and merge arrays easily.
Copying 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]
Merging Arrays
let fruits = ["Apple", "Banana"];
let veggies = ["Carrot", "Spinach"];
let all = [...fruits, ...veggies];
console.log(all); // ["Apple", "Banana", "Carrot", "Spinach"]
Adding Elements While Spreading
let numbers = [2, 3, 4];
let expanded = [1, ...numbers, 5];
console.log(expanded); // [1, 2, 3, 4, 5]
Passing Array Elements as Function Arguments
let scores = [85, 92, 78, 95, 88];
console.log(Math.max(...scores)); // 95
console.log(Math.min(...scores)); // 78
⚠️ The spread operator creates a shallow copy — nested arrays or objects are still referenced, not cloned.
let matrix = [[1, 2], [3, 4]];
let clone = [...matrix];
clone[0].push(99);
console.log(matrix[0]); // [1, 2, 99] 😱 — nested array was NOT deep-copied!
Other Useful Array Methods
concat() — Merge Arrays
let a = [1, 2];
let b = [3, 4];
let c = a.concat(b);
console.log(c); // [1, 2, 3, 4]
flat() — Flatten Nested Arrays
let nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] — one level
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] — two levels
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6] — all levels
join() — Convert Array to String
let words = ["JavaScript", "is", "awesome"];
console.log(words.join(" ")); // "JavaScript is awesome"
console.log(words.join("-")); // "JavaScript-is-awesome"
console.log(words.join("")); // "JavaScriptisawesome"
Array.isArray() — Check if Something Is an Array
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello")); // false
console.log(Array.isArray({ a: 1 })); // false
💡 Always use
Array.isArray()instead oftypeof, becausetypeof []returns"object".
Common Beginner Mistakes to Avoid
❌ Mistake 1: Forgetting That Array Indices Start at 0
let fruits = ["Apple", "Banana", "Mango"];
// Bad
console.log(fruits[3]); // undefined — there's no index 3!
// Good
console.log(fruits[2]); // "Mango" ✅ (last element)
console.log(fruits[fruits.length - 1]); // "Mango" ✅ (dynamic)
❌ Mistake 2: Using == to Compare Arrays
// Bad — arrays are compared by reference, not by value
console.log([1, 2, 3] == [1, 2, 3]); // false 😱
console.log([1, 2, 3] === [1, 2, 3]); // false 😱
// Good — compare by converting to string or use a loop
console.log(JSON.stringify([1, 2, 3]) === JSON.stringify([1, 2, 3])); // true ✅
❌ Mistake 3: Sorting Numbers Without a Compare Function
// Bad
[10, 5, 40, 25].sort(); // [10, 25, 40, 5] ❌
// Good
[10, 5, 40, 25].sort((a, b) => a - b); // [5, 10, 25, 40] ✅
❌ Mistake 4: Confusing map() with forEach()
// Bad — forEach doesn't return anything
let doubled = [1, 2, 3].forEach(n => n * 2);
console.log(doubled); // undefined ❌
// Good — map returns a new array
let doubled2 = [1, 2, 3].map(n => n * 2);
console.log(doubled2); // [2, 4, 6] ✅
❌ Mistake 5: Using const and Assuming the Array Can't Change
const arr = [1, 2, 3];
arr.push(4); // ✅ Works! const prevents reassignment, not mutation.
arr = [5, 6]; // ❌ TypeError: Assignment to constant variable
Summary: JavaScript Arrays Cheat Sheet
| Operation | Syntax | Example |
|---|---|---|
| Create | [value1, value2] |
let arr = [1, 2, 3] |
| Access | arr[index] |
arr[0] |
| Last element | arr.at(-1) |
arr.at(-1) |
| Add to end | arr.push(val) |
arr.push(4) |
| Add to start | arr.unshift(val) |
arr.unshift(0) |
| Remove from end | arr.pop() |
arr.pop() |
| Remove from start | arr.shift() |
arr.shift() |
| Find element | arr.find(fn) |
arr.find(x => x > 2) |
| Check existence | arr.includes(val) |
arr.includes(3) |
| Transform | arr.map(fn) |
arr.map(x => x * 2) |
| Filter | arr.filter(fn) |
arr.filter(x => x > 2) |
| Reduce | arr.reduce(fn, init) |
arr.reduce((a, b) => a + b, 0) |
| Sort | arr.sort((a, b) => a - b) |
arr.sort((a, b) => a - b) |
| Slice | arr.slice(start, end) |
arr.slice(1, 3) |
| Splice | arr.splice(start, count, ...new) |
arr.splice(1, 1, "new") |
| Spread / Copy | [...arr] |
let copy = [...arr] |
| Destructure | let [a, b] = arr |
let [x, y] = [1, 2] |
| Flatten | arr.flat(depth) |
arr.flat(Infinity) |
| Join | arr.join(sep) |
arr.join(", ") |
Rules of Thumb 🎯
Use array literals
[]to create arrays — simple and cleanUse
constfor arrays you won't reassign (you can still modify elements)Use
map()when you want to transform data,forEach()when you just want side effectsAlways pass a compare function to
sort()when sorting numbersUse the spread operator
[...arr]to copy arrays immutablyUse
includes()to check if an element exists in an arrayLearn
reduce()— it's the most versatile array method and unlocks advanced patterns
What's Next?
Now that you understand JavaScript arrays, you're ready to explore:
Array Methods — Essential functional methods like
map,filter, andreduceObjects — Group related data into structured key-value pairs
DOM Manipulation — Using arrays to work with HTML elements dynamically
Happy coding! 🎉





