Because the integer -1 is not equal to the Boolean true.
But if you're asking "if this number exists", then the if statement would only evaluate false if the number was 0.
Because it's a truthy value. Everything, that's not
- 0
- ''
- null
- undefined
- NaN
- false
will evaluate to true inside an if.
/edit: You can test it, by typing this into the console:
!!-1
The first "!" will negate the -1, converting it into a boolean. The second negates it again, so you can effectively get the boolean representation of any object.
I see... the if-statement treats the -1 differently because it handles types different compared to both the === and == operators.
That's why the tilde-operator is such a nice way of handling someArray.indexOf() within an if-statement. Because it converts the -1 to 0, which as a 'truthy' evaluates to false.
Yes it works very nicely 😀
This is how I code some of my indexOf checks:
if(~[1,2,3].indexOf(3)){console.log(true);}
JSHint gives me a warning but it works.