Question

I'm learning Javascript, and found this frustrating to understand.

Below are two functions that compute the sum of integers in a given array with one working solution and the other one working partially.

Here is my working function:

 var sum = function(array) {
        total = 0
        for (index in array) {
          total += array[index]
        }
        return total
    }

Here is the partially working function:

 var sum = function(array) {
        sum = 0
        for (index in array) {
          sum += array[index]
        }
        return sum
    }

You'll see that the point of difference is the variable name. I think I'm missing some fundamental understanding here, and would like some clarification.

Here are my test statements:

console.log(sum( [1, 2, 3, 4, 5, 5, 7] ) === 27)
console.log(sum( [1, 2, 3, 4, 5, 5, 7] ) === 27)

They are identical on purpose to show you the center of the issue.

For the working function, it returns true for both test statements.
For the partially working function, it returns true once followed by a TypeError: number is not a function

What is going on here?

Était-ce utile?

La solution 2

var sum = function(array) {
    var sum = 0; // Declare with var
    for (index in array) {
      sum += array[index];
    }
    return sum;
}

...will work. Just referencing sum causes the engine to look for a variable called sum firstly inside the function, and if not found there, it will traverse up the object's scope chain to find it. Declaring with var inside a function tells the engine that this is a new variable with its scope restricted to the direct parent object, in this case, the function.

Autres conseils

 var sum = function(array) {
    sum = 0

sum is now a number, not a function.

You are overwriting your sum variable...

var sum = function(array) {
        sum = 0 // <-- doh!
        for (index in array) {
          sum += array[index]
        }
        return sum
    }

Make it clear to the interpreter that your inner variable is local... or give it a unique name, which also prevents confusion.

var sum = function(array) {
    var sum = 0;
    for (index in array) {
      sum += array[index];
    }
    return sum;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top