JavaScript Tilde ~ Shorthands

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

We can use ~ as a shorthand in some everyday scenarios.

We know that ~ converts -1 to 0, so we can use it with indexOf on array.

indexOf

let items = ['foo', 'bar', 'baz'];
let el = 'a';
if (items.indexOf('a') !== -1) {}

or

if (items.indexOf('a') >= 0) {}

can be re-written as

if (~items.indexOf('a')) {}


Got any JavaScript Question?