JavaScript 'if' alternative [duplicate]

Solution 1:

It is the conditional operator, and it is equivalent to something like this:

if (pattern.Gotoccurance.score != null) {
  pattern.Gotoccurance.score;
} else {
  '0';
}

But I think that an assignment statement is missing in the code you posted, like this:

var score = pattern.Gotoccurance.score !=null ? pattern.Gotoccurance.score : '0';

The score variable will be assigned if pattern.Gotoccurance.score is not null:

var score;
if (pattern.Gotoccurance.score != null) {
  score = pattern.Gotoccurance.score;
} else {
  score = '0';
}

A common pattern to do this kind of 'default value' assignments in JavaScript is to use the logical OR operator (||) :

var score = pattern.Gotoccurance.score ||  '0';

The value of pattern.Gotoccurance.score will be assigned to the score variable only if that value is not falsy (falsy values are false, null, undefined, 0, zero-length string or NaN).

Otherwise, if it's falsy '0' will be assigned.

The performance will be equivalent, and you should focus on readability. I try to use the ternary operator on expressions that are very simple, and you can also improve the formatting, splitting it up in two lines to make it more readable:

var status = (age >= 18) ? "adult"
                         : "minor";

Related question:

  • To ternary or not to ternary?

Solution 2:

This is a ternary operator, a shorthanded way to do if statements.

If re-written, it would look like this:

if (pattern.Gotoccurance.score != null) {
   return pattern.Gotoccurance.score;
} else {
   return '0';
}