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,519
  • 1
  • 6
  • 10

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
  • 78,842
  • 31
  • 152
  • 211
1

Yes you can

(item.subitem || '').toString()
Code Maniac
  • 35,187
  • 4
  • 31
  • 54