Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report

0

this will work

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!