-1

Can anyone explain me this line of code and why we use the '?' in javascript?

return n > 0 ? ninja.yell(n-1) + "a" : "hiy"; 
  • 3
    Expression followed immediately by `?` will get executed if condition becomes true else expression after `:` will get executed.. To know more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – Rakesh_Kumar May 04 '15 at 07:16
  • 4
    see this question: http://stackoverflow.com/questions/6259982/js-how-to-use-the-ternary-operator – samgak May 04 '15 at 07:17

2 Answers2

3

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.

FatalError
  • 560
  • 2
  • 18
1

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!

Sid
  • 14,176
  • 7
  • 40
  • 48