Ali Ankarali
Ali Ankarali

Reputation: 3127

Alternative way to use ternary without an else

Is there a cleaner way to achive this?

const message = `Error message: ${json.email ? json.email[0] : ''}`

Upvotes: 0

Views: 283

Answers (4)

Felipe Goncalves
Felipe Goncalves

Reputation: 1

When you use ternary operation, always return a value. Logical operators should be use with careful.

As logical expressions are evaluated from left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is evaluated as false by short circuit.
  • true ||(anything) is evaluated as true through short circuit.

Upvotes: 0

basilikum
basilikum

Reputation: 10528

In case you use lodash, you can use the _.get method, which lets you specify a whole path of nested property accessors and if any property along the path is not found it can optionally return a default value:

_.get(json, 'password[0]', '');

So your example would translate to something like this:

const message = `Error message: ${_.get(json, 'email[0]', '')} ${_.get(json, 'password[0]', '')} ${_.get(json, 'username[0]', '')}`

Upvotes: 0

skyboyer
skyboyer

Reputation: 23705

Actually there is tc39 proposal on that: optional chaining. After it is live it would be as easy as

const message = `Error message: ${json?.email?.[0] || ''} ${json?.password?.[0] || ''} ${json?.username?.[0] || ''}`

"Stage 1" means "it seems to be on the way to be discussed". You can use such a syntax that with help of Babel.

Otherwise(no Babel) you better use helper like lodash's _.get or write your own version. Why don't use ternary operator? Because of its bad readability.

Upvotes: 3

Tushar
Tushar

Reputation: 87203

You can use || as below

(arr || [''])[0]

If arr is falsy then a new array with empty string as first element is used. [0] will return the first element of array.

Upvotes: 2

Related Questions