Question

I've come across this javascript code in the wild and am having trouble understanding exactly what it does and how it works:

// Ensure its bool.
options.something = (!(options.something === false));

From what I can tell, options.something is just being set to the opposite of false. Is there any functional difference between the above and just doing the following instead?

options.something = true;

JSHint and JSLint appropriately give a "confusing use of '!'" warning on the original code.

Was it helpful?

Solution 2

It's not actually a toggle, it's a check that the value is a boolean.

Read it from the inside out.

Inner parenthesis asks if something is false. If it is the value of the expression is true (false does equal false). Take the negative of that (! true) which returns the boolean value false.

If something is true, the inner expression is false, true != false. Take the negative of that (! false) and the result is true.

OK, so what if something is undefined? Undefined will evaluate as false and since false === false the expression is true. Negating that (! true) returns false.

So anything that is true is returned as true and undefined or false values always return false.

OTHER TIPS

Interesting piece of code. The only way options.something will be assigned false is if it is itself false.

Let's break it down:

(!(options.something === false)) => (!(false === false)) => (!true) => false

So, at then end of the day the code ensures that options.something is either true or false, and the only way it can be false is if it actually is the value false (not undefined, null, 0, etc.).

On the other hand, it will be the value true if it begins as anything else (such as undefined, null, 0, etc.).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top