Arrays are one of the most important data structures in JavaScript. They allow you to store multiple values in a single variable, making it easy to manage collections of data such as lists of numbers, strings, objects, or even other arrays.
An array is an ordered collection of items where each item can be accessed by its index, which starts at 0. Arrays are especially useful when you need to work with lists of related values — for example, a list of student names, a series of temperatures, or a shopping cart's contents.
There are two common ways to create arrays in JavaScript:
1. Using Array Literals (Recommended)
let fruits = ['apple', 'banana', 'cherry'];
This is the most concise and preferred way to create an array. The array fruits
contains three string elements.
2. Using the Array Constructor
let numbers = new Array(10, 20, 30);
This creates an array numbers
with the elements 10
, 20
, and 30
.
You can also create an empty array:
let emptyArray = [];
Or use the constructor with a specified length:
let scores = new Array(5); // creates an array with 5 empty slots
⚠️ Be careful:
new Array(5)
creates an array with length 5 but doesn't assign values to any of the elements.
You access elements in an array by referring to their index (starting from 0):
let colors = ['red', 'green', 'blue'];
console.log(colors[0]); // Output: 'red'
console.log(colors[2]); // Output: 'blue'
To modify a specific element:
colors[1] = 'yellow';
console.log(colors); // ['red', 'yellow', 'blue']
If you try to access an index that doesn’t exist in the array, JavaScript will return undefined
:
let pets = ['dog', 'cat'];
console.log(pets[5]); // Output: undefined
Assigning a value to an out-of-range index expands the array and fills missing spots with undefined
:
pets[4] = 'hamster';
console.log(pets); // ['dog', 'cat', undefined, undefined, 'hamster']
Arrays are essential for working with ordered data in JavaScript. You can create them using literals or constructors and access items using numeric indexes. Being aware of how JavaScript handles array lengths and out-of-range indexes will help you write more reliable and efficient code.
push
, pop
, shift
, unshift
, slice
, splice
)JavaScript provides several built-in methods that make working with arrays easier and more powerful. In this section, we’ll explore six essential array methods that help you add, remove, copy, and modify elements.
push()
Purpose: Adds one or more elements to the end of an array.
Syntax:
array.push(element1, element2, ...);
Example:
let fruits = ['apple', 'banana'];
fruits.push('cherry');
console.log(fruits); // ['apple', 'banana', 'cherry']
Use Case: Adding new items to the end of a list.
pop()
Purpose: Removes the last element from an array and returns it.
Syntax:
let removedItem = array.pop();
Example:
let fruits = ['apple', 'banana', 'cherry'];
let lastFruit = fruits.pop();
console.log(lastFruit); // 'cherry'
console.log(fruits); // ['apple', 'banana']
Use Case: Removing the most recent item from the end.
shift()
Purpose: Removes the first element from an array and returns it.
Syntax:
let removedItem = array.shift();
Example:
let colors = ['red', 'green', 'blue'];
let firstColor = colors.shift();
console.log(firstColor); // 'red'
console.log(colors); // ['green', 'blue']
Use Case: Processing a queue (FIFO — first in, first out).
unshift()
Purpose: Adds one or more elements to the beginning of an array.
Syntax:
array.unshift(element1, element2, ...);
Example:
let colors = ['green', 'blue'];
colors.unshift('red');
console.log(colors); // ['red', 'green', 'blue']
Use Case: Prepending items to a list.
slice()
Purpose: Returns a shallow copy of a portion of an array without modifying the original array.
Syntax:
array.slice(startIndex, endIndex);
startIndex
: Index to start (inclusive)endIndex
: Index to stop (exclusive)Example:
let numbers = [10, 20, 30, 40, 50];
let subArray = numbers.slice(1, 4);
console.log(subArray); // [20, 30, 40]
console.log(numbers); // [10, 20, 30, 40, 50] (unchanged)
Use Case: Copying a portion of an array without affecting the original.
splice()
Purpose: Changes an array by adding, removing, or replacing elements in place.
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...);
startIndex
: Index to begin changesdeleteCount
: Number of elements to removeitem1, item2, ...
: Elements to add (optional)Example 1 – Removing Elements:
let items = ['a', 'b', 'c', 'd'];
items.splice(1, 2);
console.log(items); // ['a', 'd']
Example 2 – Adding Elements:
let items = ['a', 'd'];
items.splice(1, 0, 'b', 'c');
console.log(items); // ['a', 'b', 'c', 'd']
Example 3 – Replacing Elements:
let items = ['a', 'b', 'c'];
items.splice(1, 1, 'x');
console.log(items); // ['a', 'x', 'c']
Use Case: Directly modifying part of an array, such as editing a to-do list.
Method | Action | Modifies Original? | Common Use |
---|---|---|---|
push() |
Add to end | ✅ Yes | Stack: Add |
pop() |
Remove from end | ✅ Yes | Stack: Remove |
shift() |
Remove from start | ✅ Yes | Queue: Dequeue |
unshift() |
Add to start | ✅ Yes | Queue: Enqueue |
slice() |
Copy portion (no change) | ❌ No | Cloning subarrays |
splice() |
Add/Remove/Replace in-place | ✅ Yes | Editing arrays |
Understanding these methods gives you powerful tools to manipulate arrays efficiently in a wide variety of practical programming tasks.
Iterating over arrays—going through each item one by one—is a common task in programming. JavaScript offers several types of loops to help you work with array elements effectively. In this section, we’ll look at the most commonly used loop types: for
, while
, and for...of
.
for
LoopPurpose: Gives full control over the iteration process using an index.
Syntax:
for (let i = 0; i < array.length; i++) {
// Use array[i]
}
Example – Summing Numbers:
let numbers = [10, 20, 30];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 60
Common Mistake: Off-by-one errors like using i <= array.length
instead of i < array.length
, which will try to access an out-of-range index.
while
LoopPurpose: Repeats a block of code while a condition is true. Useful when the number of iterations isn’t fixed or depends on dynamic conditions.
Syntax:
let i = 0;
while (i < array.length) {
// Use array[i]
i++;
}
Example – Printing Elements:
let fruits = ['apple', 'banana', 'cherry'];
let i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
// Output:
// apple
// banana
// cherry
Tip: Always make sure your loop has an end condition. Forgetting to increment i
can cause an infinite loop.
for...of
LoopPurpose: A modern, concise way to loop through array values without using indexes. Improves readability and avoids index-related bugs.
Syntax:
for (let element of array) {
// Use element
}
Example – Capitalizing Words:
let animals = ['cat', 'dog', 'fox'];
for (let animal of animals) {
console.log(animal.toUpperCase());
}
// Output:
// CAT
// DOG
// FOX
Use Case: When you just need the values, not the index.
Loop Type | Best When You Need... | Has Index? | Readability |
---|---|---|---|
for |
Full control over start/stop/index | ✅ Yes | Moderate |
while |
Dynamic stopping conditions | ✅ Yes | Low–Moderate |
for...of |
Simple value-based iteration | ❌ No | ✅ High |
Avoid i <= array.length
— it will go one step too far.
Use for...of
when you don’t need the index—it’s cleaner and safer.
Keep loops focused — avoid doing too much inside a loop block.
Use const
inside for...of
if the value doesn't change:
for (const name of names) {
console.log(name);
}
Looping through arrays is essential for tasks like summing values, transforming data, and displaying results. Understanding how and when to use different loop types will help you write cleaner, more efficient JavaScript. Start with for...of
for simplicity, and use classic loops when more control is needed.
map
, filter
, reduce
, forEach
, find
)JavaScript arrays come with powerful higher-order methods that allow you to write cleaner, more expressive code. These methods take callback functions as arguments and help you transform, filter, summarize, and search data efficiently.
Let’s explore each one with practical, real-world examples.
map()
: Transforming DataPurpose: Creates a new array by applying a function to each element of the original array.
Syntax:
array.map((element, index, array) => {
// return transformed value
});
Example – Convert prices from USD to EUR:
let usdPrices = [10, 20, 30];
let eurPrices = usdPrices.map(price => price * 0.9);
console.log(eurPrices); // [9, 18, 27]
Use Case: Applying the same transformation to each item (e.g., converting units, formatting text).
filter()
: Selecting SubsetsPurpose: Creates a new array with only the elements that pass a test (i.e., return true
from the callback).
Syntax:
array.filter((element, index, array) => {
return condition;
});
Example – Get users over age 18:
let users = [
{ name: 'Alice', age: 17 },
{ name: 'Bob', age: 22 },
{ name: 'Carol', age: 19 }
];
let adults = users.filter(user => user.age >= 18);
console.log(adults);
// [
// { name: 'Bob', age: 22 },
// { name: 'Carol', age: 19 }
// ]
Use Case: Keeping only the items that match a condition (e.g., active users, valid inputs).
reduce()
: Aggregating ResultsPurpose: Reduces an array to a single value by applying a function cumulatively.
Syntax:
array.reduce((accumulator, current, index, array) => {
return updatedAccumulator;
}, initialValue);
Example – Calculate total cart price:
let cart = [29.99, 9.99, 4.99];
let total = cart.reduce((sum, price) => sum + price, 0);
console.log(total); // 44.97
Use Case: Summing values, counting occurrences, or building a new object from array data.
forEach()
: Executing Side EffectsPurpose: Executes a function on each element in the array. Unlike map
, it does not return a new array.
Syntax:
array.forEach((element, index, array) => {
// side effect (e.g., logging)
});
Example – Log each order ID:
let orders = [101, 102, 103];
orders.forEach(id => console.log(`Order #${id}`));
// Output:
// Order #101
// Order #102
// Order #103
Use Case: Performing operations like logging, DOM updates, or API calls.
⚠️ Tip: Don’t use
forEach()
when you need to transform data—usemap()
instead.
find()
: Locating an ElementPurpose: Returns the first element that satisfies a condition. If none is found, returns undefined
.
Syntax:
array.find((element, index, array) => {
return condition;
});
Example – Find the first overdue task:
let tasks = [
{ title: 'Pay bills', done: true },
{ title: 'Clean room', done: false },
{ title: 'Buy groceries', done: false }
];
let firstUndone = tasks.find(task => !task.done);
console.log(firstUndone);
// { title: 'Clean room', done: false }
Use Case: Searching for a specific match (e.g., user by ID, product by name).
Method | Purpose | Returns | Mutates? | Best For |
---|---|---|---|---|
map() |
Transform elements | New array | ❌ | Format/change array values |
filter() |
Select elements | New array | ❌ | Get a subset of items |
reduce() |
Aggregate to single value | Single value | ❌ | Sum, count, or combine items |
forEach() |
Perform side effects | undefined |
❌ | Logging, DOM manipulation |
find() |
Find first match | Single item/undefined |
❌ | Locate an object or value |
Mastering these advanced methods lets you write elegant, efficient code for complex data tasks. With practice, you’ll find they often replace traditional loops entirely in modern JavaScript development.