This a bit playing with words, but if your array is actually only made of consecutive integers starting from 0
to m
or more generally from n
to m
with a constant common difference d
(or step if you prefer), you can do something which is both better and faster ;)
In the case you described
var n = 1;
var m = 5; // (the length of your array)
var d = 1; // you increment with for each element
// n m and d describe [1,2,3,4,5]
var sum = ((m * (m + 1) / 2) - ((n - 1) * n / 2)) * d;
No looping needed, but this works only with matching problems for arithmetic progression
Joke aside, looping is generally a good thing, as long as you don't nest too much of them depending on the same variables boundaries.