JavaScript every() method

JavaScript every() method:

Using the Javascript every() method

Let’s start by creating an array of items.

const items = [
  { name: 'T-shirt plain', price: 9 },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 }
];

Let’s say we want to check if all the items have a name.

const haveNames = items.every(item => {
  return item.name;
});

// Returns true

If we now remove the name on our item, it will return false.

Let’s take a more accurate example.
We have a list of users, with temperatures, we want to see if everyone is under 37.8, else someone potentially has a risk of Covid-19.

const users = [
  { name: 'Bob', temperature: 36.3 },
  { name: 'Sarah', temperature: 37.9 },
  { name: 'Billy', temperature: 36.9 },
];

const temperature = users.every(user => {
  return user.temperature < 37.8;
});

// Returns false

Whoops! Sarah has a high temperature, so now we get a false back, this means we need to do something.

I hope this shows how one line can beat an array to loop over people.

The syntax for every is as follows:

const new = original.every(function(value));

Inside our function, we can check on certain properties the value has.

from Tumblr https://generouspiratequeen.tumblr.com/post/635845739234377728

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s