Home > OS >  Javascript array.length returning double the value it's supposed to return. Why?
Javascript array.length returning double the value it's supposed to return. Why?

Time:01-31

So, I'm learning Javascript through a book and it has some exercises. One of the exercises asks for you to build two functions, one that creates an array from two numbers provided in the arguments, and the other function has to sum all the numbers in the array. Here's my code:

let beg = 1;
let end = 3;
array = [];
sumNum = 0;

function range(begg, endd) {
    for (let count = begg; count <= endd; count  ) {
        array.push(count);
    }
    return array;
}

console.log(range(beg, end));

function sum(arrayy) {
    for (let i = 0; i <= arrayy.length - 1; i  ) {
        sumNum = arrayy[i]   sumNum;
        console.log(sumNum);
        
    }
    console.log("\n")
    console.log(arrayy.length - 1);
    return sumNum / 2;
}

console.log(sum(range(beg, end)));

array2 = [1, 2, 3];
console.log("\n");
console.log(array2.length);

As I was solving the exercise I kept getting double the sum of all the numbers in the array. I started to print some information and discovered that my arrayy.length is returning double the value it's supposed to return and the loop runs double the times it should run.

Here's my output:

[ 1, 2, 3 ]
1
3
6
7
9
12


5
6


3

Sorry it this is a noob question, but my curiosity is killing me and I have not found anything on the internet, so why am I getting this result? Thanks in advance.

CodePudding user response:

As Ivan said: The "array" variable is global, so each time you call the range function you keep appending items to that shared array. You should add the array inside your function and return it. Other than that you did a pretty nice job!

function range(begg, endd) {    
    array = []
    for (let count = begg; count <= endd; count  ) {
        array.push(count);
    }
    return array;
}

Also: The sum function should have the "sumnum" variable inside the function to prevent it from increasing every time you call the function:

function sum(arrayy) {
    sumnum = 0;
    for (let i = 0; i <= arrayy.length - 1; i  ) {
        sumNum = arrayy[i]   sumNum;
        console.log(sumNum);
    }
    console.log("\n");
    console.log(arrayy.length - 1);
    return sumNum / 2;
}

remove the array and sumnum variables from the top of your code to get rid of the global variables.

  • Related