- I am trying to understand a small piece of code
I thought
!!
in javascript does the not operator two timesvar 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 isboolean
?
Asked
Active
Viewed 42 times
0

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 ` – Barmar Mar 03 '16 at 17:52` unless ` ` is already a boolean.
2 Answers
5
That is because,
String("false")
will return"false"
. A string.!"false"
will be evaluated tofalse
. Since a non empty string will be considered astrue
when it coerces toboolean
.!false
will be evaluated totrue
.

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