aug
aug

Reputation: 11714

The difference between ~~ and + in javascript?

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 :)

Upvotes: 2

Views: 224

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382160

Yes, there is a difference. Try ~~"3.4".

Just like +, ~~ converts, whenever possible, what follows to a number but unlike + it makes it an integer.

Bitwise operators always reduce numbers to 32 bits integers in javascript. And this one "Inverts the bits of its operand" (which means the integer part won't be changed by a double execution).

From the MDN :

The operands of all bitwise operators are converted to signed 32-bit integers in big-endian order and in two's complement format.

Upvotes: 2

Guffa
Guffa

Reputation: 700372

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 type Number though, 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 parseInt or parseFloat to convert a string to a number.

Upvotes: 5

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

+num will convert a string to a number, but doesn't convert decimal numbers to integers. For strings that contain characters as well as numbers, NaN is returned.

~~num will convert the string to a number and cuts off any decimals (without rounding). For strings that contain characters as well as numbers, 0 is returned.

Upvotes: 2

Related Questions