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

143
Visualizações
default value while adding values inside an object

I am trying to sum up values inside an object, but i am adding a Nullish coalescing operator if undefined or null then it should have zero value. But here instead of getting 10 i am getting 4 only.

let data = {
  a: 4,
  b: 6,
  c: null
}

console.log(data?.a ?? 0 + data?.b ?? 0 + data?.c ?? 0)

Any help is appreciated

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Just add small brackets this will do. The reason for above not running is because the ?? operator is conditional and will evaluate the first statement since there is value for data?.a it will not run the right part of it which is 0 + data?.b ?? 0 + data?.c ?? 0

let data = {
  a: 4,
  b: 6,
  c: null
}

console.log((data?.a ?? 0) + (data?.b ?? 0) + (data?.c ?? 0))

about 4 years ago · Juan Pablo Isaza Relatório

0

this will work

console.log((data?.a ?? 0) + (data?.b ?? 0) + (data?.c ?? 0))
about 4 years ago · Juan Pablo Isaza Relatório

0

Ideal case for reduce.

  • First: make an array of values with Object.value
  • Next: reduce (awesome method to master)
  • Optional: Use + operator for elegant type conversion (might not work in every case)
console.log(Object.values(data).reduce(function (sum, value) { return sum + +value }, 0))

Good practice is to learn from utility / helper libraries like lodash or ramda. Lodash provides nice solution as well

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