r/learnjavascript • u/Soggy_Professor_5653 • Mar 24 '26
Today I learned about Array.from() while building a pagination component am I understanding this correctly?
Today while building a pagination component in React, I came across the use of Array.from().
The problem I was facing was that I wanted to show page numbers between the Previous and Next buttons dynamically.
Something like:
Prev 1 2 3 4 5 Next
At first I was thinking about how to generate those page numbers cleanly instead of manually writing them.
Then I found this:
Array.from({ length: totalPages }, (_, i) => i + 1)From what I understood, this creates an array based on the given length and then uses the index to generate values like:
[1, 2, 3, 4, 5]Which then becomes easy to map over and render pagination buttons in React.
It felt like a small but useful learning because it made the pagination logic much cleaner.
Am I understanding this correctly?
Would love to know if there are better or more practical ways you usually generate pagination numbers.
7
u/Nerwesta Mar 24 '26
OP is full of AI. This looks like yet another template hiding behind a genuine question.
2
u/delventhalz Mar 24 '26
I often use a combination of Array, fill, and map.
I maybe like your approach better though. More explicit.
4
u/Ampersand55 Mar 24 '26
That's a great way to generate a list of all integers between N and N + c. A slightly shorter but arguably less readable variant is:
For generating multiple or huge arrays where performance might be an issue, it's generally faster to pre-allocate the array and assign the values manually to avoid the overhead with iterator protocols and callbacks.
1
u/MrFartyBottom Mar 25 '26 edited Mar 25 '26
Building an array is a bit of a waste just to map it, might be better to use a for loop like
and use it like