guilin 桂林
guilin 桂林

Reputation: 17422

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

Upvotes: 9

Views: 1366

Answers (2)

Esailija
Esailija

Reputation: 140230

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

Upvotes: 9

Clive
Clive

Reputation: 36956

It's the Bitwise NOT operator:

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators

Upvotes: 8

Related Questions