# Whyis there a + in the code ..?

Whyis there a + in the code ..?
0

#1

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

#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

#3

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.

#4

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

#5

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

#6

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

#7

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)

#8

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