2

I have a question about the if statement and boolean evaluation in JavaScript.

I create on jsFiddle example of that click, there's four different functions which evaluates the types in array through the loop.

But let's focus only on function b and c.

function b(p) {
    return (p == true);
}

function c(p) {
    if (p) {
        return true;
    }
    else {
        return false;
    }
}

As you can see in the console the results are different, for example, -1 and 'Hello' are true to the c, while false in b.

Why that's happens?

Thanks for attention!

0

1 Answer 1

-1

-1 != true and Hello != true yet both -1 and Hello are truth-y and evaluate to true when cast to a boolean (which is what the if statement does) which is why

if('Hello') {
  return true;
} else {
 return false;
}

returns true;

Sign up to request clarification or add additional context in comments.

4 Comments

But isn't the == true is loosely type check? I mean 'hello' === true definitely would be false.
I'm not sure what you mean. Just type this in your console (Boolean('Hello') == true) vs ('Hello' == true). Hopefully that will make sense for you.
@Volter9: Yes, it's a loose (coercing) test. But if you read up on how == works, it's plain why "hello" == true is false. For more information, read the answers to the question this duplicates.
@Volter9: To be clear, the type of coercion done by == isn't a simple Boolean() conversion. The algorithm used by == is quite a bit more complex. Adam's comment shows an example. Best is to understand the underlying algorithm if you want to use ==.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.