Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
I'm doing a function of inverting values, and the 0, is also inverting, how do I make the 0 not to be negative?

Code in Javascript, please help me to make 0 not negative

function invertSign(val) {

    return (val * -1);
}

console.log(invertSign(1)) -1
console.log(invertSign(-2)) 2
console.log(invertSign(0)) -0
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use || 0:

function invertSign(val) {
   return -val || 0;
}

If -val evaluates to -0, it will be a falsy value, and so the || operator will evaluate to the second operand, which is 0. And so -0 is replaced by 0.

Alternatively, you subtract from 0:

function invertSign(val) {
   return 0 - val;
}

Here -0 never occurs, because the minus here is not a unary operator, but the binary one. 0 - 0 is just 0, so this may be the simplest solution.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can check if the value is zero, and if it is, then return 0


function invertSign(val) {
    if (val === 0) return 0;
    return (val * -1);
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try adding an if statement to check if val === 0.

function invertSign(val) {
    if (val === 0) return val;
    return val * -1;
}

console.log(invertSign(1)); // logs -1
console.log(invertSign(-2)); // logs 2
console.log(invertSign(0)); // logs 0
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda