{

How to get array length and check an array is empty in HandlebarJS


Handlebar array length JavaScript example

In this short tutorial, Learned about how to find the array length in handlebar template javascript with examples.

There is a length attribute on the array which will not work outside but inside {{each}} helper classes.

Array length in handlebar javascript

if json object data of type is an array, we can use the length property as seen below syntax.

{{array.length}} let’s declare json object

 {
  numbers: ["one", "two", "three"]
}

In html template, use {{numbers.length}} to check length of an array

Total records - {{numbers.length}}  

Output rendered is

Total records - 3  

Helper functions to check the length of an array

Let’s declare a customer helper class and register seen below.

Handlebars.registerHelper('arraySize', function (data) {
  return data.length;
});

In the template access the helper class using double brace syntax

{{arraySize numbers}} // returns 3

how to check array or list is empty in handlebar

Sometimes, we want to check array length is zero or the array size is empty.

We have to use handlebar if condition

array.length will not work in if blocker in handlebars

Instead, you can use an array in checks array is empty or not

<div>
{{#if numbers }}
<p>Number array length is {{numbers.length}}</P>
{{else }}
Array is  empty
{{/if}}
</div>

We can also write a custom helper to check if the array length is empty or greater than 3

<div>
{{#isArrayEmpty numbers 0}}
array length is empty
{{else }}
<p>Number array length is {{numbers.length}}</P>
{{/isArrayEmpty }}
</div>

We have to register a custom helper

Handlebars.registerHelper('isArrayEmpty', function (a, b, options) {
'use strict';
   if (a.length===b) {
     return options.fn(this);
  }
  return options.inverse(this);
});

Conclusion

You have learned how to check array length and check array or object or list is empty.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.