-1 evaluates to true?

http://postimg.org/image/58mdp8qsv/


note that -1 == true also evaluates to false. But the if-statements accepts it as true. Why?
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.
~ is a bitwise operator, as you can see here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators


It never occured to me to use it for indexOf, but if it works, that's nice. I usually use a bitwise OR as a faster alternative to Math.floor:


1.324324|0 // 1


Well, it's not exactly floor, as it will just cut of everything after the dot, but if you're only dealing with positive number it does the job and has the nice side effect of converting non-numbers into 0:

Code:
[1, 2, 3]|0		// 0
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.

Original thread: https://forums.rpgmakerweb.com/threads/1-evaluates-to-true.56214/