denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.97k stars 2.55k forks source link

The tilde(~) operator #70

Closed danilosampaio closed 3 years ago

danilosampaio commented 6 years ago

Tilde operator (~): -(N+1)

where N is the expression to the right of the tilde

Uses:

String to number:

console.log(~~"1"); // 1

true/false to 1/0:

console.log(~~true); // 1 console.log(~~false); // 0

Array/String contains a element/char:

~someStr.indexOf("a") instead of someStr.indexOf("a") >= 0

Source: https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/

Pokechu22 commented 6 years ago

~ returns the bitwise complement. I guess since JS doesn't have real integers this isn't particularly useful, but in other languages that's what ~ is for.

pero5ar commented 6 years ago

Putting almost any arithmetic operator in front of an expression in JS will cause the value to convert to a Number, put a "+" or "-" instead of the tilde and you will get similar results. The only valid thing is the indexOf, but in the same manner you can do 1+someStr.indexOf("a")

denysdovhan commented 3 years ago

This is more like a hack. Looks pretty expectable, so I'd prefer not to add it. Anyway, thanks for reporting!