Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the conditional "if(x)" different than "if(x == true)"?

I'm wondering what the core difference is between the conditional syntax below?

if (something) {
    // do something
}

vs.

if (something == true) {
    // do something
}

Are there any differences?

Edit: I apologize. I made a typo when the question was asked. I did not mean to put a triple equals sign. I know that triple equals is a strict operator. I was meaning to ask if '==' is the equivalent of if (something).

like image 601
W3Geek Avatar asked Nov 27 '22 07:11

W3Geek


2 Answers

The difference is that in if(something), something is evaluated as boolean. It is basically

if(ToBoolean(something))

where ToBoolean is an internal function that is called to convert the argument to a boolean value. You can simulate ToBoolean with a double negation: !!something.

In the second case, both operands are (eventually) converted to numbers first, so you end up with

if(ToNumber(something) == ToNumber(true))

which can lead to very different results. Again, ToNumber is an internal function. It can be simulated (to some degree) using the unary plus operator: +something == +true. In the actual algorithm, something is first passed ToPrimitive if something is an object.


Example:

Assume that

var something = '0'; // or any other number (not 0) / numeric string != 1

if(something) will be true, since '0' is a non-empty string.

if(something == true) will be false, since ToNumber('0') is 0, ToNumber(true) is 1 and 0 == 1 is false.

like image 176
Felix Kling Avatar answered Dec 09 '22 19:12

Felix Kling


EDIT: Below only holds true for the original question, in which the === operator was used.

The first one will execute the body of the if-statement if something is "truthy" while the second will only execute it if it is equal in type and value to true.

So, what is "truthy"? To understand that, you need to know what is its opposite: falsey. All values in JavaScript will be coerced into a Boolean value if placed in a conditional expression. Here's a list of falsey values:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy, though I've probably missed some obscure corner case that someone will point out in the comments.

Here's my answer to the updated question:

The conditional if (something) and if (something == true) are equivalent, though the second is redundant. something will be type coerced in the same way in either case. This is wrong. See Felix Kling's answer.

like image 42
FishBasketGordo Avatar answered Dec 09 '22 17:12

FishBasketGordo