0

I want to validate undefined attributes from an object so I use ternary like this

item.subitem ? item.subitem.toString() : ''

Is there any way to simplify this expression using || or && ?

Eric Marcelino
  • 1,588
  • 1
  • 7
  • 11

2 Answers2

3

It's simple:

item.subitem && item.subitem.toString() || ''

Or simply like:

(item.subitem || '').toString()

OR,

''+(item.subitem || '')

If you can use optional chaining, then it can be even more simple:

item.subitem?.toString()

See this post for more detail.


As @Thomas mentioned in comment, you can also use an array and convert to a string:

[item.subitem].toString();

This should clear how it will work:

[].toString(); // ''
[undefined].toString(); // ''
['foo'].toString(); // 'foo'
['foo', 'bar'].toString(); 'foo,bar'
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

Yes you can

(item.subitem || '').toString()
Code Maniac
  • 37,143
  • 5
  • 39
  • 60