Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to produce null in accessing array function in javascript

function average(arr){
    if (arr.length === 0) return null;

    let total = 0;
    arr.forEach(function(item){
        total += item;
    })
    return total / arr.length;
}

// using array.reduce() which makes more sense here
function average2(arr){
    if (arr.length === 0) return null;

    const total = arr.reduce(function(prev,next){
      return prev + next;
    });
    return total / arr.length;
}

console.log(average([]));
console.log(average([1,2,3]));

console.log(average2([]));
console.log(average2([1,2,3]));
 Run code snippet
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #produce #null #accessing #array #function #javascript
ADD COMMENT
Topic
Name
8+2 =