Pass the Test with Array.prototype.every()

toddster79

Todd Carlson

Posted on October 23, 2020

Pass the Test with Array.prototype.every()

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!

💖 💪 🙅 🚩
toddster79
Todd Carlson

Posted on October 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript arrays : fundamentals & methods
javascript JavaScript arrays : fundamentals & methods

October 11, 2023

Pass the Test with Array.prototype.every()
javascript Pass the Test with Array.prototype.every()

October 23, 2020

Which Array Function When?
javascript Which Array Function When?

August 8, 2017