In Java you can use a for
loop to traverse objects in an array as follows:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
// Do something
}
Can you do the same in JavaScript?
In Java you can use a for
loop to traverse objects in an array as follows:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
// Do something
}
Can you do the same in JavaScript?
There are various way to loop through array in JavaScript.
Generic loop:
ES5's forEach:
jQuery.each:
Have a look this for detailed information or you can also check MDN for looping through an array in JavaScript & using jQuery check jQuery for each.
If anybody is interested in the performance side of the multiple mechanisms available for Array iterations , i've prepared the following JSPerf tests:
https://jsperf.com/fastest-array-iterator
Results :
The traditional
for()
iterator, is by far the fastest method, specially when used with the array length cached.The
Array.prototype.forEach()
and theArray.prototype.map()
methods are the slowest approximations, probably as a consequence of the function call overheadIntro
Since my time in college, I've programmed in Java, JavaScript, Pascal, ABAP, PHP, Progress 4GL, C/C++ and possibly a few other languages I can't think of right now.
While they all have their own linguistic idiosyncrasies, each of these languages share many of the same basic concepts. Such concepts include procedures / functions,
IF
-statements,FOR
-loops, andWHILE
-loops.A traditional
for
-loopA traditional
for
loop has three components:These three components are separated from each other by a
;
symbol. Content for each of these three components is optional, which means that the following is the most minimalfor
loop possible:Of course, you will need to include an
if(condition === true) { break; }
or anif(condition === true) { return; }
somewhere inside thatfor
-loop to get it to stop running.Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index:
Using a traditional
for
loop to loop through an arrayThe traditional way to loop through an array, is this:
Or, if you prefer to loop backwards, you do this:
There are, however, many variations possible, like for example this one:
... or this one ...
... or this one:
Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.
Note that each of these variations is supported by all browsers, including very very old ones!
A
while
loopOne alternative to a
for
loop is awhile
loop. To loop through an array, you could do this:Like traditional
for
loops,while
loops are supported by even the oldest of browsers.Also, note that every while loop can be rewritten as a
for
loop. For example, thewhile
loop hereabove behaves the exact same way as thisfor
-loop:For...in
andfor...of
In JavaScript, you can also do this:
This should be used with care, however, as it doesn't behave the same as a traditional
for
loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.As an alternative to
for...in
, there's now also forfor...of
. The following example shows the difference between afor...of
loop and afor...in
loop:Additionally, you need to consider that no version of Internet Explorer supports
for...of
(Edge 12+ does) and thatfor...in
requires at least Internet Explorer 10.Array.prototype.forEach()
An alternative to
for
-loops isArray.prototype.forEach()
, which uses the following syntax:Array.prototype.forEach()
is supported by all modern browsers, as well as Internet Explorer 9 and later.Libraries
Finally, many utility libraries also have their own
foreach
variation. AFAIK, the three most popular ones are these:jQuery.each()
, in jQuery:_.each()
, in Underscore.js:_.forEach()
, in Lodash.js:Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
3. Transform to a new array
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
5. Create a new array based on the original but without modifying it
6. Count the number of each category
7. Retrieve a subset of an array based on particular criteria
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
9. Find an element in an array
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
The best way in my opinion is to use the Array.forEach function. If you cannot use that I would suggest to get the polyfill from MDN to make i available, it is certainly the safest way to iterate over an array in JavaScript.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
So as others has suggested, this is almost always what you want:
This ensures that anything you need in the scope of processing the array stays within that scope, and that you are only processing the values of the array, not the object properties and other members, which is what for .. in does.
using a regular c style for loop works in most cases, it is just important to remember that everything within the loop shares it's scope with the rest of your program, the { } does not create a new scope.
Hence:
will output "11" - which may or may not be what you want.
Working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
Yes, you can do the same in JavaScript using loop, but not limited to that, many ways to do loop over arrays in JavaScrip, imagine you have this array below and you'd like to do a loop over it:
These are the solutions:
1) For loop
For loop is a common way looping through arrays in JavaScript, but no considered as the fastest solutions for large arrays:
2) While loop
While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:
3) Do while
Do while doing the same thing as while with some syntax difference as below:
These are the main ways to do javascript loops, but there are few more ways to do that.
Also we use
for in
loop for looping over objects in javascript.Also look at
map()
,filter()
,reduce()
etc functions on Array in JavaScript. They may do things much faster and better than usingwhile
andfor
.This is good article if you like to learn more about the async functions over arrays in JavaScript.
Read more>> here: