making a variable value positive

I have a variable that will sometimes be negative and sometimes positive.

Before I use it I need to make it positive. How can I accomplish this?


Solution 1:

Use the Math.abs method.

There is a comment below about using negation (thanks Kelly for making me think about that), and it is slightly faster vs the Math.abs over a large amount of conversions if you make a local reference to the Math.abs function (without the local reference Math.abs is much slower).

Look at the answer to this question for more detail. Over small numbers the difference is negligible, and I think Math.abs is a much cleaner way of "self documenting" the code.

Solution 2:

Between these two choices (thanks to @Kooilnc for the example):

Number.prototype.abs = function(){
    return Math.abs(this);
};

and

var negative = -23, 
    positive = -negative>0 ? -negative : negative;

go with the second (negation). It doesn't require a function call and the CPU can do it in very few instructions. Fast, easy, and efficient.

Solution 3:

if (myvar < 0) {
  myvar = -myvar;
}

or

myvar = Math.abs(myvar);