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

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

this will work

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

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 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