This is how JsFromHell defines a function to find sum of a numeric array (http://jsfromhell.com/array/sum)
sum = function(o){
for(var s = 0, i = o.length; i; s += o[--i]);
return s;
};
//sum([1, 2, 3, 4, 5, 6, 7, 8, 9])
Can someone explain what’s happening within second part of the for loop? What’s the meaning of “i;”? It appears like its same as i >= 0. But that returns a NaN.
JavaScript has various ways of coercing non-Boolean values to
trueorfalse. One of them has to do with numbers: zero isfalse, any other number istrue.For strings, an empty string is
false, others aretrue. Thenullvalue is coerced tofalse, as is the somewhat zen-like “undefined” non-value.You could write that code:
and it might be even more efficient. (Or it might not be; it’s the kind of micro-optimization that only library maintainers should worry about, since next week the browser vendors may rev their interpreters and flip the situation on its head.)
Finally, if you’re getting a
NaN, it means that you don’t really have an array of numbers. If there’s a single thing in the array that can’t cleanly be converted to a numeric value in the third part of the “for” loop, you’ll get aNaNresult. edit — oh wait, I see; you triedi >= 0and noti > 0. That means the loop will try to accesso[-1]which is undefined. That’ll give you aNaNwhen you try to convert it to a number.