Need help with simplest JavaScript function that returns an average of array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Need help with simplest JavaScript function that returns an average of array

Guys, my code doesn't work no meter what I'm doing. Please help!!!! Function have to return an average of numbers in array. Here is my code: function averageLst(nums) { for (var i = 0; i < nums.length; i++) { total += nums[i]; } var nums = []; var avg = total / nums.length; } averageLst([75, 60, 100, 90]); Thanks!

14th Jun 2017, 10:23 PM
DIY Mods
DIY Mods - avatar
3 Answers
+ 10
> the line "var nums = [];" will declare a local variable of same name as the local attribute of your function, assigning it an empty list, so you're attempting to divide your sum by zero ^^ > on the other hand, you try to store the sum inside an uundeclared 'total' variable (since there's no reason to use a global variable declared elsewhere) > at last, you call your function, but: - you doesn't return any value from the function - you doesn't store any eventual returning value from the function Fix of the code: function averageLst(nums) { var total = 0; // declare and initialize the total var for (var i = 0; i < nums.length; i++) { total += nums[i]; } return total / nums.length; // return the average value, avoiding use of another 'avg' local variable ;) } alert(averageLst([75, 60, 100, 90])); // returned value is send to alert box to be displayed to user ... obviously, you can store the returned value in a variable, for use it later: var avg = averageLst([75, 60, 100, 90]);
14th Jun 2017, 10:41 PM
visph
visph - avatar
+ 3
@washika put your 'total = 0' inside the function or the result will be wrong on more than one calling of it 🙂 var nums = [75, 60, 100, 90]; //first time... document.write(averagel_st(nums)+"<br/>"); //81.25 //second document.write(averagel_st(nums)); //oops! 162.5
15th Jun 2017, 5:52 AM
Phil Servis
Phil Servis - avatar
+ 3
[offtopic] I will never understand than later and less informative answer will get so much upvotes while sooner, more readable, adding clear explanations, and the best marked one by asker will get so few (actually 8 against 26) ^^ @<^> washika D <^>: Nothing against you in particular, but this is totally absurd and unproductive as well as demotivating, so I cannot ever be silent about this kind of things :P [/offtopic]
20th Jun 2017, 6:19 AM
visph
visph - avatar