Function to add and subtract alternate array elements in JavaScript

Took 5 minutes and 10 seconds to code JavaScript method to add and subtract alternate elements in an array. Here is the code snippet.

Code:

arr = [1,2,3,4,5,6,7];
function alternateAddSubtract(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
sum += arr[i];
} else {
sum -= arr[i];
}
}
return sum;
}

document.write(alternateAddSubtract(arr));

Result:

4

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 ...