Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does `~` mean in javascript

I view the code of express, and see this code https://github.com/visionmedia/express/blob/master/lib/application.js#L490

if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);

what the ~ means before envs

like image 788
guilin 桂林 Avatar asked Nov 19 '11 02:11

guilin 桂林


1 Answers

In case you were wondering why it is used in that situation, it is a shorthand for finding out if indexOf method found something.

indexOf returns -1 when it doesn't find something, and >= 0 when it does. So when you do ~-1 you get 0 (a falsy value) and when you do it on anything else you get a truthy value.

So:

if( ~str.indexOf( "something" ) ) {
...
}

Is a shorter way of saying

if( str.indexOf( "something" ) !== -1 ) {
...
}

If you are wondering how is -1 the NOT of 0, then read here

like image 53
Esailija Avatar answered Sep 23 '22 11:09

Esailija