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

247
Vistas
Shorthand way to write Conditional in Javascript

I usually run into writing conditionals like this and I'm wondering if there a short hand way to write something similar below without calling a function

const currentValue = this.props.book.location.areaValueInDollars ? this.props.book.location.areaValueInDollars : 0; 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use nullish coalescing operator:

this.props.book.location.areaValueInDollars || 0

More on the subject here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use short-circuiting and the Logical OR operator.

const currentValue = window['a'] || 0; 

console.log(currentValue);

If the variable exists, then the first operand will return true, causing it to "short circuit" and be returned. The second operand is only evaluated if the first is false, since the expression is evaluated from left to right.


Using the Logical OR operator has a caveat though. If the variable is 0, null, undefined... (for full list, see Falsy values), it will return false.

To solve this, we can use the Nullish coalescing operator, which will only return the right-hand side operand if the left operand is null or undefined. Like so:

const currentValue = window['a'] ?? 0; 

console.log(currentValue);

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