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.


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!


Author of scripteverything.com, Ryan has been dabbling in code since the late '90s when he cut his teeth by exploring VBA in Excel when trying to do something more. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP. When he is not behind a screen, Ryan enjoys a good bush walk with the family during the cooler months, and going with them to the beach during the warmer months.

Recent Posts