I’m a newbie and struggling…
Can anyone tell me what’s wrong with my code?

``````var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(i+1);
console.log(sliced);
}
``````

the log shows: [“one”, “two”, “three”], [], [], [].
but what I mean to do, is to get: [“one”, “two”, “three”], [“two”, “three”], [“three”], [].

Why my code not work? And how should I code? Thanks a lot.

I am not super well versed in the nuances of “for…in” syntax vs a traditional for loop, but I believe the problem is arising from the fact that “for…in” syntax “iterates over the enumerable properties of an object, in arbitrary order.” In other words, by using “for…in,” your code is being applied to every element in the array, but not necessarily in sequential order. Your desired result depends on ordered iteration, which a traditional for-loop provides via its built-in incrementation. The following should do what you want:

``````var a = ["zero", "one", "two", "three"];
for (var i = 0; i < a.length; i++) {
var sliced = a.slice(i+1);
console.log(sliced);
}
``````

For more info on “for…in” syntax, check out the MDN entry linked above, as well as this StackOverflow answer on the potential dangers of using “for…in” when trying to iterate over an array (as a relative newbie myself, some of the finer points of the StackOverflow answers went over my head, but it was interesting nonetheless).

`i` in your `for` loop is a string, you can see it by adding
`console.log(typeof i);`

So `(i+1)` will give you `01, 11, 21, 31`;

To make your code work you need `i` to be number. Simplest way:
`var sliced = a.slice(+i+1);`

1 Like

Declaring a variable inside a loop is not a best practice

why do you say that wilfred?

Because it messes with garbage collection - creates pointers that won’t be reused over time and have to be garbage collected.

cool but why should I care about garbage collection? I like putting variables in my loops because it keeps that variable safe from being touched on accident.

Keeping your variable declared using “var” inside a loop doesn’t protect it from anything at all. That’s the problem.

if you use ‘let’ it will be safe, but using ‘var’ it wont be safe whether it goes in the loop or not.

Man, grab eslint, setup few common rulesets, and you’ll realize how much you can learn from that.
Actually memory leaks in JavaScript are real and much more common than you think…

Both `let` and `var` create the same pointers, the only difference is visibility scope and that’s pretty much it.
If you really care about your vars go for `_.map()` `_.forEach()` lodash methods and use `const` instead.