What Does The “~” Unary Operator Do With indexOf Function?

If you find yourself using the .indexOf() function on many variables to test whether or not a string existings in another string, then this little handy tip can help write a comparative statement quicker.

What does the ~ (tilde) actually do to a variable?

Let’s have a quick look:

var n = -1;
console.log( ~n ); // => 0
console.log( ~~n ); // => -1
console.log( ~~~n ); // => 0

Can you see a pattern?

The impact of placing the tilde in front of a number is that it applies the following formula:

console.log( ~n === -(n + 1) ); // => true

Therefore, one great way of using this is with .indexOf() function.

Why?

Let’s have a look at how I would normally write an indexOf() if statement:

var e = “some text”;
e.indexOf( “x” ) > -1 ? true : false; // => true
e.indexOf( “?” ) > -1 ? true : false; // => false

See, what’s a little annoying about the .indexOf() function is that if the search string (needle) is found at the very beginning of the string being searched (haystack) then the result is 0, as seen here:

var e = "hello world";
console.log( e.indexOf( "hello" ) ); // => 0

With that being the case we can’t just write an if statement with:

if ( e.indexOf( "hello" ) ) ...

As 0 in Javscript is “falsey” and therefore doesn’t satisfy the if condition, even though the comparison was true.

So with the ninja tilde operator, you can write a more simplified if statement like so:

var e = "hello world";
~e.indexOf( “hello” ) ? true : false; // => true

As the tilde turns the initial 0 value now into -1 making it truthy!

Nice and neat!