Reputation: 3411
This seems like a simple question, but I don't know the correct syntax to make it work.
I have this code that's used by DataTables to generate a table:
'<td>'+d.expirationDate+'</td>'+
'<td>'+d.dateReceived+'</td>'+
I'd like to add a qualifier onto this that if the date field is not set, to display nothing instead of the word null
.
So I tried this:
'<td class="dropInfo">'+
if (d.debitExpDate !== 'null') {
d.expirationDate
}
+'</td>'+
but I get an error. Uncaught SyntaxError: Unexpected token if
What's the correct syntax for this?
Upvotes: 0
Views: 37
Reputation: 46361
The other answers are just fine, but there is another common option:
'<td>'+(d.expirationDate===null ? '' : d.expirationDate)+'</td>'
The advantage here is that more complex conditions can also be used. for example:
'<td>'+(d.expirationDate>Date.now() ? '' : d.expirationDate)+'</td>'
Upvotes: 1
Reputation: 5064
Several solutions are available.
Solution1: One line synthaxe, as pointed out by @Tom DDD (see his post)
'<td>'+d.expirationDate+'</td>'+
'<td>' + (d.dateReceived || '') + '</td>'+
Solution2 : Split the generation of your js with ; and concacenate with +=
var js = '<td class="dropInfo">';
if (d.debitExpDate !== 'null') {
js +=d.expirationDate
}
js+='</td>'
Upvotes: 2
Reputation: 4007
use a logical or ||
'<td>'+d.expirationDate+'</td>'+
'<td>' + (d.dateReceived || '') + '</td>'
|| evalutes the first thing on the left. If the left is "truthy" then it uses that value otherwise it uses the second thing.
Since null is not a truthy value in this case it will choose the empty string.
Upvotes: 3