Arrow and ternary functions

Working on Guess the Number
this code seems to work

function updateScore(theWinner){
    if (theWinner === 'human'){
        humanScore += 1;
    } else{
        computerScore += 1;
    }
}

but this code seems not to work.
const updateScore = winner => 'human' ? humanScore += 1 : computerScore += 1;
why are the two codes not equivalent?
How can I improve the second?
Is there a better way of doing the first code?
thank you

In the second example you are not referencing the argument passed in to the function inside the function (winner):

const updateScore = winner => 'human' ? humanScore += 1 : computerScore += 1;

Instead you are evaluating the string ‘human’ which is always going to be truthy (it’s not an empty string). So in your arrow function/ternary humanScore += 1 will always be executed. You could do something like:

const updateScore = winner => winner === 'human' ? humanScore += 1 : computerScore += 1;

But I personally prefer if/else statement when the logic involves assignment to different variables (humanScore/computerScore) and I use the ternary when it returns a value that can be assigned to one target.

1 Like

Thank you.
That’s a very helpful explanation.

1 Like

What do you mean by

?

I mainly like to use ternary in situations like this where it’s returning something assigned to one variable (greeting) but it’s more my personal preference:

let greeting = isBirthday ? 'Happy birthday' : 'Good morning';

It also comes in handy in React conditional rendering to render one out of 2 options:

{isLoggedIn ? <button>Logout</button> : <button>Login</button>}

When there are two different code-blocks doing different logic, I personally prefer the if/else to choose between those.

Thank you for taking the time and writing a helpful explanation.
Cheers