Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) jQuery and AJAX The Office Status Project Revisited

Jim Dennis
Jim Dennis
13,075 Points

Could we not use the Ternary Operator?

The if (....) { statusHTHML += ... } else code seems rather verbose.

Could we not use statusHTML += '<li class="' + employee.inoffice?'in':'out' + '">' + employee.name + '</li>' ... to replace those six lines of code? Interpolating the result of the ternary operator expression?

2 Answers

rydavim
rydavim
18,814 Points

None of the courses that are typically before this one cover ternary conditionals, so I believe that's why it isn't used here in the video.

Personally, I think I would only use it to handle the in-office if statement though. For me, putting it all together on a single line makes it more difficult to read, particularly if I need to revisit it down the road. Certainly if you were trying to minify your code, that might be worth it.

// I would consolidate...
if (employee.inoffice === true) {
    statusHTML += '<li class="in">';
  } else {
    statusHTML += '<li class="out">';
  };
// into...
statusHTML += employee.inoffice ? '<li class="in">' : '<li class="out">';
// and leave the rest of it intact for human legibility.

That's completely a personal preferance though. The short answer to your question is yes, you could use the ternary operator.

As a side note, code is frequently misinterpreted or missing pieces on the forums if you just paste it into the post body. When including code fragments, you can use the following markdown to ensure it's displayed correctly. You also get fancy syntax highlighting.

```language

your code here

```

Happy coding! :)

// I would consolidate...
if (employee.inoffice === true) {
    statusHTML += '<li class="in">';
  } else {
    statusHTML += '<li class="out">';
  };
// into...
statusHTML += employee.inoffice ? '<li class="in">' : '<li class="out">';
// and leave the rest of it intact for human legibility.

Sry, was just testing out what Rydavim showed. :)