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 &&
?
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 &&
?
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'