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
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))
this will work
console.log((data?.a ?? 0) + (data?.b ?? 0) + (data?.c ?? 0))
Ideal case for reduce.
Object.value+ 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