Positive Number to Negative Number in JavaScript?

Oscar Godson picture Oscar Godson · Apr 7, 2011 · Viewed 218.3k times · Source

Basically, the reverse of abs. If I have:

if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  slideNum = -slideNum
}
console.log(slideNum)

No matter what console always returns a positive number. How do I fix this?

If I do:

if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  _selector.animate({
    left: (-slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
} else {
  _selector.animate({
    left: (slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
}

it works tho, but it's not "DRY" and just stupid to have an entire block of code JUST for a -.

Answer

RichardTheKiwi picture RichardTheKiwi · Apr 7, 2011
Math.abs(num) => Always positive
-Math.abs(num) => Always negative

You do realize however, that for your code

if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ slideNum = -slideNum }
console.log(slideNum)

If the index found is 3 and slideNum is 3,
then 3 < 3-1 => false
so slideNum remains positive??

It looks more like a logic error to me.