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

175
Vistas
Shorthand for if/else in javascript

I wrote the function to check if a given number is positive, negative, or zero. Is there a shorthanded way?

Is it possible to test the condition with map (using object to index the conditions)? i was inspired by second solution in this question but not sure how it applies here.

const numCheck = (num) => {
  if (num == 0) {
    return "zero";
  } else {
    return num > 0 ? "positive" : "negative";
  }
};

const num1 = 3;
console.log(numCheck(num1));
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

In the solution below, the numCheck() method is tested by using the Array.prototype.map() method, considering three possible situations.

const numCheck = (num) => {
  return (num == 0) ? "zero" : ((num > 0) ? "positive" : "negative");
};

const numbers = [1, -1, 0];

console.log(numbers.map(number => numCheck(number)));

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do that, simply use Math.sign() :

const numCheck = n => ['negative','zero','positive'][1+Math.sign(n)]
 
console.log( numCheck( 4 ) ) 
console.log( numCheck( 0 ) ) 
console.log( numCheck( -3 ) ) 

about 4 years ago · Juan Pablo Isaza Denunciar

0

A shorter solution:

var numCheck = (num) => num == 0 ? "zero" : num > 0 ? "positive" : "negative";
const num1 = 3;
console.log(numCheck(num1));

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