I want to increment an object value using the optional chaning operator (?.). In my example I want to increase the age of a Person by one in a function called birthday() only if an age is set for the current person. The line with the if clause works fine (also tenary if works obviously). However I wanted to know if something like the line below is possible. The syntax given results in an SyntaxError: invalid increment/decrement operand. Maybe its an issue based on the operator precedence, but I have now clue how to solve it.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let peter = new Person("Peter", 27);
let paul = new Person("Paul", undefined);
Person.prototype.birthday = function() {
if (this.age) this.age++;
};
//Person.prototype.birthday = function(){this?.age++};
peter.birthday();
paul.birthday();
console.log(peter, paul);
I want to increment an object value using the optional chaning operator (?.)
You can't. The reason is that the result of optional chaining is just a value, not a property reference, so you can't use any of the operators that write back to the property (like ++
, --
, +=
, etc.). (That's shown by this part of the specification.) In contrast, the result of a property acccessor like this.age
is (in specification terms) a reference to the property, so the operator can write back to the property.
Your version with if
is the way to handle this.
But separately, just as a side note, your two statements do different things.
Your optional chaining (this?.age
) is checking that this
is not nullish. But your if
is checking that this.age
is not nullish. The equivalent if
would be if (this) { this.age++; }
. But from the overall code context, you don't want that, you want what you currently have in the if
, though I think I'd probably make it a more specific check:
if (this.age !== undefined) {
this.age++;
}
I say that because 0
is falsy, so just if (this.age)
would not increment 0
.