Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda