This page looks best with JavaScript enabled

Use homogenous arrays to maintain sanity

 ·   ·  ☕ 1 min read

Use values with same types in any array. Changing types (even for scenarios that you think are totally valid for the day) can rain down hell.

Homogeneity of an array refers to using the same types of variables within an array.

The following arrays are homogenous -

1
2
3
4
const fruits = ['apple', 'orange];
const nums = [0,1,2]
const answers= [true, false];

The following arrays are not -

1
2
const planets = [earth, 3];
const answers = [true, 42];

You may think you have good reasons to include multiple types. For example group together different attributes of earth -

1
const earth = ["earth", 3, true];

Arrays are highly ‘iterable’, and when you iterate you take an element and do something. You cannot do that “something” consistently when you use different types. It can lead to unexpected results, errors and frustrations.

For e.g.:

1
2
3
const earth = ["earth", 3, true];
[...earth].map(val => val.toUpperCase());
// TypeError: val.toUpperCase is not a function

What should you do instead?

Use consistent types in an array.

If you want to group together stuff, do it in an object. Use arrays to store series of such objects.

1
2
const earth = { name: "earth", position: 3, life: true };
const planets = [earth];
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things