I am wondering if JavaScript has an enhanced for loop syntax that allows you to iterate over arrays. For example, in Java, you can simply do the following:
String[] array = "hello there my friend".split(" ");
for (String s : array){
System.out.println(s);
}
output is:
hello
there
my
friend
Is there a way to do this in JavaScript? Or do I have to use array.length and use standard for loop syntax as below?
var array = "hello there my friend".split(" ");
for (i=0;i<array.length;i++){
document.write(array[i]);
}
JavaScript has a
foreach-style loop (for (x in a)), but it is extremely bad coding practice to use it on anArray. Basically, thearray.lengthapproach is correct. There is also aa.forEach(fn)method in newer JavaScripts you can use, but it is not guaranteed to be present in all browsers – and it’s slower than thearray.lengthway.EDIT 2017: "We’ll see how it goes", indeed. In most engines now,
.forEach()is now as fast or faster thanfor(;;), as long as the function is inline, i.e.arr.forEach(function() { ... })is fast,foo = function() { ... }; arr.forEach(foo)might not be. One might think that the two should be identical, but the first is easier for the compiler to optimise than the second.Belated EDIT 2020: There is now
for (const item of iterable), which solves the downsides of usingfor (item in iterable).