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).
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
.
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 This is wrong. See Felix Kling's answer.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With