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.
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com
My Github — https://github.com/ramu-narasinga
My website — https://ramunarasinga.com
My Youtube channel — https://www.youtube.com/@ramu-narasinga
Learning platform — https://thinkthroo.com
Codebase Architecture — https://app.thinkthroo.com/architecture
Best practices — https://app.thinkthroo.com/best-practices
Production-grade projects — https://app.thinkthroo.com/production-grade-projects