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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...