I have to create and array given a number (n). The array will have all the numbers up to and including that number, but excluding zero. I wrote the following code
function upTonArr(n) {
for (var i = 0, monkeys = []; i <= n; monkeys.push(++i));
return monkeys;
}
but had to change it for i < n in order for the test to pass.
Can someone please tell me why if "n" needs to be included in the array the notation does not require i to be <=n?
Thanks in advance.
You are using a prefix operator (++i). What that does is it increments the variable before fetching it. On the first run, the value is 0, but because of the prefix operator, 1 gets pushed to the array. If you had i <= n, it would be pushing (n + 1) as the last value to the array.
The other version, the postfix operator (i++), will first fetch the variable and then increment it after accessing it, so 0 would be pushed to the array on the first run.