mjshi

Jack of Most Trades
Veteran
Joined
Feb 16, 2013
Messages
987
Reaction score
826
First Language
English
Primarily Uses
N/A
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.
 

Iavra

Veteran
Veteran
Joined
Apr 9, 2015
Messages
1,797
Reaction score
865
First Language
German
Primarily Uses
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.
 
Last edited by a moderator:

SilverDash

Veteran
Veteran
Joined
Oct 11, 2015
Messages
427
Reaction score
174
First Language
Dutch
Primarily Uses
RMMV
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.
 
Last edited by a moderator:

Iavra

Veteran
Veteran
Joined
Apr 9, 2015
Messages
1,797
Reaction score
865
First Language
German
Primarily Uses
~ 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
 

SilverDash

Veteran
Veteran
Joined
Oct 11, 2015
Messages
427
Reaction score
174
First Language
Dutch
Primarily Uses
RMMV
Yes it works very nicely :D


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.
 
Last edited by a moderator:

Latest Threads

Latest Posts

Latest Profile Posts

Valentines Entry, first contest I'm in and it is so much fun to just participate!
Anatomy is really hard. I'm not an artist.
just destroyed hours of work again. i don't know why I bother.
World Map for the inside of my main character's head. Every spot is an area that either occupies his thoughts or staples of everyone's "headspace"

Forum statistics

Threads
109,000
Messages
1,041,143
Members
141,466
Latest member
williamjjj
Top