using es6 array functions and arrow operator - Javascript Function

Javascript examples for Function:Arrow Function

Description

using es6 array functions and arrow operator

Demo Code

// 7./*from w w  w .j  a v a  2 s . c om*/
// The old way (using loop & Vanilla JS)
function sumOfArrayVanilla(array) {
    let sum = 0;
    for (let i = 0; i < array.length; i++) {
        sum += array[i];
    }
    return sum;
}

// The smart way (using es6 array functions)
let sumOfArray = array => array.reduce((acc, val) => acc + val, 0);

let array = [0, 1, 2, 3, 4, 5];
console.log(`Using the OLD way: ${sumOfArrayVanilla(array)}`);
console.log(`Using the GOOD way: ${sumOfArray(array)}`);

Related Tutorials