Skip to content
Advertisement

trouble with truthy/falsey

A quick intro, I am a total noob learning JS and feel that it’s going well, however I am doing a simple exercise right now and I’m hung up on something.

I have learned that: a falsey value is a value that is considered false when encountered in a boolean context ex: false, 0, -0, 0n, “”, null, undefined, NaN (Not a number) truthy is everything other than falsey (such as a String, boolean true, any number not 0 etc.)

so in my example below, if anyone could help me understand why value => value == true, would print out false (as was the case) when I have a string value in my array (“Angela”). Thanks!

let values = [11, NaN, [], "Angela"]

function checkForFalsey() {
  if (values.some(value => value == true)) {
    console.log("At least one item is falsey")
  }
}
checkForFalsey()

Advertisement

Answer

Edit:

The question was a bit confusing because of the snippet, I understood that you were trying to look for falsy values.

The reason why:

value => value == true

would print out false it’s because none of the elements of the array is equal to true.

You are correct about what a falsy value is, but that doesn’t mean that a truthy value would be == to true.

Here you can read more about it:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

One way of checking for truthy values would be:

(values.some(value => value != false)) 

or

(values.some(value => !!value === true)) 

Old answer:

Because the method you use tests that at least one element in the array matches the condition.

You can read more here

If you want to check that all elements of the array matches the condition, then you can use .every()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

let values = [11, NaN, [], ""]

function checkForFalsey() {
  if (values.every(value => value == false)) {
    console.log("All values are falsey");
  } else {
    console.log("NOT all values are falsey");
  }
}
checkForFalsey()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement