I read following statemend in JavaScript:
this.fade = (fade == undefined ? 5 : fade);
Its new for me therefore i don't know what does it mean.
I read following statemend in JavaScript:
this.fade = (fade == undefined ? 5 : fade);
Its new for me therefore i don't know what does it mean.
This is called the ternary operator
The ternary operator is a short form of a one-line if statement.
The expression before the ?
is the condition.
If it is true then the variable on the left side of the =
is equal to the value before the :
, otherwise, it is the value after the :
.
The parentheses around this expression are completely optional.
this.fade = fade == undefined ? 5 : fade;
would have the same result.
It is the ternary operator. It means that if fade == undefined
it will return 5
(this.fade = 5
) else it will return fade
(this.fade = fade
).
To be more clear, is like writing an if-else statement:
if (fade == undefined) {
this.fade = 5;
} else {
this.fade = fade;
}
The code you have showed is using ternary operator. It is used to evaluate a final expression based on some condition. The general syntax of ternary operator is
condition ? exp1 : exp2;
exp1,exp2
are two expression. If the condition is true
the above whole line will evaluate to exp1
otherwise exp2
.
You can use if else
for ternary operators. Like in your code it will be.
if(fade == undefined){
this.fade = 5
}
else{
this.fade = fade
}
Note:if/else
can be always used instead of ternary operators but ternary operator can't be always used for if
statements.
Its like a if statement. You can translate it like:
if(fade == undefined ){
this.fade = 5;
} else {
this.fade = fade
}