Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Count Elements of an Array Using Recursive Function in JavaScript



The recursive function calls itself with some base condition. Let’s say the following is our array with marks −

var listOfMarks=[56,78,90,94,91,82,77];

Following is the code to get the count of array elements −

Example

function countNumberOfElementsUsingRecursive(listOfMarks) {
   if (listOfMarks.length == 0) {
      return 0;
   }
   return 1 +
   countNumberOfElementsUsingRecursive(listOfMarks.slice(1));
}
var listOfMarks=[56,78,90,94,91,82,77];
console.log("The array=");
console.log(listOfMarks);
var numberOfElements=countNumberOfElementsUsingRecursive(listOfMarks);
console.log("The Number of elements = "+numberOfElements);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo110.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo110.js
The array=[
   56, 78, 90, 94,
   91, 82, 77
]
The Number of elements = 7
Updated on: 2020-09-09T13:02:23+05:30

587 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements