Reputation: 24308
I have been trying to do the following - change a positive to a negative number.
It appears there are a number of ways to do this. There is the standard
x *= -1
or just placing a negative sign in front the variable i.e if x = 5, then -x is equal to -5.
This seems a great shorthand but wanted to know what the difference is, I can't find any documentation regarding this shorthand on MDN.
I assume there are other ways too.
Probably a basic question but it is annoying not understanding this apparent shorthand.
Any ideas ?
Upvotes: 0
Views: 8612
Reputation: 21852
Unary operators in Javascript are basically shorthand functions. You can find the documentation for the Unary (-)
here
The -
takes in one argument. The number you pass to it. Under the hood, I'm guessing it multiplies it by -1
and returns the product. The function could be written along the lines of:
function -(arg) {
return arg * -1;
}
This is conjecture though. Will need to go through V8's codebase to know for sure.
Update:
So from further research I figure that it's instead of multiplication by -1
, it could be a simple sign change. I referred to V8's implementation but that proved to be a dead end because I suck at C++, but upon checking ECMA's specs and the IEEE 754 specs defined here in Steve Hollasch's wonderful blog, I am leaning towards a inversion of the sign bit. All Javascript numbers are 64 Bit IEEE 754 FLoating Points, they can be represented like so:
SEEEEEEE EEEEMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM
Where S
is the sign bit. So it looks like the Unary -
just flips the sign bit.
Upvotes: 6