How to get array length and check array is empty inHandlebarJS


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

There is a length attribute on 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, Then we can use 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 length of an array

Let’s declare an customer helper class and register as 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 an empty in handlebarJS

Some times, we want to check array length is zero or array size is empty

We have to use handlebar if condition

array.length will not work in if blocker in handlarbar

Instead you can use 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 custom helper to check if 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 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 checking 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.