Search code examples
javascriptarrays

what is the wrong with this javascript function?


I want to know what is wrong with this function that takes array and sums up it's elements

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = 0;
var arraySum = function() {
  for (var i = 0; i <= arr.length; i++) {
    sum += arr[i];
  }
  console.log(sum);
};
arraySum(arr);


Solution

  • You are trying to access an element outside of the array, this returns undefined.

    for (var i = 0 ; i<= arr.length ; i++) {
    //                 ^ the equal sign
    

    replace it with

    for (var i = 0 ; i< arr.length ; i++) {
    

    var arr = [1,2,3,4,5,6,7,8,9,10];
    var sum = 0;
    var arraySum = function () {
        for (var i = 0; i< arr.length; i++) {
            sum += arr[i];
        }
    };
    
    arraySum(arr);
    document.write(sum);