Categories
JavaScript Answers

How to dynamically creating variables in for loops with JavaScript?

Spread the love

Sometimes, we want to dynamically creating variables in for loops with JavaScript.

In this article, we’ll look at how to dynamically creating variables in for loops with JavaScript.

How to dynamically creating variables in for loops with JavaScript?

To dynamically creating variables in for loops with JavaScript, we use an array.

For instance, we write

const createVariables = () => {
  const accounts = [];
  for (let i = 0; i <= 20; ++i) {
    accounts[i] = "whatever";
  }
  return accounts;
};

to define the createVariables function.

In it, we loop from i between 0 to 20.

And we use i as the index of the entry we want to put into accounts.

Conclusion

To dynamically creating variables in for loops with JavaScript, we use an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *