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