0

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.

JC Hulce
  • 1,551
  • 2
  • 13
  • 23
  • if options.something is null or undefined, set it true. if true, set it false. it's a toggle. it could written simpler as options.something=options.something!==true; – dandavis Jan 31 '14 at 05:03
  • 1
    @dandavis actually no, thats very different. Maybe `(x!==false)` – ajax333221 Jan 31 '14 at 05:15
  • doh! that code really should be spelled out with an IF statement for better readability. – dandavis Jan 31 '14 at 05:22

2 Answers2

3

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.).

Daniel Larsen
  • 198
  • 1
  • 11
1

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.

pravprab
  • 2,301
  • 3
  • 26
  • 43
OldTimer
  • 124
  • 3
  • 1
    Safari's console has undefined === false evaluating as false. – Daniel Larsen Jan 31 '14 at 05:19
  • 1
    You can read in the specification that `undefined === false` is `false`: http://es5.github.io/#x11.9.6. `TypeOf(undefined)` is "undefined" and `TypeOf(false)` is "boolean", so they are not equal and the result is `false`. – Felix Kling Jan 31 '14 at 05:37