#84 empty arrays

Want to check if an array is empty in your templates, for example:

There are many ways to do this, one way would be check the array length e.g.

Or even better, you can use the empty computed helper in your controller to easily check if your comments array is empty with:

 


Also published on Medium.

Published by

Emad Ibrahim

Author of asp .net MVC & TDD, entrepreneur, passionate technologist, programmer and productivity nut. more at http://t.co/oSJXPvzu

  • In HTMLBars an empty array will evaluate to false so an {{#unless myEmptyArray}} will also work.

    • Good point. that was probably a bad example of “empty” 🙂

  • JeffreyBiles

    If you’re going to be looping through the array when it has items, you can use an else block for the empty array case.

    {{#each comments as |comment|}}
    {{comment.title}}
    {{else}}
    No Comments
    {{/each}}

    • Thanks for the tip. I think I used a really bad example to illustrate the usefulness of “empty”. With that said, I think I will mention this in a future tip – it’s one of my favorite {{each}} features.