The tilde is an operator that does something that you’d normally think wouldn’t have any purpose. It is a unary operator that takes the expression to its right performs this small algorithm on it (where N is the expression to the right of the tilde): -(N+1). See below for some samples.
So, unless you actually have an application that needs to run this algorithm on numbers – which I doubt very many people do – how are we going to use this squiggly little character to our advantage?
The tilde character needs a numeric value for N, so if you place it in front of a string expression, it will convert that string to a number for the calculation. That still leaves us with a not-so-helpful number because it doesn’t match the number that was in the string. If you’re any good at mathematics, though, you’ll realize that if you run this algorithm twice, you’ll get the same number that you started with. With a string, it’ll convert it to a number, then change it, then change it back to the number.
As shown in the above code example, you can also convert
false into 1 and 0 respectively. I don’t see quite as many uses for this, but I wouldn’t doubt that there were some. Also, I realize that there are plenty of ways to convert strings into numbers and I’m not claiming this is the best way. I’m just saying that this is a viable option.
If you look back at the first code sample, you’ll see that using ~ on -1 converts it to 0. The number 0 is a falsey value, meaning that it will evaluate to
false when converted to a Boolean. That might not seem like a big insight at first, but remember functions like
indexOf will return -1 when the query is not found. This means that instead of writing something similar to this:
You can now have fewer characters in your code so you can write it like this:
I think this might be a more common use case, and probably the only way I’ll actually use tilde unless I run into a situation where other string conversions are hard to read within the context they’re being used (such as here:
num = 1 + +"2").
ADDED 3/6/2012: One thing you need to consider before using the tilde as a means to convert strings to numbers (as pointed out in the comments by Beej Jorgensen) is that it will convert into an integer, not a decimal number. “3.14” and 3.14 will both end up as just 3 (with double tildes). Also somewhat important to note: ~ is a Binary NOT operator, which means that it doesn’t actually run the algorithm stated above. The algorithm above is just one way for you to be able to understand what the outcome will be when this operator is applied to it (Thanks Danny Ayers and Anonymous for pointing this out).