JavaScript's Tilde: Its Real Use Is No Mystery

A while back I wrote an article titled “The Great Mystery of the Tilde” where I tried to explain what the ~ (tilde) operator did in JavaScript. When trying to demystify what it was, I ended up perpetuating a lot of misinformation. I’m here to fix that today.

Setting The Facts Straight

Normally, I don’t care too much about going back and updating old content, but my error was quite eggregious. Not only that: that post is the second most view post I had last year, so if I’m going to have that much traffic going to it, then I need to fix it, so I’ve added a paragraph to that post directing visitors to this new post, so that I can prevent future misinformation from spreading.

So What Is It?

The ~ operator in JavaScript is the Bitwise NOT operator. If you don’t work with binary very often, then that probably doesn’t mean anything to you at all. Don’t worry, though, I’ll explain. If you have a number, say 8, it looks like this in binary: 1000. When you use the ~ on that number, it will convert each bit to the opposite value. That means, each 1 will become a 0 and vice versa. So ~8 would equal 7, whose binary representation looks like this: 0111. Or a 13 (1101) would become 2 (0010). The only problem is that JavaScript uses what is called “Two’s Complement” in order to be able to represent positive and negative numbers in binary. So, because of this, in actuality, ~8 equals -9. If you want a better explanation than that, you’ll need to do some research on your own because I don’t feel adequate to explain it.

If you’re wondering what you would use this for (besides as a lame hack as I recommended in my previous article and that I no longer recommend)… so am I. I can find some examples on the internet for using bitwise operators, but I haven’t really seen a helpful example utilizing this particular operator. So, if you find a tilde in some JavaScript code you’re reading, then check out my old article linked above just to make sure they’re not using wrongly. If it doesn’t seem to be used hackily, then I guess you’ll have to let me know so I can see an example where it’s used correctly!

Conclusion

So, now I hope this sets the record straight and that people being directed to the old post by Google will end up seeing this post. God bless and happy coding!

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.