Can anyone help me , why my function is not executing

In the debugger ,it says, return value is undefined, so, after for loop, I have added, “return result”, Still it shows the same thing.

Hi @vaishnavi_A.N

There are several problems:

  • You don’t need the first line …
  • … but you need a variable that holds the function parameter: function avg (arr).
  • sum gets reset on every round of the loop. It needs to be outside the for loop to just be set to 0 at the beginning.
  • You’re if condition is never met, because you compare the array values with the array length. This should be: i === arr.length - 1.

That’s it :slightly_smiling_face:
Michael

1 Like

yes, I thought stupidly, that arr[i]===arr.length, I corrected it.
Is this the right way @mikoMK?
I am getting the o/p in the console, but when I change a value in the array, and again save it, it is going to the source tab and at sum=0, it is showing undefined.
The same thing when I tried in codepen, it gave me a value initially, and then within seconds, gave me another o/p.

You are a saviour man!!! @mikoMK.
u explain concepts so easily.

:heart: :heart: :heart: :heart: from India.

I’m glad it was helpful so far. :slightly_smiling_face:

It’s unclear for me what your final goal is with your updated Pen. You push the index into an array in certain conditions, you calculate the average before the sum is calculated and so on.

Often when you code a function you have some input (the array in your case) and you have an output (return value) which you save into a variable (the average of the array values?). You would then call the function like this: const avg = myFunc(arr2);.
So your ultimate goal is to code a function which takes an array as input, calculates the average of the items and returns said average.