Lessons from open-source: How to create an array containing 0..N using Array.from?

Lessons from open-source: How to create an array containing 0..N using Array.from?

This lesson is picked from Next.js source code. In this article you will learn how to create an array containing 0 to n using Array.from.

Array.from

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object. — MDN Docs

In the MDN Docs, I could not find any example using an object with length property

Array.from({ length: n + 1 }, (_, i) => i)

Practice the exercises based on documentation to become an expert in Next.js

Stackoverflow results:

I searched on the internet and found this stack overflow answer.

The third way is a modified version to create an array that contains 1..n. The only difference is i+1.

Github results:

Github search results made me realise the importance of data structures and algorithms.

I have seen this code snippet used in repositories containing “Algorithm” name.

Conclusion:

There is a strong correlation between quality code and utilising the right data structures and algorithms. I have seen Depth First Search implementation in next.js source code and some exceptional usage of data structures to handle cache using weakmap. Yea, do not use for loop to create an array containing 0..n. Use Array.from. Take your coding skills to next level.