I have a question understanding some JavaScript syntax, below:
var myObject = {
value: 0;
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.increment( );
document.writeln(myObject.value); // 1
myObject.increment(2);
document.writeln(myObject.value); // 3
Specifically:
this.value += typeof inc === 'number' ? inc : 1;
Is this line saying that if:
typeof inc === 'number'
then:
this.value += inc
Any good way to think about this or resource to help understand would be appreciated.
That’s correct, it’s called a ternary operator. If the statement resolves to true it does the first option if not it resolves the second. It can be broken down into a simple if/else