0
  • I am trying to understand a small piece of code
  • I thought !!in javascript does the not operator two times

    var result = !!String("false");
    
  • so I thought for the above code it will return as false

  • but it returns true..and can you tell me why the type is boolean?
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This was closed as a duplicate of http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript/784946#784946 but I reopened it. The question isn't about what `!!` does, but why it returns a different result than he expected with this particular argument. – Barmar Mar 03 '16 at 17:49
  • The really simple explanation, is that the string `"false"` is in fact true – adeneo Mar 03 '16 at 17:50
  • Plus the fact that `!` always converts its argument to a boolean, so `!!` is not the same as `` unless `` is already a boolean. – Barmar Mar 03 '16 at 17:52

2 Answers2

5

That is because,

  1. String("false") will return "false". A string.

  2. !"false" will be evaluated to false. Since a non empty string will be considered as true when it coerces to boolean.

  3. !false will be evaluated to true.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
2
String("false")

Resolves to:

"false"

Which is a string that is non-empty, so

!"false"

Resolves to

false

And finally

!false

Resolves to

true
Halcyon
  • 57,230
  • 10
  • 89
  • 128