Can anyone explain me this line of code and why we use the '?' in javascript?
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
Can anyone explain me this line of code and why we use the '?' in javascript?
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
This is a ternary operator which also present in other programming languages:
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
^^ ^^ ^^
if condition if true if false(else)
The above statement is equivalent to below:
if(n>0) {
return ninja.yell(n-1) + "a";
} else {
return "hiy";
}
For more read this tutorial.
The question mark is actually called Ternary Operator, usually in programming laguages it is used for a one line if statement and it has the following construct:
condition ? return if condition is True : return if condition is False
Think the ternary operator as "then" and the ":" as else. So your code will be:
return if( n > 0) then ninja.yell(n-1) + "a" else "hiy";
Hope you get it now!