3 ms·
JavaScript's for in/of were not intended to be like that. `in` is broken so in a world without backwards compatibility to worry about they would have just fixed
by IshKebab 4y ago
JavaScript's for in/of were not intended to be like that. `in` is broken so in a world without backwards compatibility to worry about they would have just fixed it to have the behaviour of `of`. But because they had to consider backwards compatibility they had to come up with a new name.
You should basically never use `for in`. I guess part of the problem is that making that clear in most languages is easy - just add a compiler warning. But JavaScript requires users to manually set up and configure ESLint and if you know how to do that you probably already know not to use `for in` anyway.
I guess modern runtimes like Deno might help here.
- rascul 4y agoWhat is broken about for in? A quick search didn't turn up anything for me. I don't write much Javascript but for the times I do this seems like it could be useful information for me.
- layer8 4y agoYou need to up your Google-foo. E.g.: https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea https://stackoverflow.com/questions/500504/why-is-using-for-...
- pavlov 4y agoThat talks about using for…in with arrays, but not plain objects. IMO it’s fine for iterating over object keys. Sure, there are bizarre ways to make your objects go nuts in JavaScript through prototypal inheritance, but if you’re doing that then for…in is not your biggest problem.
- IshKebab 4y agoYou shouldn't normally need to iterate over object keys. Doing so is a pretty big indication of bad design. If you do you should use `Object.entries()` which avoids enumerating properties in the prototype chain. There's really no reason at all to use for-in and its use is usually a mistake.