简体   繁体   中英

How does the ternary operator in the else statement work in this example?

Though the question is old but still baffles me alot

If you've watched the javascript udemy course...

In the pig game the guy created he said

If(dice !== 1) {
//Let's assume I've created my roundscore and other variables
}

/*What really baffles me is when he got to else statements he said */

else {
activePlayer === 0? activeplayer = 1 : activeplayer = 0
}

//Please why can't he say 

else if (dice === 1){
activeplayer = 1
}

/*Please I need a clear explanations */

Ternary operators and if/else statements can be interchangeable and either can be used in the place of others in most cases. In your case, the if statement checks if the dice does not equal one, then goes to the else statement. In here the code checks if the activePlayer variable is equal to zero: if it is, then the variable is set to 1 and if not the variable is set to 0.

However, there seems to be a mistake in the if statement as when the if condition is satisfied, the code will not regard the else statement, meaning the else statement will only run if the variable = 1, meaning the ternary operator is redundant. Look over your question again and see, I believe there is a mistake in your code or even the video.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM