You can't use if like that. The fundamental problem is that in JavaScript if is a statement, not an expression, and it doesn't return any value (unlike more strict functional languages like Scala, where everything is an expression and produces a value).
So you have the following options:
Use ternary conditional operator ?: which produces a value and actually can be used in an expression:
... + x.description? x.description : '' + ...
The only inconvenience is that you always need an else value, so in case of just checking description for null, you need to provide an empty string as an alternative. It could be a hassle when you need a lot of fields to print.
- Use a helper function within the formatting scope. This is an elegant solution in case you have just a single big object to format:
const source = {
first: 'first',
second: null,
third: 'third',
}
function fmt(key) {
return source[key]? source[key] : ''
}
let html = '<div><hr>'
+ fmt('first') + '<hr>'
+ fmt('second') + '<hr>'
+ fmt('third') + '<hr>'
+ '</div>'
document.write(html)
- As a more compact alternative to ?: operator, you can use || operator like this:
const s = {
first: 'first',
second: null,
third: 'third',
}
let html = '<div><hr>'
+ (s.first || '') + '<hr>'
+ (s.second || '') + '<hr>'
+ (s.third || '') + '<hr>'
+ '</div>'
document.write(html)
I guess this one is more elegant than #1, since you don't have to repeat property access 2 times :)