0

I am trying to write this if/else statement using javascript's ternary operator syntax. Is it possible to write this as a ternary operator?

function changePlayer() {
            if (currentPlayer === playerOne) {
                currentPlayer = playerTwo
            } else {
                currentPlayer = playerOne
            }
        };

My current attempt is:

function changePlayer(){
      currentPlayer === playerOne ? playerTwo : playerOne;
}
1
  • 1
    currentPlayer=[playerOne, playerTwo][+(currentPlayer==playerOne)] Commented Jan 10, 2016 at 23:11

2 Answers 2

2

You just miss the assignment statement. So the final example will go like this:

function changePlayer(){
      currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}
Sign up to request clarification or add additional context in comments.

4 Comments

nice! will give you the green tick when I can
I'd say he misses the assignment.
I think you meant the assignment. The comparison wasn't missing.
@PaulFitzgerald There was nothing wrong with the code, it was just the explanation that needed a tweak.
1

The first argument of the ternary operator is the condition:

function changePlayer(){
  currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.