How can I check the positive number in Javascript and return the opposite?

Example, pass to a function or enter into the prompt:

1: -1 14: -14

UPD: the code turned out to be with an error - plus changed to negative now changes as needed

  function opposite(number) { if (number < 0) { return -(number) } else { return +(number) } } console.log(opposite(-1)); 

  • four
    Multiply the number by -1 , get the opposite. - Visman
  • @PavelMayorov for what a minus? - spectre_it
  • And why even if if you can return 0-number ;? - Vladimir Martyanov
  • @ Vladimir Martianov is a good question. what for. I solved the problem as best I could, then asked for help from the community, with the goal that the more experienced comrades offered a simpler and more universal solution - spectre_it
  • one
    @ stas0k Well, here it is more simple :-) - Vladimir Martyanov

2 answers 2

 function opposite(number) { if (number < 0) { return Math.abs(number) } else { return -Math.abs(number) } } opposite(700) //output -700 

For reference: Math.abs ()

 function opposite(number) { return number * (-1); } opposite(-1) //output 1 
  • one
    mark your answer as accepted and get the sign "Self-Taught" :) - Ruslan_K