3 ms·
one thing to note: for (key in obj) // do It’s better to use the first method below (when initializing): obj = Object.create(null) obj = {} So you don
by sbr464 7y ago
one thing to note:
for (key in obj) // do
It’s better to use the first method below (when initializing):
obj = Object.create(null)
obj = {}
So you don’t inherit random keys from the chain, unless you intend to. Or use:
Object.keys(obj).forEach(k
Which doesn’t have this issue like the for-in loop version does.
- snek 7y agoobj = Object.create(null) obj = {} is exactly the same as obj = {} I would also do `Object.keys().forEach()`.
- sbr464 7y agoIt’s not. The null version won’t have methods like hasOwnProperty etc. If it wasn’t clear, i was mentioning 2 ways of initializing, not that you should reassign immediately.
- sbr464 7y agoI see a lot of people accessing a map/dictionary using the “for (key in)” pattern, not realizing they are inheriting any method/prototype names along with their basic dictionary they’ve defined. Using Object.create(null) is an easy way to not only save memory, but reduce issues if using dynamic key names. https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea/500531#500531 https://stackoverflow.com/questions/500504/why-is-using-for-...
- lilyball 7y agoNot particularly relevant here; the for-in loop here was operating on the `env` object, which holds all the keys directly. The prototype access was via the expression `options.env`, not the for loop.