0

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?

1
  • You would have to create the string depending on a condition. Check the condition first then create the string according to the condition result. If you do this often, look into using a formatting library such as Handlebars.js Commented May 27, 2015 at 19:23

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

sweet - i love it. Works perfectly!
2

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

Comments

1

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

2 Comments

really nice - the syntax is correct, and the additional Date.now is actually something I wanted to use eventually :)
@JohnWu - Feel free to change your "correct answer" selection ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.