Ad

Using default params and arrow functions

Code
Diff
  • /* Array.reduce(
     * (accumulator, currentValue, currentIndex, array) => {
     * return accumulator + currentValue;
     * },
     * initialValue
     * );
     */
    const sumOfElements = (arr=[]) => arr.reduce((sum, currentValue) => sum + currentValue,0)
    • /* Array.reduce(
    • * (accumulator, currentValue, currentIndex, array) => {
    • * return accumulator + currentValue;
    • * },
    • * initialValue
    • * );
    • */
    • function sumOfElements(arr) {
    • return (arr||[]).reduce((sum, currentValue) => sum + currentValue,0);
    • }
    • // Using ES6 Arrow Functions
    • sumOfElements = arr => (arr||[]).reduce((sum, currentValue) => sum + currentValue,0)
    • const sumOfElements = (arr=[]) => arr.reduce((sum, currentValue) => sum + currentValue,0)