Thomas_da_tank
Thomas_da_tank

Reputation: 61

I am trying to convert numbers into their opposite value regardless of whether number is positive or negative

I tried this code, it works

const opposite = number => -number

Code won't run, just trying to experiment with different ideas

function opposite(number){
   return Math.abs(number) 
}

opposite(1)

What Am I missing here ?

Upvotes: 0

Views: 818

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

Your code is running, your just noticing the output for two reasons:

  1. returning a value from your function doesn't mean it will be logged to the console. You need to console.log() the function call to see its output (the returned value)

  2. Math.abs() will get the absolute value of a number passed into it (which isn't the same as the opposite). You can think of this as the distance a given number is away from 0. Thus doing Math.abs(1) will give 1 not -1, perhaps making you think your function isn't working. With this in mind Math.abs() will only give you the opposite for numbers which are negative, not positive.

See running example below:

function opposite(number){
   return Math.abs(number) 
}

console.log(opposite(-1)); // returns 1
console.log(opposite(1)); // returns 1

Upvotes: 2

Related Questions