They both seem to output the same results and turn strings into numbers. Is there a difference I am not aware about? I can’t seem to find any documentation regarding ~~ operator.
var hey = true
hey = +hey //hey = 1
var hey = true
hey = ~~hey //hey = 1
var num = "1231"
num = ~~num //num = 1231
var num = "1231"
num = +num //num = 1231
There is one difference that I found and that’s ~~ will always try to output a number whereas there are cases for + to simply return NaN
num = "omfg"
num = ~~num //num = 0
num = "omfg"
num = +num //num = NaN
num = {}
num = ~~num //num = 0
num = {}
num = +num //num = NaN
Any clarification would be awesome 🙂
Both will implicitly turn the operand into a number, because the operators can only be used on a number.
The difference is that the
~operator is a bitwise operator, so it will also turn the number into a 32 bit integer. (The result will still be of the typeNumberthough, i.e. a double precision floating point number.)Neither is a descriptive way to turn a value into a number, as they both use a side effect of the actual operation. Normally you would use a function like
parseIntorparseFloatto convert a string to a number.