Home Ask Login Register

Developers Planet

Your answer is one click away!

Marian Petruk February 2016

How to unshorten this js code

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.


Idos February 2016

This is the ternary operator in javascript.

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

Translates to:

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

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

if (!checkEnd())
    if (role == 'player')

jmugz3 February 2016

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

Post Status

Asked in February 2016
Viewed 2,192 times
Voted 8
Answered 2 times


Leave an answer

Quote of the day: live life