Function to compute sum of all array elements in JavaScript

Took 2 minutes and 33 seconds to code a method to compute the sum of all elements of the array in JavaScript. Here is the code snippet.

Code:

arr = [1, 2, 3, 4];
function arrSum(arr) {
sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}

document.write(arrSum(arr));

Result:

10

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...