Javascript a recursive function with no clear base case?

You can simply return the value you are interested in:

function countElements(arr) {
  var count = 0;
  for (var i=0; i<arr.length; i++) {
    if (arr[i] instanceof Array) {
      count += countElements(arr[i]); // recursion here
    } else {
      count++; // normal element counts as 1
    }    
  }
  return count;
}

Demo: http://jsbin.com/ejEmOwEQ/1/edit

WARNING: The function might not end if the array contains self reference (var arr = []; arr.push(arr); countElements(arr);)

Leave a Comment