How to Create Array from a for Loop with JavaScript?

Sometimes, we want to create an array from a for loop with JavaScript.

In this article, we’ll look at how to create an array from a for loop with JavaScript.

Create Array from a for Loop with JavaScript

To create an array from a for loop with JavaScript, we can use the JavaScript array push method to append the entries into the array within the loop body.

For instance, we can write:

const yearStart = 2000;
const yearEnd = 2040;
const arr = [];

for (let i = yearStart; i < yearEnd + 1; i++) {
  arr.push(i);
}

console.log(arr)

We set the yearStart and yearEnd variables to the start and end values of the for loop.

Then we loop from yearStart to yearEnd with the for loop with:

for (let i = yearStart; i < yearEnd + 1; i++)

Then in the loop body, we call arr.push with i to push i into the arr array.

Therefore, from the console log, we see that arr is:

[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040]

Conclusion

To create an array from a for loop with JavaScript, we can use the JavaScript array push method to append the entries into the array within the loop body.