-1

In pure JavaScript is it possible to create a loop in the form of

for item in array
{
  alert(item)
  // do stuff
}

instead of

for (var i = 0;  i < array.length; i++)
{
  alert(array[i])
  // do stuff
}
Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47

1 Answers1

2

One option would be to use a let...of loop

for (let item of array) {
  alert(item);
}

Another option would be to use a forEach loop

array.forEach(function(item){
   alert(item);
});

You can find more information here.

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • 3
    Should you not mark it as duplicate instead? This is very basic question. – Rajesh Dec 19 '16 at 14:00
  • I will do! @Rajesh i have never really marked a question as a duplicate before! will do it now :-) – Paul Fitzgerald Dec 19 '16 at 14:02
  • @Rajesh someone else has already done so! :-) – Paul Fitzgerald Dec 19 '16 at 14:02
  • 1
    Point is this is our portal and its our responsibility to keep it clean. Marking answer as duplicate will make sure, someone searching for such query gets enough information. For example, there is `for...of` that is more suited for this question but since it is not described here, people will not know about it. Also there are many details that could help if you mark duplicate and also keep one collective post. So please next time if you see such basic question, do mark it duplicate. :-) – Rajesh Dec 19 '16 at 14:07
  • @Rajesh will do! thanks! – Paul Fitzgerald Dec 19 '16 at 14:12