The +
operator doesn’t change the sign of the value, and the -
operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.
var a = 4;
a = -a; // -4
a = +a; // -4
The abs
function does what you think that the +
opreator does; it makes the value positive regardless of the original sign.
var a =-4;
a = Math.abs(a); // 4
Doing +a
is practically the same as doing a * 1
; it converts the value in a
to a number if needed, but after that it doesn’t change the value.
var a = "5";
a = +a; // 5
The +
operator is used sometimes to convert string to numbers, but you have the parseInt
and parseFloat
functions for doing the conversion in a more specific way.
var a = "5";
a = parseInt(a, 10); //5