1

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.

nice_dev
  • 17,053
  • 2
  • 21
  • 35

4 Answers4

0

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.

Marvin
  • 853
  • 2
  • 14
  • 38
0

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;
}
dome
  • 820
  • 7
  • 20
0

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.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • You can also change the first code block to this for better understanding `condition ? whentrue: whenfalse;` – weegee May 11 '19 at 19:12
-1

Its like a if statement. You can translate it like:

if(fade == undefined ){
    this.fade = 5;
} else {
    this.fade = fade
}
Doan
  • 208
  • 5
  • 19
  • 1
    _"Its like a if statement"_ No its not. You can execute statements inside `if` block but you can't use statements using ternary operator. – Maheer Ali May 11 '19 at 18:31
  • 1
    I think what OP meant was that the ternary operator is a short form of a simple if statement, which it is – Marvin May 16 '19 at 23:28