Search code examples
javascriptarraysfunctionreturn

I need help understanding this function with counter


Trying to figure out what this function does, can somone explain it to me. is there a better platform for these questions?

function whatDoIDoFunction (x, arr) {
   var y = 0;
   var i=0;

  for(i=0; i < arr.length; i++){
    if(arr[i] == x)
      y++;
  }
return y;
}

Solution

  • It's good to add console.logs to see what's happening.

    function whatDoIDoFunction(x, arr) {
      var y = 0;
      var i = 0;
    
      for (i = 0; i < arr.length; i++) {
        console.log('examining ' + arr[i]);
        if (arr[i] == x)
          y++;
        console.log('y is ' + y);
      }
      return y;
    }
    
    var array = [1,2,1,2,3,4,5,1,0]
    whatDoIDoFunction(1, array);

    If you run the snippet, you will observe that y increments only when the "current" array element is equal to the x that is passed in as the first parameter. In other words, your function counts how many occurrences of x are in arr.