Lessons from open-source: How to create an array containing 0..N using Array.from?
Ramu Narasinga
Posted on March 19, 2024
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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Posted on March 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 19, 2024
March 14, 2024
March 11, 2024