5

How to loop through a fixed (development time) list of values in JavaScript?

In Perl, I'd do:

for my $item ('foo', 'bar', 'baz') {

which would run the loop with foo, bar and baz in $item (one each loop run).

JavaScript could do:

for (item in new Array('foo', 'bar', 'baz')) {

but that would make item contain 0, 1 and 2, not the values.

Copy&paste the source for each item would be an option, but a very bad one in terms of maintenance.

Another option would be

var items = new Array('foo', 'bar', 'baz');
for (i in items) {
    var item = items[i];

But that's also bad code as it defines a structure (Array) with lots of overhead where none is needed.

2
  • Use for (item of ...) instead: for...of Commented May 1, 2019 at 16:31
  • what is the expected output? Commented May 1, 2019 at 16:34

2 Answers 2

6

Instead of using i in items use let i of items, this is because in gets attribute names, but of actually iterates through the array properly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I assumed it to be that easy but didn't find anything on the web.
3

A good option is to use the forEach like:

['foo', 'bar', 'baz'].forEach(function(item){ console.log(item); })

for loops only work well with object object

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.