Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: what is "- 0" doing?

Tags:

javascript

This is purely an educational question.

I'm working on a new version of a web app that the company I'm working for had made earlier. when re-writing the math, I came across this:

document.getElementById("estResidual").value-0;

Thinking there was no purpose for the "-0", I removed it. But when I tried the calculations, the numbers were waaayyyyyy off. Then I tried re-adding the "-0", and voila! everything worked nicely.

The Question: What did the "-0" do to change the value?

like image 634
DanTheMan Avatar asked Mar 04 '14 20:03

DanTheMan


People also ask

What does 0 do in JS?

0 is an argument passed to void that does nothing, and returns nothing. JavaScript code (as seen above) can also be passed as arguments to the void method. This makes the link element run some code but it maintains the same page.

Is 0 positive in JS?

JavaScript actually has two different representations for zero: positive zero, represented by +0 (or just 0 ), and negative zero, represented by -0 . This is because JavaScript implements the IEEE Standard for Floating-Point Arithmetic (IEEE 754), which has signed zeroes.

What is the difference between Null and 0 in JavaScript?

Conceptually, zero (0) is a number, and NULL is a value that represents "no value". As such, 0 can be added, subtracted, etc., but NULL cannot. The NULL value for a variable can indicate, for example, that a variable has not yet been assigned a value.

DO FOR loops start at 0 JavaScript?

for loops typically start with 0 instead of 1 . You can use the variable i in the code to be executed during the loop. The for loop increments the variable at the end of each loop. Once the condition is false, we exit the for loop.


2 Answers

It's an (ab)use of JavaScript's soft typing behavior. In this case, it will convert a string to a float:

> "13"
"13"
> "13"-0
13
> "1.01"-0
1.01

Unary + will do the same:

> +"13"
13
> +"9.9"
9.9

Note that using + will instead convert the integer 0 into a string and concatenate it:

> "13"+0
"130"

This is all standardized. For explicit details on how these operators should behave, you can always check the ECMAScript Language Specification (e.g. addition, subtraction. unary plus).

like image 97
Claudiu Avatar answered Oct 03 '22 02:10

Claudiu


The JS engine re-casts on the fly to try and make statements work. So JS will cast "23" to an integer 23 when you try to perform math on it, and likewise it will convert integer 23 to string "23" if you do something like:

var a = 23;
console.log(23 + "asdf");
//outputs "23asdf"
like image 38
BLSully Avatar answered Oct 03 '22 02:10

BLSully