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?
You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability. As an example of multiple else if statements, we can create a grading app that will output a letter grade based on a score out of 100.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Syntax: result = condition ? value1 : value2; If condition is true then value1 will be assigned to result variable and if wrong then value2 will be assigned.
This rule has a string option: "always" (default) enforces newlines between the operands of a ternary expression. "always-multiline" enforces newlines between the operands of a ternary expression if the expression spans multiple lines. "never" disallows newlines between the operands of a ternary expression.
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:
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';
}
It's called the ternary operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With