0

What does the following mean in javascript and How does it evaluate to a result true.

!!"false"

Would there by any need to use such an expression.

ckv
  • 10,539
  • 20
  • 100
  • 144
  • 1
    Generally for having a boolean value. A string is a truthy value in JavaScript, `negation -> true to false`, again `false to true`. – Ram Jan 26 '14 at 11:57

5 Answers5

1

Every non-empty string is considered true. So when you double negate something that's true, you get true again.

Code like that can be used to get the boolean value from a non-boolean variable, for example.

Shomz
  • 37,421
  • 4
  • 57
  • 85
1

That means not not a truely value string, so you'll end up with true (boolean).

CD..
  • 72,281
  • 25
  • 154
  • 163
1

Ah, this one is tricky if you assume that "false" evaluates to boolean false. Know that, unless it's an empty string, "", that a string will always evaluate to true. So, you are basically saying, not not true. Double-negative cancels out, thus, true.

STDQ
  • 32
  • 8
1

You should recall which things in Java are truthy and falsy–which items convert to true and false in logical contexts:

Falsy

  1. false
  2. null
  3. undefined
  4. 0
  5. NaN
  6. ''

Truthy

  1. true
  2. non-zero numbers (other than NaN).
  3. non-empty strings
  4. objects, including wrapped versions of primitives.
  5. arrays

Note that new Boolean(false) is truthy. Don't wrap primitives.

Now the ! operator takes false to true and back. For any other value, it takes the logical interpretation converting to boolean, and then flips it. So, !"false" first interprets "false" as true since nonempty strings are truthy. Then, it computes !true, and gets false.

Using a second ! operator will then convert the false to true. Given a truthy argument x, !!x will be true. Given a falsy argument y, !!y will be false.

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
0

It is done to evaluate a non-boolean value as if was a boolean, any value will be evaluated as true except: undefined, null, 0, false or empty string ("").

gpopoteur
  • 1,509
  • 10
  • 18