Array in Code

Trying to use an array in my code. Where am I going wrong?

var Rsum = new Array(5);
var Rsum[1] = 6;
var Rsum[2] = 4;
var Rsum[3] = 7;
var Rsum[4] = 2;
var Rsum[5] = 8;
for (i = 1; i <= 5; i++){
     R = R + Rsum[i];
}//next i

We can use JSHint to easily find out what’s wrong with the code.

What’s going wrong is that var is inappropriately being used. It’s used to declare a new variable, not when adding an item to an array.
Also, the R and i variables aren’t defined.


var Rsum = new Array(5);
var sum = 0;
var i;
Rsum[1] = 6;
Rsum[2] = 4;
Rsum[3] = 7;
Rsum[4] = 2;
Rsum[5] = 8;
for (i = 1; i <= 5; i++) {
    sum = sum + Rsum[i];
}

That fixes up the issues that JSHint cares about, so now we can move on to fixing more subtle issues.

The variable names aren’t all that meaningful as they currently are so I suggest that we instead of Rsum and R, we use more meaningful variable names, such as numbersToAdd and sum instead. They also shouldn’t begin with an uppercase letter, as that is normally reserved for constructor functions.


// an example constructor
function Person(name) {
    this.name = name;
    this.legs = 2;
}
var person = new Person('Pete');

That new Array() is also an old notation and has now been replaced by just using [] instead.
So this is how the code looks after the first set of fixes.


var numbersToAdd = [5];
var sum = 0;
var i;
numbersToAdd[1] = 6;
numbersToAdd[2] = 4;
numbersToAdd[3] = 7;
numbersToAdd[4] = 2;
numbersToAdd[5] = 8;
for (i = 1; i <= 5; i++) {
    sum = sum + numbersToAdd[i];
}

We shouldn’t use multiple var statements in the same section of code, because that tempts us to inappropriate use them separately in different places, so we should declare variables in one comma-separated var statement instead.

That original new Array(5) as well as [5] doesn’t declare an array of size five, but instead declares an array and puts the number 5 in to the first index, at index 0. We can assign those other array values from there too, and because arrays start their numbering from 0, that is where we should do our looping from too, by starting at 0 and looping while i is less than the length of the array.

And as a final touch, I prefer instead of ++ to use +=1 because it’s more expressive about what it does, and is easier to modify later on too.


var numbersToAdd = [6, 4, 7, 2, 8],
    sum = 0,
    i;
for (i = 0; i < numbersToAdd.length; i += 1) {
    sum = sum + numbersToAdd[i];
}

That code is now looking really good.