What does this bit of code represent? I know it’s some kind of if alternative syntax…
pattern.Gotoccurance.score != null ? pattern.Gotoccurance.score : '0'
What’s the need for this sort of coding? Is this more efficient or just a shortened version with the same efficiency?
It is the conditional operator, and it is equivalent to something like this:
But I think that an assignment statement is missing in the code you posted, like this:
The
scorevariable will be assigned ifpattern.Gotoccurance.scoreis not null:A common pattern to do this kind of ‘default value’ assignments in JavaScript is to use the logical OR operator (
||) :The value of
pattern.Gotoccurance.scorewill be assigned to thescorevariable only if that value is not falsy (falsy values arefalse,null,undefined,0, zero-length string orNaN).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:
Related question: