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?

2

2 Answers 2

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>" )
Sign up to request clarification or add additional context in comments.

1 Comment

@Alnitak - Yeah, probably. I've added that in.
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");
}

2 Comments

The variable isn't undefined; it's null instead, so your code won't work.
You should use triple equals: stackoverflow.com/questions/8044750/…

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.