JavaScript Arrays And How To Avoid Loops
Open this example in our interactive code editor to experiment with it.
Try the EditorArrays exist in every programming language. It’s a data structure best suited for storing multiple values. And, for doing various operations on these values, often called as a collection.
In JavaScript, an array is also an object which contains a list of items.
Let’s look at an example of a JavaScript array:
// Empty array
const empty = [];
// Array of numbers
const numbers = [1, 2, 3];
// Array of strings
const fruits = ["apple", "banana", "cherry"];
// Array of mixed types
const mixed = [1, "hello", true, null, { name: "Adrian" }];
// Accessing array elements
console.log(numbers[0]); // 1
console.log(fruits[1]); // "banana"
// Array length
console.log(numbers.length); // 3
There are many ways to work with arrays. They come with built-in methods that allow you to manipulate the data. Most often, developers reach for for or while loops to iterate over arrays. But there are much better ways to do it.
Useful array methods
Let’s explore 7 useful array methods that help you avoid writing loops.
.map()
Assignment: Multiply each number in the array by 2.
Loop solution:
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
console.log(doubled); // [2, 4, 6, 8, 10]
✅ Using .map():
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
The .map() method creates a new array by calling a function on each element of the original array. It’s perfect when you want to transform every item in an array.
.filter()
Assignment: Get all numbers greater than 3.
Loop solution:
const numbers = [1, 2, 3, 4, 5];
const greaterThanThree = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 3) {
greaterThanThree.push(numbers[i]);
}
}
console.log(greaterThanThree); // [4, 5]
✅ Using .filter():
const numbers = [1, 2, 3, 4, 5];
const greaterThanThree = numbers.filter((number) => number > 3);
console.log(greaterThanThree); // [4, 5]
The .filter() method creates a new array with all elements that pass the test implemented by the provided function. It’s useful when you want to narrow down an array based on a condition.
.reduce()
Assignment: Sum all numbers in the array.
Loop solution:
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 15
✅ Using .reduce():
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, number) => accumulator + number, 0);
console.log(sum); // 15
The .reduce() method executes a reducer function on each element of the array, resulting in a single output value. It’s the most versatile array method - you can implement any other array method with it.
.indexOf()
Assignment: Find the index of “cherry” in the fruits array.
Loop solution:
const fruits = ["apple", "banana", "cherry", "date"];
let cherryIndex = -1;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i] === "cherry") {
cherryIndex = i;
break;
}
}
console.log(cherryIndex); // 2
✅ Using .indexOf():
const fruits = ["apple", "banana", "cherry", "date"];
const cherryIndex = fruits.indexOf("cherry");
console.log(cherryIndex); // 2
The .indexOf() method returns the first index at which a given element can be found in the array, or -1 if it’s not present.
.every()
Assignment: Check if all numbers are positive.
Loop solution:
const numbers = [1, 2, 3, 4, 5];
let allPositive = true;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
allPositive = false;
break;
}
}
console.log(allPositive); // true
✅ Using .every():
const numbers = [1, 2, 3, 4, 5];
const allPositive = numbers.every((number) => number > 0);
console.log(allPositive); // true
The .every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
.some()
Assignment: Check if any number is greater than 4.
Loop solution:
const numbers = [1, 2, 3, 4, 5];
let hasGreaterThanFour = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 4) {
hasGreaterThanFour = true;
break;
}
}
console.log(hasGreaterThanFour); // true
✅ Using .some():
const numbers = [1, 2, 3, 4, 5];
const hasGreaterThanFour = numbers.some((number) => number > 4);
console.log(hasGreaterThanFour); // true
The .some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
.includes()
Assignment: Check if the array includes the value “banana”.
Loop solution:
const fruits = ["apple", "banana", "cherry"];
let hasBanana = false;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i] === "banana") {
hasBanana = true;
break;
}
}
console.log(hasBanana); // true
✅ Using .includes():
const fruits = ["apple", "banana", "cherry"];
const hasBanana = fruits.includes("banana");
console.log(hasBanana); // true
The .includes() method determines whether an array includes a certain value among its entries, returning true or false.
Bonus
You can also chain these methods together for more powerful operations:
const people = [
{ name: "Adrian", age: 28 },
{ name: "John", age: 17 },
{ name: "Jane", age: 32 },
{ name: "Bob", age: 15 },
];
// Get names of all adults, sorted alphabetically
const adultNames = people
.filter((person) => person.age >= 18)
.map((person) => person.name)
.sort();
console.log(adultNames); // ["Adrian", "Jane"]
Chaining methods makes your code more readable and expressive. Each method returns a new array, so you can keep adding more transformations.
Summary
Arrays are a fundamental data structure in JavaScript. While loops are a common way to iterate over arrays, built-in array methods like .map(), .filter(), .reduce(), .indexOf(), .every(), .some(), and .includes() provide a more declarative and concise way to work with collections.
The key benefits of using these methods over loops are:
- Readability - The intent of the code is clearer
- Immutability - Most methods return new arrays instead of modifying the original
- Chainability - Methods can be chained together for complex transformations
- Less error-prone - No off-by-one errors or forgotten break statements
Next time you reach for a for loop, consider whether one of these array methods might be a better fit.
Ready to level up your coding skills?
Build real projects and grow your portfolio with BigDevSoon.
Start 7-Day Free Trial
Creator of BigDevSoon
Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.
Related Posts
Boolean And Friends in JavaScript
Conditions, typecasting, logical operators, comparison operators, ternary operator, optional chaining, null-coalescing operator - they are all part of JavaScript.
Var, Let, Const in JavaScript
Everyone needs variables in JavaScript. Let's learn the best ways to use them.