1

I was trying to understand code of this Tic-Tac-Toe (30 lines of code) game and encountered with this strange for me notation of js.

  1. t[id] ? ai() : move(id, 'ai');
  2. !checkEnd() ? (role == 'player') ? ai() : null : reset()

I know that this is shortened version of if-statement, but don't know exactly how to convert it.

Thanks in advance.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Read up on the [ternary operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) (AKA the conditional operator). – nnnnnn Feb 08 '16 at 22:08
  • Got to love the arrogance of the comments... The second one is essentially a nested `if` statement. In case that was the confusing bit as you said you understand that it's a shorthand if statement. – ste2425 Feb 08 '16 at 22:11
  • I have already read that this is ternary operator, thanks, but how to translate second if-statement with function? – Marian Petruk Feb 08 '16 at 22:12
  • You'd evaluate the inner ternary first `(role == 'player') ? ai() : null` and the result becomes part of the outer ternary – j08691 Feb 08 '16 at 22:15

2 Answers2

3

This is the ternary operator in javascript.

t[id] ? ai() : move(id, 'ai');

Translates to:

if (t[id])
    ai();
else
    move(id, 'ai');

And !checkEnd() ? (role == 'player') ? ai() : null : reset() to:

if (!checkEnd())
    if (role == 'player')
        ai();
    else
        ;
else
    reset();
Idos
  • 15,053
  • 14
  • 60
  • 75
0

That is called a ternary operator.

Check this from MDN. They have good info if you're starting. And this one from MSDN

Simply put,

condition ?  expression if true : expression if false
mugabits
  • 1,015
  • 1
  • 12
  • 22