Categories
Modern JavaScript

Better JavaScript — Loops and Arrays

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at ways to improve our JavaScript code.

Don’t Modify an Object During Enumeration

We shouldn’t modify an object during enumeration.

The for-in loop isn’t required to keep current with object modifications.

So we may get items that are outdated in the loop.

This means that we should rely on the for-in loop to behave predictably if we change the object being modified.

So we shouldn’t have code like:

const dict = {
  james: 33,
  bob: 22,
  mary: 41
}

for (const name in dict) {
  delete dict.bob;
}

We have the dict object but we modified it within the for-in loop.

But the loop isn’t required to get the latest changes, so bob might still show up.

Prefer for-of Loops to for-in Loops for Array Iteration

The for-in loop isn’t meant to be used to iterate through arrays.

The order is unpredictable and we get the keys of the item instead of the item itself.

So if we have something like:

const scores = [4, 4, 5, 7, 7, 3, 6, 6];
let total = 0;
for (const score in scores) {
  total += score;
}
const mean = total / scores.length;

score would be the key of the array.

So we wouldn’t be adding up the scores.

Also, the key would be a string, so we would be concatenating the key strings instead of adding.

Instead, we should use the for-of loop to loop through an array.

For instance, we can write:

const scores = [4, 4, 5, 7, 7, 3, 6, 6];
let total = 0;
for (const score of scores) {
  total += score;
}
const mean = total / scores.length;

With the for-of loop, we get the entries of the array or any other iterable object so that we actually get the numbers.

Prefer Iteration Methods to Loops

We should use array methods for manipulating array entries instead of loops whenever possible.

For instance, we can use the map method to map entries to an array.

We can write:

const inputs = ['foo ', ' bar', 'baz ']
const trimmed = inputs.map((s) => {
  return s.trim();
});

We called map with a callback to trim the whitespace from each string.

This is much shorter than using a loop like:

const inputs = ['foo ', ' bar', 'baz ']
const trimmed = [];
for (const s of inputs) {
  trimmed.push(s.trim());
}

We have to write more lines of code to do the trimming and push it to the trimmed array.

There’re many other methods like filter , reduce , reduceRight , some , every , etc. that we can use to simplify our code.

Conclusion

We shouldn’t modify objects during enumeration.

Also, we should prefer iteration methods to loops.

The for-of is better than the for-in loop for iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *