2 minute read

Today I learned some cool “tricks” (uhmm… fundamentals…) in JavaScript.

In this blog post I’ll show you how to:

  • check if at least one value is false in an array
  • check if all values are false in an array
  • find an element in an array

Trick 1: How to check if at least one value is false in an array

To check whether at least one value in the array is false you can use some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.

const array = [false, true, true];

// check whether any element is false
array.some(x => x == false); // true

Try it out by clicking here.

Trick 2: How to check if all values are false in an array

To check if all values are false in an array you can use every():

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

const array1 = [false, false, false];
array1.every(x => x == false); // true

const array2 = [false, false, true];
array2.every(x => x == false); // false

Try it out by clicking here.

Trick 3: How to find an element in an array

To find an element in an array based on some condition you can use find():

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

const array1 = ["2021-04-25", "2021-04-26"];
const today = "2021-04-26";

// Find item that returns true
console.log(array1.find(item => item == today)); // "2021-04-26"

Note 1: Only matches the first match.

Note 2: If you need to find the index use findIndex().

Bonus: Get today’s string in YYYY-MM-DD format

Here’s a nice bonus. I also had to get today’s date in the format of YYYY-MM-DD (ex. 2021-04-26) and this is how you do that:

const today = new Date()
const todayString = today.toISOString().slice(0,10);

Conclusion

That’s it! That’s all I wanted to share today. By writing these down I hope I remember them better for next time. I call these things tricks but they are more like fundamentals, but hey, we all have to start somewhere!

Subscribe

Comments