Embed presentation
Download to read offline
![Write a function in javascript that calculates the average element in a non-empty list.
Solution
function average(array)
{
var sum = 0;
for( var i = 0; i < array.length; i++ ){
sum += parseInt( array[i]); //don't forget to add the base
}
var avg = sum/array.length;
window.alert( "The average of all the elements is: " + avg);
}](https://image.slidesharecdn.com/writeafunctioninjavascriptthatcalculatestheaverageelementi-230703042120-8af2eb54/75/Write-a-function-in-javascript-that-calculates-the-average-element-i-pdf-1-2048.jpg)
The document describes a JavaScript function named 'average' that calculates the average of elements in a non-empty array. It sums the elements after parsing them to integers and then divides the sum by the number of elements to compute the average. Finally, it alerts the user with the calculated average.
![Write a function in javascript that calculates the average element in a non-empty list.
Solution
function average(array)
{
var sum = 0;
for( var i = 0; i < array.length; i++ ){
sum += parseInt( array[i]); //don't forget to add the base
}
var avg = sum/array.length;
window.alert( "The average of all the elements is: " + avg);
}](https://image.slidesharecdn.com/writeafunctioninjavascriptthatcalculatestheaverageelementi-230703042120-8af2eb54/75/Write-a-function-in-javascript-that-calculates-the-average-element-i-pdf-1-2048.jpg)