nami
nami

Reputation: 1266

Help with ternary operator

I don't think I am using the ternary operator correctly as I am not getting the results am I after:

buildHTML.push("<a href='http://mysite/user?screen_name=" + data.friend == null ? data.user.me : data.friend + "'>" + data.friend == null ? data.user.me : data.friend + "</a>");

This gives me null if friend is null, and gives me friend if friend is not null

It should be giving me me if friend is null and friend if friend is not null.

What am I doing wrong?

Upvotes: 0

Views: 242

Answers (3)

nikmd23
nikmd23

Reputation: 9103

A few things to note that may help you out:

  • Use === instead of == when comparing items in JavaScript.
  • data.friend may be undefined, which is different than null, you may want to do a different check.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298908

Try adding some parentheses:

buildHTML.push("<a href='http://mysite/user?screen_name=" + 
(data.friend == null ? data.user.me : data.friend)
 + "'>" + 
(data.friend == null ? data.user.me : data.friend)
+ "</a>");

Upvotes: 1

Sampson
Sampson

Reputation: 268354

Wrap up the ternary logic:

buildHTML.push("<a href='http://mysite/user?screen_name=" + (data.friend == null ? data.user.me : data.friend) + "'>" + (data.friend == null ? data.user.me : data.friend) + "</a>");

You may also need to check to see whether data.friend is == or === to null.

Upvotes: 4

Related Questions