
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Odd even index difference - JavaScript
We are required to write a JavaScript function that takes in an array of numbers like this −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8];
The function should return the difference between the sum of elements present at the odd index and the sum of elements present at even index
Example
Following is the code −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8]; const oddEvenDiff = arr => { let diff = 0; for(let i = 0; i < arr.length; i++){ if(i % 2 === 0){ diff += arr[i]; }else{ diff -= arr[i] }; }; return Math.abs(diff); }; console.log(oddEvenDiff(arr));
Output
This will produce the following output in console −
18
- Related Articles
- Find even odd index digit difference - JavaScript
- Even numbers at even index and odd numbers at odd index in C++
- Swapping even and odd index pairs internally in JavaScript
- Swap Even Index Elements And Odd Index Elements in Python
- Separate odd and even in JavaScript
- Even index sum in JavaScript
- Adding only odd or even numbers JavaScript
- Odd even sort in an array - JavaScript
- Sorting odd and even elements separately JavaScript
- Difference between sums of odd and even digits.
- JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
- Matching odd even indices with values in JavaScript
- How to multiply odd index values JavaScript
- Rearrange array such that even index elements are smaller and odd index elements are greater in C++
- Add class (odd and even) in HTML via JavaScript?

Advertisements