HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Refactoring your for...in loops to avoid ESLint warnings

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptloopsyourrefactoringavoidwarningseslintfor

Problem

ESLint is one of my tools of choice, but oftentimes it gets in the way of work, due to the way it prefers me to do things. One of the warnings I have seen more times than I care to admit is the following:
> for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.eslint(no-restricted-syntax)
@Quick refresher
Let's look at three refactoring options to deal with it and avoid the warning!
Object.keys() has the exact same behavior as a for...in loop, so it can be used as a drop-in replacement:

Solution

const data = [3, 4];
// Same as for (let k in data) console.log(k)
Object.keys(data).forEach(k => console.log(k));
// 0 1


@Quick refresher
Let's look at three refactoring options to deal with it and avoid the warning!
Object.keys() has the exact same behavior as a for...in loop, so it can be used as a drop-in replacement:
Object.values() is very similar to Object.keys(), but returns the values instead of the keys, which might be what you are really using the keys for:
Finally, if you need both key and value, Object.entries() has you covered:

Code Snippets

const data = [3, 4];
// Same as for (let k in data) console.log(k)
Object.keys(data).forEach(k => console.log(k));
// 0 1
const data = [3, 4];
// Iterate over the values
Object.values(data).forEach(v => console.log(v));
// 3 4
const data = [3, 4];
// Iterate over the data, returning key-value pairs
Object.entries(data).forEach(e => console.log(e[0], e[1]));
// [0, 3] [1, 4]

Context

From 30-seconds-of-code: eslint-refactor-for-in

Revisions (0)

No revisions yet.