0

I have two variables in a jquery code and if item.a not exist, it outputs a 'null' so i want to check if the variable exists. Here's the code:

.append( "<a>" + item.a + ", " + item.b + "</a>" )

If there is no "item.a" it results in

null, Blabla

I tried this if / else statement but it returns nothing

.append( "<a>" + (item.a) ? item.a : + ", " + item.b + "</a>" )

Any idea?

Adige72
  • 177
  • 2
  • 4
  • 17
  • Use native JavaScript, see: http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null for more details. – StuperUser Jul 05 '12 at 11:01
  • 1
    strictly speaking you do not need an _existence_ check - if the value is `null` you need a _falsey_ check. – Alnitak Jul 05 '12 at 11:07

2 Answers2

5

Your attempt was close. Try this instead:

.append( "<a>" + (item.a ? item.a : "") + ", " + item.b + "</a>" )

Or, assuming you don't want the comma when you don't have item.a:

.append( "<a>" + (item.a ? item.a + ", " : "") + item.b + "</a>" )
James Allardice
  • 156,021
  • 21
  • 318
  • 304
1

The condition operator you use

EDIT

.append( "<a>" + (item.a != null ? item.a + ", " : "") + item.b + "</a>" )

If variable is null

if(varName === null)
{
    alert("variable has null");
}

If variable does not exists

if(typeof varName === 'undefined')
{
    alert("variable not defined");
}
Adil
  • 139,325
  • 23
  • 196
  • 197
  • The variable isn't `undefined`; it's `null` instead, so your code won't work. – Bojangles Jul 05 '12 at 11:01
  • You should use triple equals: http://stackoverflow.com/questions/8044750/javascript-performance-difference-between-double-equals-and-triple-equals – StuperUser Jul 05 '12 at 11:04