Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you want to convert an object to boolean when used in a boolean context?

Tags:

javascript

I understand that !! converts anything to a boolean value, but why would you want to do this:

if (!!someObject) { ... }

When you can just do:

if (someObject) { ... }

EDIT:

Just to clarify, I'm simply asking why you would write code like in the first example, rather than that in the second example. Are there any practical differences?

like image 382
Derek Chiang Avatar asked Nov 12 '22 00:11

Derek Chiang


1 Answers

There isn't a significant different between them. So, most likely, it's personal preference or to be explicit about the intent.

Though, it's possibly from an uncertainty/misunderstanding of how or when values are treated as a booleans.

But, both if statements and Logical NOT operators use the internal ToBoolean():

If ToBoolean(GetValue(exprRef)) is true, [...]

Let oldValue be ToBoolean(GetValue(expr))

The operators just add 2 more rounds of ToBoolean() with negation on top of the if statement's own use. But, the result is the same.

like image 107
Jonathan Lonowski Avatar answered Nov 15 '22 00:11

Jonathan Lonowski