bzlight
bzlight

Reputation: 1150

Conditional operator not evaluating properly

Problem

I'm trying to assign a value to a variable using a conditional operator based on the string value of another variable.

Code

const test = fnUserPlatform.platform === ('ps4' || 'xb1' || 'pc') ? 'p2.br.m0.weekly' : 'br.defaultsolo.current';

When fnUserPlatform.platform equals 'ps4" test evaluates properly to p2.br.m0.weekly but when fnUserPlatform.platform is 'xb1' or 'pc' it evaluates to 'br.defaultsolo.current' which is not correct.

Does anyone know why its evaluating in this way?

Upvotes: 1

Views: 49

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386522

By using this expression,

'ps4' || 'xb1' || 'pc'

you get the first string because this string is a truthy value and by using logical OR ||, this value is takes as result for this expression.

If the first value would be an empty string, then the first truthy value is taken

'' || 'xb1' || 'pc'
      ^^^^^

For a better approach to check if you have an item and some values, you could take an array and check with Array#includes.

const
    test = ['ps4', 'xb1', 'pc'].includes(fnUserPlatform.platform)
       ? 'p2.br.m0.weekly'
       : 'br.defaultsolo.current';

Upvotes: 4

Matteo Pagani
Matteo Pagani

Reputation: 545

Try to do this:

const test = fnUserPlatform.platform === 'ps4' ? 'p2.br.m0.weekly' : fnUserPlatform.platform === 'xb1' ? 'p2.br.m0.weekly' : fnUserPlatform.platform === 'pc' ? 'p2.br.m0.weekly' : 'br.defaultsolo.current';

Upvotes: -1

Related Questions