DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Andrey
Andrey

Posted on

Interesting way to inverse number in JavaScript

It’s binary inversion. ~n = -(n + 1)

Image description

Oldest comments (1)

Collapse
 
casraf profile image
Chen Asraf

There is a nice trick of turning indexOf results into booleans involving this method.
Take the following code:

const txt = 'contains';
const contains = txt.indexOf('contains') > -1;
Enter fullscreen mode Exit fullscreen mode

Can be turned into:

const txt = 'contains';
const contains = ~txt.indexOf('contains');
Enter fullscreen mode Exit fullscreen mode

Since -1 will turn to 0 it will be resolved as false when doing a naive bool comparison, and other numbers (0 and up) will change into numbers which will be considered true.

I personally prefer to have things more readable, and also there are standard methods that aim to remove the need for these types of checked (includes for example), so I don't use it at all. But it's a nice thing to think about :)

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post