Whyis there a + in the code ..?

Whyis there a + in the code ..?
0.0 0


Can someone tell me why do we have a + here… :thinking:
c= +(a- b).toFixed(2);


The plus before a number tells JS to convert it to a number - it’s a shortcut. Without it, it would evaluate to a string.

let a = (10-5).toFixed(2);
console.log(typeof a)
// string

let b = +(10-5).toFixed(2);
console.log(typeof b)
// number


In JS (and other languages) you can use + and - as unary operator to return the number representation.

Since toFixed return a string, the + there converts it back to a number.


So, can it be said it basically works as a parseInt() function…???


I think the + is not specific to integers.

let a = +"3.14159"
console.log(typeof a, a)
// number 3.14159

let b = parseInt("3.14159")
console.log(typeof b, b)
// number 3


Ooohhhh…now I get it slightly…thanks for the help…will try to dig deeper on my own now :slight_smile:


Not really.
parseInt accept radix, this means that you can be explicit on how your interpreter should try to “read” and convert the number:

parseInt('546', 2);  // will produce NaN since digits is not a valid for binary
+'546' // 546

In practice the only real difference I ever encountered was that parseInt will treat empty string as NaN, while unary will treat it as boolean:

parseInt('') //NaN
+'' // 0

(yay for javascript)


Even I was of this opinion that unary might only work with base10 values and not for other bases.