DEV Community

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

Posted on

3

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!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay