 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding sum of alternative elements of the array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate and return the sum of alternative elements of the array.
For example −
If the input array is −
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be −
1 + 3 + 5 + 7 = 16
Example
Following is the code −
const arr = [1, 2, 3, 4, 5, 6, 7]; const alternativeSum = (arr = []) => {    let sum = 0;    for(let i = 0; i < arr.length; i++){       const el = arr[i];       if(i % 2 !== 0){          continue;       };       sum += el;    };    return sum; }; console.log(alternativeSum(arr));  Output
Following is the output on console −
16
Advertisements
 