mainSize = mainSize < 0 ? 20 : mainSize ;
What do the "?" and the ":" within that assignment of the 'mainSize' variable?
mainSize = mainSize < 0 ? 20 : mainSize ;
What do the "?" and the ":" within that assignment of the 'mainSize' variable?
This is the ternary operator ( docs ).
This is a shortened version with slightly different behavior than if
.
Example of a conditional:
if (mainSize < 0)
mainSize = 20;
else
mainSize = mainSize;
It is equivalent to:
mainSize = (mainSize < 0) ? 20 : mainSize ;
The light difference between changing the if
by a ternary is that the ternary will result in one of the two values (as if it returns) while a if
will execute whatever is inside of your execution block, not necessarily returning something.
For example, the% w /% of the following can not be represented as a ternary:
if (mainSize < 0)
negativo = true;
else
positivo = true;
mainSize = mainSize < 0 ? 20 : mainSize ;
? é igual ao if
if(mainSize < 0){
}
: igual ao else
else{
}
mainSize < 0 se 20 senão mainSize