sum array without loop javascript

Sum Array without Loop in Javascript

Summing up the elements of an array without using a loop is a common problem in Javascript. Fortunately, there are several ways to do it.

Method 1: Using reduce()

The reduce() method is used to reduce the elements of an array to a single value. In this case, we can use it to sum up the elements of an array without a loop.


const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((a, b) => a + b, 0);
console.log(sum); // outputs 15

In the code above, we first declare an array arr containing 5 elements. We then use the reduce() method on the array, passing in a callback function that takes two parameters (a and b) and returns their sum. The second parameter of reduce() is the initial value of the accumulator, which is set to 0. The sum is then logged to the console.

Method 2: Using eval()

The eval() function evaluates a string as Javascript code. This can be used to sum up the elements of an array without a loop.


const arr = [1, 2, 3, 4, 5];
const sum = eval(arr.join('+'));
console.log(sum); // outputs 15

In the code above, we first declare an array arr containing 5 elements. We then join the elements of the array with the + operator using the join() method. The resulting string is evaluated as Javascript code using the eval() function, and the sum is assigned to the sum variable. The sum is then logged to the console.

Method 3: Using forEach()

The forEach() method executes a provided function once for each array element. This can be used to sum up the elements of an array without a loop.


const arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach(num => sum += num);
console.log(sum); // outputs 15

In the code above, we first declare an array arr containing 5 elements. We then declare a variable sum and initialize it to 0. We then use the forEach() method on the array, passing in a callback function that takes one parameter (num) and adds it to the sum variable. The sum is then logged to the console.

Conclusion

In conclusion, there are several ways to sum up the elements of an array without a loop in Javascript. The most efficient method is probably to use the reduce() method, but the eval() function and the forEach() method are also viable options.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe