Skip to content
On this page

Array

In addition to methods like map(), reduce(), filter(), and sort(), the Array object provides many other useful higher-order functions.

Every

The every() method checks if all elements in the array satisfy a given test condition. For example, to check if all strings in an array are non-empty:

javascript
let arr = ['Apple', 'pear', 'orange'];
console.log(arr.every(function (s) {
    return s.length > 0;
})); // true, because all elements satisfy s.length > 0

console.log(arr.every(function (s) {
    return s.toLowerCase() === s;
})); // false, because not all elements are lowercase

Find

The find() method is used to locate the first element that meets the specified condition. If found, it returns that element; otherwise, it returns undefined:

javascript
let arr = ['Apple', 'pear', 'orange'];
console.log(arr.find(function (s) {
    return s.toLowerCase() === s;
})); // 'pear', because 'pear' is entirely lowercase

console.log(arr.find(function (s) {
    return s.toUpperCase() === s;
})); // undefined, because there is no element that is entirely uppercase

FindIndex

Similar to find(), the findIndex() method locates the first element that meets the condition but returns the index of that element. If none is found, it returns -1:

javascript
let arr = ['Apple', 'pear', 'orange'];
console.log(arr.findIndex(function (s) {
    return s.toLowerCase() === s;
})); // 1, because the index of 'pear' is 1

console.log(arr.findIndex(function (s) {
    return s.toUpperCase() === s;
})); // -1, because there is no all-uppercase element

ForEach

The forEach() method is similar to map(), applying the given function to each element but not returning a new array. It is commonly used for traversing arrays, so the function passed does not need to return a value:

javascript
let arr = ['Apple', 'pear', 'orange'];
arr.forEach(x => console.log(x)); // Prints each element in order
Array has loaded