logo

The next-generation blog, news, and article for you to start sharing your stories today!

Sum of array in javascript without loop

Threre are mostly many way to find sum of  all int element of the array in javascript. we will basically use two ways.

1. Sum of array using for loop

let considered you have an array in javascript

let a = [10, 20, -30, 5, 7]

let total = 0;

for (const ele of a) {  // where a is [10, 20, -30, 5, 7]
	total += ele
}

// total will be 12

2. Sum of array without for loop in javascript

Now in this case we will use reduce function which is introduce in es6

let a = [10, 20, -30, 5, 7]

let sum = a.reduce((a, b) =>  a + b , 0)

// example like this

reduce((previousValue, currentValue) => { /* ... */ } )

For more details about javascript reduce function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 

Thank you. Please contact me in case of any query.

avatar

Vikram Parihar

An editor at Keyscript

Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.