DEV Community

loading...
Cover image for Pass the Test with Array.prototype.every()

Pass the Test with Array.prototype.every()

toddster79 profile image Todd Carlson ・1 min read

I learned so much this week during my ongoing quest to become a JavaScript ninja. While attempting to solve an algorithm problem I came across the .every() method, which I found to be especially useful. What does the .every() method do? I'm so glad you asked. The .every() method allows you to check and see if every element in an array passes a test. If all the elements pass the test it returns true, and false if they don't.

For example, the following code checks to see if all of the elements in the array are strings.

let arr = ["1", "2", "3"];

const checkString = (arr) => {
    return arr.every((item) => {
       if(typeof(item) === 'string') {
          return true;
    }
  });
  return false
}
console.log(checkString(arr))
// logs true to the console
Enter fullscreen mode Exit fullscreen mode

Since all of the elements inside of our array are strings, the function returns true.

If we wanted to check and see if the array contained at least one string we could use the .some() method.

let arr = ["1", 2, 3];

const checkString = (arr) => {
    return arr.some((item) => {
       if(typeof(item) === 'string') {
          return true;
    }
  });
  return false
}
console.log(checkString(arr))
// logs true to the console
Enter fullscreen mode Exit fullscreen mode

And there you have it, two useful array methods for the price of one blog post. I hope you found this useful, and, as always, happy coding!

Discussion (0)

pic
Editor guide