zallarak
zallarak

Reputation: 5515

Conditionals/syntax confusion

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.

Upvotes: 1

Views: 163

Answers (4)

kinakuta
kinakuta

Reputation: 9037

The ternary operator is just a shorthand version of if/else. It's sometimes helpful to put the conditional expression inside parentheses to better see the condition being tested:

this.value = (typeof inc === 'number') ? inc : 1;

So if typeof inc results in "number" then assign inc to this.value, otherwise assign 1.

Upvotes: 1

Joe
Joe

Reputation: 82554

It's the ternary operator.

this.value += typeof inc === 'number' ? inc : 1;

is the same as

if (typeof inc === 'number') {
    this.value += inc;
} else {
    this.value += 1;
}

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270599

It is indeed saying that if typeof inc === 'number' then to add inc to this.value, and otherwise to add 1 to this.value. The pattern is an example of the ternary operator, which returns the left side of the : if the condition is true, and the right side of the : if false.

Ternary operations are somewhat more commonly used for assignment like:

// Assign the greater of y and z to x (or z if they're equal)
var x = y > z ? y : z;

// equivalent to:
if (y > z) {
  var x = y;
}
else var x = z;

In this case though, it is used to return a number to the += operator.

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23268

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

if (typeof inc === 'number') this.value += inc;
else this.value++;

Upvotes: 1

Related Questions