jms
1
I guess all of us have written code like this:
obj = {}
if (!obj.foo) {
obj.foo = bar
} else {
obj.foo += bar
}
It would be a lot more concise if we could just write:
obj = {}
obj.foo += bar
So if foo doesn't exist yet, it gets initialised with the value of bar.
Thoughts?
ljharb
2
+= already does + combined with assignment for this case. For what you're asking about, i think you'd need obj.foo ||= bar or obj.foo ??= bar?
jms
3
Thank you for the hint with ||=.
I guess I would hope obj.foo += bar to work like obj.foo = obj.foo + bar || bar.
Example:
let fooExists = {
foo: 4
}
let fooDoesntExist = {}
function addTwo(obj) {
obj.foo = obj.foo + 2 || 2
return obj
}
addTwo(fooExists)
// foo => 6
addTwo(fooDoesntExist)
// foo => 2
If I run the following code instead it will return NaN
let fooDoesntExist = {}
function addTwo(obj) {
obj.foo += 2
return obj
}
addTwo(fooDoesntExist)
// foo => NaN
Now that I know of obj.foo = obj.foo + bar || bar it's fine though. Even though I think obj.foo += bar is more concise and better looking.
Edit:
I guess this would also be a nice syntax: obj.foo += 2 || 2. But it also returns NaN if foo doesn't exist yet.