The JavaScript .every() method

I definitely think one of the great things about programming is that there is always something new to learn. No matter your experience level something can always come along that either is brand new, or better, can make something you know how to do easier. In studying data structures and algorithms I came across the .every() method for JavaScript. It is a method that will test every element in an array to see if it fulfills a certain condition, and it’s a useful tool to know about.

The .every() method returns a boolean, which means it will either return true or false. It’s important to note that every element in the array must return true in order for the .every() method to return true as well. If just one element is false, the entire method will return false.

It’s also important to note that calling the .every() method on an empty array will return true no matter the condition.

For an example of how to use the .every() method:

const array = [0, 10, 14]array.every((val) => val > 5)

The way that this method will work is that each element in the array will be passed in as the value of ‘val’. The method will then check to see if that ‘val’ is greater than 5. The above example will obviously return false.

I came across the .every() method while trying to solve a coding challenge in which the challenge was to figure out if two strings were palindromes, meaning if they would be spelled the same forwards and backwards. Now there are multiple ways to solve this challenge and there are easier ways to solve it than using .every(), but it’s important to know multiple ways to solve a problem, just in case.

Using .every() in the context of this problem, we’d be checking to see is every character in the string is the same as the character mirrored at the other end. The first element is compared to the last element, the second element to the second to the last, and so on. An example of building that into a function is below:

function palindrome(str) {
return str.split('').every((char, i)=>{
return char === str[str.length - i - 1];
});
}

To break down what’s happening:

Call .split() on the string to turn it into an array, .every() only works on arrays.

We set up the arguments of ‘char’ and ‘i’ to stand for each individual character and the index, or position, in the array.

‘char’ is then compared to the length of the array, minus the index, minus 1 because indices in arrays start at 0.

As stated earlier, this might not be the most efficient way to solve this challenge, but it’s just an example of how to use the .every() method. Having multiple solutions to problems is good practice. The .every() can be one of them.