over 1 year ago

Saw this example on MDN:

var str = 'rawr';
var searchFor = 'a';

// this is alternative way of typing if (-1*str.indexOf('a') <= -1)

if (~str.indexOf(searchFor)) {
  // searchFor is in the string

} else {
  // searchFor is not in the string

}

According to the documentation,

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

So if a character exists within a string, indexOf will return the first occurance of that character's index which will either be an 0 or any positive nubmer.

Thus, the tilde operator will turn them into:

~0 === -1 
~1 === -2
~2 === -3
...

Any none zero number is considered a true in JS, so:

1 == true
-1 == true

Thus, if str.indexOf() returns any number other than -1, ~str.indexOf() equals to a negative number, which will be considered True.

In the case of -1 is returns (i.e. the character does not exist in the string):

~(-1) === 0

0 == false

Thus, the else branch is executed.

← How to use Django REST Framework's Token Based Authentication Django create and login user manually →
 
comments powered by Disqus