This question already has an answer here:
- Question mark and colon in JavaScript 6 answers
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'
Update:
What's the need for this sort of coding? Is this more efficient or just a shortened version with the same efficiency?
It's called the ternary operator.
It is ternary operator/conditional operator .
In mathematics, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A.
it is a short hand form of if..else
e.g. want to find out if a number is even or not
//Using if..else approach
//using ternary
One more variant is switch
//using switch
Now, if you have a simple if..else condition to perform like the one described, you can go ahead with ternary.
But if the conditional checking becomes complex , go either with if..else or switch as readability will be lost in ternary
e.g. it is easy to perform minimum or maximum of two numbers using a ternary operator but becomes clumsy to find the largest & second largest among 3 or more numbers and is not even recommmended. It is better to use if..else instead
Responding to the question update "Why need for this sort of coding?"
You can sometimes use the ternary operator to reduce complexity:
For example, I have a web page which needed to verify that at least two out of three specific text fields had values entered. The if/else logic looked pretty ugly, but the ternary operator made it a one-liner to determine how many fields were filled in:
This solution appears quite elegant and easy to read than some alternatives.
This is a ternary operator, a shorthanded way to do if statements.
If re-written, it would look like this:
It is the conditional operator, it is equivalent to something like this:
But I think that an assignment statement is missing in the code you posted, like this:
The
score
variable will be assigned ifpattern.Gotoccurance.score
is 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.score
will be assigned to thescore
variable 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.Update: The performance will be equivalent, 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: