If (arr[i] == true) vs. if (arr[i])

Tell us what’s happening:

I wrote almost the same code as below except for my if statement I said:

if (arr[i] == true) 

This did not pass the tests. From what I have gathered this is because my code is checking if the element is literally a boolean value of true. Whereas this:

if (arr[i])

is checking the condition (expression evaluation?) of true rather than the literal.

Is this correct?

Your code so far

function bouncer(arr) {
let newArray = [];
for (var i = 0; i < arr.length; i++) {
  if (arr[i]) newArray.push(arr[i]);
return newArray;

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36.

Challenge: Falsy Bouncer

Link to the challenge:

1 Like

So yeah, there’s a “shortcut” code thing going on here, and you were spot-on catching that.

if(arr[i] == true) means “if the value of arr[i] is literally the boolean true…”

if(arr[i]) means “if the value at arr[i] is something that is not ‘falsy’…” - which is a whole confusing concept in and of itself.

There are two different ways an evaluation can go: falsy or truthy. Truthy is defined as… anything that doesn’t evaluate as falsy (useless definition, but you’ll see its significance in a minute). Falsy, on the other hand, is anything that can be coerced to a non-true value. So, for example, null, or undefined will both evaluate to false.

So if(arr[i])... is simply saying “if there is a value at arr[i], and that value is not null, or undefined, or something that will be evaluated as ‘false’”.


You just stumbled across two concepts before realizing it:

  • Evaluation of an expressions: The interpreter/runtime will always evaluate parenthesis from the inside out, so for example if(f1(f2(f3(expr))) will evaluate the expression “expr”, then send the value as an argument to f3, the result to f2, then to f1 and the return value to the “if” control form. Expressions are basically sentences of code that yield a value, which is basically everything:
    • Assignment expressions yield the value you assigned
    • Function calls to functions that have no return statement yield undefined
    • Standalone values yield the same value
    • Logical, numerical and composite expressions with operators yield a left-to-right evaluation result. That’s why you can short-circuit evaluation with the && operator.
  • Truthiness and falsiness: JS happens to be a weakly typed language which means you can make implicit conversions and comparisons like for example 5 == "5" (but 5 !== "5") or how the following values coerce to false: false, undefined, null, NaN, "", 0 and these to true: basically anything that is not on the previous list of things haha.
1 Like