Loop through an array in JavaScript












2655















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?










share|improve this question




















  • 5





    Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

    – Mark Szymanski
    Jun 10 '10 at 0:15






  • 38





    no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

    – CMS
    Jun 10 '10 at 0:38






  • 2





    related - stackoverflow.com/questions/5349425/…

    – jondavidjohn
    Nov 1 '11 at 17:53











  • related - stackoverflow.com/q/6208964/31671

    – alex
    Dec 18 '15 at 10:09






  • 6





    jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

    – EscapeNetscape
    Nov 3 '16 at 19:45
















2655















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?










share|improve this question




















  • 5





    Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

    – Mark Szymanski
    Jun 10 '10 at 0:15






  • 38





    no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

    – CMS
    Jun 10 '10 at 0:38






  • 2





    related - stackoverflow.com/questions/5349425/…

    – jondavidjohn
    Nov 1 '11 at 17:53











  • related - stackoverflow.com/q/6208964/31671

    – alex
    Dec 18 '15 at 10:09






  • 6





    jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

    – EscapeNetscape
    Nov 3 '16 at 19:45














2655












2655








2655


551






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?










share|improve this question
















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?







javascript arrays loops for-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 1 '18 at 10:17









John Slegers

28.3k13149132




28.3k13149132










asked Jun 10 '10 at 0:04









Mark SzymanskiMark Szymanski

20.3k206084




20.3k206084








  • 5





    Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

    – Mark Szymanski
    Jun 10 '10 at 0:15






  • 38





    no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

    – CMS
    Jun 10 '10 at 0:38






  • 2





    related - stackoverflow.com/questions/5349425/…

    – jondavidjohn
    Nov 1 '11 at 17:53











  • related - stackoverflow.com/q/6208964/31671

    – alex
    Dec 18 '15 at 10:09






  • 6





    jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

    – EscapeNetscape
    Nov 3 '16 at 19:45














  • 5





    Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

    – Mark Szymanski
    Jun 10 '10 at 0:15






  • 38





    no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

    – CMS
    Jun 10 '10 at 0:38






  • 2





    related - stackoverflow.com/questions/5349425/…

    – jondavidjohn
    Nov 1 '11 at 17:53











  • related - stackoverflow.com/q/6208964/31671

    – alex
    Dec 18 '15 at 10:09






  • 6





    jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

    – EscapeNetscape
    Nov 3 '16 at 19:45








5




5





Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

– Mark Szymanski
Jun 10 '10 at 0:15





Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct?

– Mark Szymanski
Jun 10 '10 at 0:15




38




38





no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

– CMS
Jun 10 '10 at 0:38





no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

– CMS
Jun 10 '10 at 0:38




2




2





related - stackoverflow.com/questions/5349425/…

– jondavidjohn
Nov 1 '11 at 17:53





related - stackoverflow.com/questions/5349425/…

– jondavidjohn
Nov 1 '11 at 17:53













related - stackoverflow.com/q/6208964/31671

– alex
Dec 18 '15 at 10:09





related - stackoverflow.com/q/6208964/31671

– alex
Dec 18 '15 at 10:09




6




6





jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

– EscapeNetscape
Nov 3 '16 at 19:45





jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

– EscapeNetscape
Nov 3 '16 at 19:45












39 Answers
39






active

oldest

votes













1 2
next












3270














Use a sequential for loop:






var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}





@zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.



It shouldn't be used for array-like objects because:




  • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.

  • Inherited properties are also enumerated.


The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.



For example:






Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
console.log(array[i]);
}





The above code will console "a", "b", "c" and "foo!".



That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).



The for-in statement as I said before is there to enumerate object properties, for example:






var obj = {
"a": 1,
"b": 2,
"c": 3
};

for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
console.log("prop: " + prop + " value: " + obj[prop])
}
}





In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.



I would recommend you to read the following article:




  • Enumeration VS Iteration






share|improve this answer





















  • 179





    Why the down-vote? for...in should be avoided for Array-like objects!

    – CMS
    Jun 10 '10 at 0:10






  • 16





    This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

    – OscarRyz
    Jun 10 '10 at 0:13






  • 14





    @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

    – Matthijs Wessels
    Aug 14 '12 at 16:41






  • 13





    @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

    – Phrogz
    Apr 27 '13 at 13:32






  • 5





    jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

    – Enrico
    Aug 7 '13 at 7:26



















999





+50









Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.



It works like this:



// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
// ... do something with s ...
}


Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const:



// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here


Some JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.



If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:



var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) {
// ... do something with s ...
} );


But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:



var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
if (i in myStringArray) {
s = myStringArray[i];
// ... do something with s ...
}
}


Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.



You will often see the length caching done in the loop initialization clause, like this:



var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {


The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.






share|improve this answer





















  • 21





    Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

    – Phrogz
    Jun 4 '12 at 16:29






  • 2





    @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

    – Denis V
    Nov 28 '13 at 21:08






  • 2





    @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

    – Mark Reed
    Nov 29 '13 at 13:34








  • 1





    I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

    – Mark Reed
    Nov 30 '13 at 1:14








  • 2





    @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

    – Mark Reed
    Jan 14 '14 at 15:40



















415














You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.



[1,2,3,4].map( function(item) {
alert(item);
})


The general syntax is:



array.map(func)


In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.



The return value of array.map is another array, so you can use it like this:



var x = [1,2,3,4].map( function(item) {return item * 10;});


And now x is [10,20,30,40].



You don't have to write the function inline. It could be a separate function.



var item_processor = function(item) {
// Do something complicated to an item
}

new_list = my_list.map(item_processor);


which would be sort-of equivalent to:



 for (item in my_list) {item_processor(item);}


Except you don't get the new_list.






share|improve this answer





















  • 7





    No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

    – hasen
    Jun 10 '10 at 0:14






  • 91





    That particular example is probably better implemented using Array.forEach. map is for generating a new array.

    – harto
    Jun 10 '10 at 0:20






  • 21





    @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

    – CMS
    Jun 10 '10 at 0:30








  • 3





    The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

    – Mark Reed
    Sep 10 '14 at 17:00








  • 3





    Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

    – gengkev
    Apr 26 '16 at 23:47



















107














In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:



for(var i=0, len=myArray.length; i < len; i++){}


It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.






share|improve this answer





















  • 2





    myArray.forEach(function(obj) {}); is still the best

    – Jan Sverre
    Jan 2 '12 at 19:47











  • a tiny improvement: you could use ++i instead of i++

    – roberkules
    Apr 12 '12 at 14:58






  • 13





    ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

    – ngryman
    Apr 15 '12 at 0:45













  • @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

    – Jose
    May 8 '12 at 13:03






  • 5





    You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

    – Rui Marques
    Nov 30 '12 at 13:12





















101














for (var s of myStringArray) {



(Directly answering your question: now you can!)



Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.



This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.



It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.



It also works on Node (I tested it on version 0.12.0).



Iterating an array



// You could also use "let" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}


Iterating an array of objects



var band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];

for(var member of band){
console.log(member.firstName + ' ' + member.lastName);
}


Iterating a generator:



(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)



function* fibonacci() { // a generator function
let [prev, curr] = [1, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}

for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}




Compatibility table:
http://kangax.github.io/es5-compat-table/es6/#For..of loops



Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators



}






share|improve this answer


























  • If you're using ES6, I would suggest const s instead of var s

    – joeytwiddle
    Feb 10 '18 at 6:26



















84














Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.



You may not need all of them, but they can be very useful, or would be if every browser supported them.



Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.



filter returns an array of items that satisfy some condition or test.



every returns true if every array member passes the test.



some returns true if any pass the test.



forEach runs a function on each array member and doesn't return anything.



map is like forEach, but it returns an array of the results of the operation for each element.



These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.



Ignore it until you need it.



indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.



(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= , i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
}
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
while(i<L){
if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();





share|improve this answer





















  • 1





    Addition: IE supports forEach since version 9, see forEach Method MSDN

    – rwitzel
    Apr 17 '15 at 15:12





















62














Use the while loop...



var i=0, item, items = ['one','two','three'];
while(item = items[i++]){
console.log(item);
}


logs: 'one','two','three'



And for the reverse order, an even more efficient loop



var items = ['one','two','three'], i = items.length;
while(i--){
console.log(items[i]);
}


logs: 'three','two','one'



Or the classical for loop



var items = ['one','two','three']
for(var i=0, l = items.length; i < l; i++){
console.log(items[i]);
}


logs: 'one','two','three'



Reference:
http://www.sitepoint.com/google-closure-how-not-to-write-javascript/






share|improve this answer





















  • 17





    The first example of the "while" syntax won't work if any of the array elements is falsy.

    – Chris Cooper
    Apr 16 '12 at 14:42






  • 2





    ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

    – Stijn de Witt
    Mar 31 '13 at 19:09






  • 1





    @StijndeWitt But for this applies: if the value is falsy, it won't work...

    – yckart
    Jun 22 '13 at 15:30











  • While iterating over collection, you should care about optimization. As it may effect page performance.

    – Zaheer Ahmed
    Jan 11 '14 at 20:56



















53














Intro



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, and WHILE-loops.





A traditional for-loop



A traditional for loop has three components:





  1. The initialization: executed before the look block is executed the first time


  2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false


  3. The afterthought: performed every time after the loop block is executed


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 minimal for loop possible:



for (;;) {
// Do stuff
}


Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-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:



for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}




Using a traditional for loop to loop through an array



The traditional way to loop through an array, is this:



for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}


Or, if you prefer to loop backwards, you do this:



for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}


There are, however, many variations possible, like for example this one:



for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}


... or this one ...



var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}


... or this one:



var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}


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 loop



One alternative to a for loop is a while loop. To loop through an array, you could do this:



var key = 0;
while(value = myArray[key++]){
console.log(value);
}


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, the while loop hereabove behaves the exact same way as this for-loop:



for(var key = 0; value = myArray[key++];){
console.log(value);
}





For...in and for...of



In JavaScript, you can also do this:



for (i in myArray) {
console.log(myArray[i]);
}


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 for for...of. The following example shows the difference between a for...of loop and a for...in loop:



var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
console.log(i); // logs 3, 5, 7
}


Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.





Array.prototype.forEach()



An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:



myArray.forEach(function(value, key, myArray) {
console.log(value);
});


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(myArray, function(key, value) {
console.log(value);
});


_.each(), in Underscore.js:



_.each(myArray, function(value, key, myArray) {
console.log(value);
});


_.forEach(), in Lodash.js:



_.forEach(myArray, function(value, key) {
console.log(value);
});





share|improve this answer

































    36














    If you want a terse way to write a fast loop and you can iterate in reverse:



    for (var i=myArray.length;i--;){
    var item=myArray[i];
    }


    This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.



    There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.






    share|improve this answer





















    • 16





      For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

      – Stijn de Witt
      Mar 1 '13 at 12:09






    • 5





      falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

      – danwellman
      Apr 27 '13 at 7:33






    • 4





      I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

      – Stijn de Witt
      May 15 '14 at 17:23











    • "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

      – Mouscellaneous
      Jan 28 '16 at 8:54






    • 1





      @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

      – Phrogz
      Jan 28 '16 at 18:33





















    28














    Some use cases of looping through an array in the functional programming way in JavaScript:



    1. Just loop through an array



    const myArray = [{x:100}, {x:200}, {x:300}];

    myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
    });


    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



    const people = [
    {name: 'John', age: 23},
    {name: 'Andrew', age: 3},
    {name: 'Peter', age: 8},
    {name: 'Hanna', age: 14},
    {name: 'Adam', age: 37}];

    const anyAdult = people.some(person => person.age >= 18);
    console.log(anyAdult); // true


    3. Transform to a new array



    const myArray = [{x:100}, {x:200}, {x:300}];

    const newArray= myArray.map(element => element.x);
    console.log(newArray); // [100, 200, 300]


    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



    const myArray = [{x:100}, {x:200}, {x:300}];

    const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
    console.log(sum); // 600 = 0 + 100 + 200 + 300

    const average = sum / myArray.length;
    console.log(average); // 200


    5. Create a new array based on the original but without modifying it



    const myArray = [{x:100}, {x:200}, {x:300}];

    const newArray= myArray.map(element => {
    return {
    ...element,
    x: element.x * 2
    };
    });

    console.log(myArray); // [100, 200, 300]
    console.log(newArray); // [200, 400, 600]


    6. Count the number of each category



    const people = [
    {name: 'John', group: 'A'},
    {name: 'Andrew', group: 'C'},
    {name: 'Peter', group: 'A'},
    {name: 'James', group: 'B'},
    {name: 'Hanna', group: 'A'},
    {name: 'Adam', group: 'B'}];

    const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
    return {...groups, A: A + 1};
    } else if (person.group === 'B') {
    return {...groups, B: B + 1};
    } else {
    return {...groups, C: C + 1};
    }
    }, {});

    console.log(groupInfo); // {A: 3, C: 1, B: 2}


    7. Retrieve a subset of an array based on particular criteria



    const myArray = [{x:100}, {x:200}, {x:300}];

    const newArray = myArray.filter(element => element.x > 250);
    console.log(newArray); // [{x:300}]


    Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.



    8. Sort an array



    const people = [
    { name: "John", age: 21 },
    { name: "Peter", age: 31 },
    { name: "Andrew", age: 29 },
    { name: "Thomas", age: 25 }
    ];

    let sortByAge = people.sort(function (p1, p2) {
    return p1.age - p2.age;
    });

    console.log(sortByAge);


    enter image description here



    9. Find an element in an array



    const people = [ {name: "john", age:23},
    {name: "john", age:43},
    {name: "jim", age:101},
    {name: "bob", age:67} ];

    const john = people.find(person => person.name === 'john');
    console.log(john);


    enter image description here



    The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.



    References




    • Array.prototype.some()

    • Array.prototype.forEach()

    • Array.prototype.map()

    • Array.prototype.filter()

    • Array.prototype.sort()

    • Spread syntax

    • Array.prototype.find()






    share|improve this answer

































      26














      There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.



      var i = 0,
      item;

      // note this is weak to sparse arrays or falsey values
      for ( ; item = myStringArray[i++] ; ){
      item; // This is the string at the index.
      }


      Or if you really want to get the id and have a really classical for loop:



      var i = 0,
      len = myStringArray.length; // cache the length

      for ( ; i < len ; i++ ){
      myStringArray[i]; // Don't use this if you plan on changing the length of the array
      }


      Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.






      share|improve this answer





















      • 3





        Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

        – Phrogz
        Jun 4 '12 at 16:28











      • Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

        – Gabriel
        Jun 26 '12 at 1:43






      • 1





        @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

        – Stijn de Witt
        Mar 31 '13 at 19:06






      • 1





        @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

        – Gabriel
        Apr 4 '13 at 17:15






      • 1





        @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

        – Noz
        Jul 30 '14 at 18:14



















      26














      There are various way to loop through array in JavaScript.



      Generic loop:



      var i;
      for (i = 0; i < substr.length; ++i) {
      // Do something with `substr[i]`
      }


      ES5's forEach:



      substr.forEach(function(item) {
      // Do something with `item`
      });


      jQuery.each:



      jQuery.each(substr, function(index, item) {
      // Do something with `item` (or `this` is also `item` if you like)
      });


      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.






      share|improve this answer





















      • 4





        It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

        – Pete
        Dec 30 '14 at 2:33



















      25














      I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.



      For instance:



      _.each([1, 2, 3], function(num){ alert(num); });
      => alerts each number in turn...





      share|improve this answer



















      • 7





        For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

        – Mark Reed
        Oct 11 '13 at 10:59






      • 3





        Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

        – Walter Chapilliquen - wZVanG
        Jun 23 '15 at 23:32



















      24














      Array loop:



      for(var i = 0; i < things.length; i++){
      var thing = things[i];
      console.log(thing);
      }


      Object loop:



      for(var prop in obj){
      var propValue = obj[prop];
      console.log(propValue);
      }





      share|improve this answer

































        22














        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:



        var arr = [1, 2, 3, 4, 5];


        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:



        for (var i=0, l=arr.length; i<l; i++) { 
        console.log(arr[i]);
        }


        2) While loop



        While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:



        let i=0;

        while (arr.length>i) {
        console.log(arr[i]);
        i++;
        }


        3) Do while

        Do while doing the same thing as while with some syntax difference as below:



        let i=0;
        do {
        console.log(arr[i]);
        i++;
        }
        while (arr.length>i);


        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 using while and for.



        This is good article if you like to learn more about the async functions over arrays in JavaScript.




        Functional programming has been making quite a splash in the
        development world these days. And for good reason: Functional
        techniques can help you write more declarative code that is easier to
        understand at a glance, refactor, and test.



        One of the cornerstones of functional programming is its special use
        of lists and list operations. And those things are exactly what the
        sound like they are: arrays of things, and the stuff you do to them.
        But the functional mindset treats them a bit differently than you
        might expect.



        This article will take a close look at what I like to call the "big
        three" list operations: map, filter, and reduce. Wrapping your head
        around these three functions is an important step towards being able
        to write clean functional code, and opens the doors to the vastly
        powerful techniques of functional and reactive programming.



        It also means you'll never have to write a for loop again.




        Read more>> here:






        share|improve this answer


























        • Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

          – shea
          Jun 29 '17 at 8:33



















        19














        If you're using the jQuery library, consider using
        http://api.jquery.com/jQuery.each/



        From the documentation:




        jQuery.each( collection, callback(indexInArray, valueOfElement) )



        Returns: Object



        Description: A generic iterator function, which can be used to
        seamlessly iterate over both objects and arrays. Arrays and array-like
        objects with a length property (such as a function's arguments object)
        are iterated by numeric index, from 0 to length-1. Other objects are
        iterated via their named properties.



        The $.each() function is not the same as $(selector).each(), which is
        used to iterate, exclusively, over a jQuery object. The $.each()
        function can be used to iterate over any collection, whether it is a
        map (JavaScript object) or an array. In the case of an array, the
        callback is passed an array index and a corresponding array value each
        time. (The value can also be accessed through the this keyword, but
        Javascript will always wrap the this value as an Object even if it is
        a simple string or number value.) The method returns its first
        argument, the object that was iterated.







        share|improve this answer





















        • 7





          jQuery for everything?

          – Exception
          Feb 7 '13 at 19:03






        • 6





          Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

          – Stijn de Witt
          Mar 31 '13 at 19:04






        • 1





          Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

          – Stijn de Witt
          Jun 5 '17 at 10:50



















        19














        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



        Performamce results



        Results :



        The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.



        let arr = [1,2,3,4,5];

        for(let i=0, size=arr.length; i<size; i++){
        // do something
        }


        The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead






        share|improve this answer
























        • is better use i = i +1 instead of i++

          – DarckBlezzer
          Dec 10 '18 at 18:19



















        16














        I did not yet see this variation, which I personally like the best:



        Given an array:



        var someArray = ["some", "example", "array"];


        You can loop over it without ever accessing the length property:



        for (var i=0, item; item=someArray[i]; i++) {
        // item is "some", then "example", then "array"
        // i is the index of item in the array
        alert("someArray[" + i + "]: " + item);
        }


        See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/



        This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.



        Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)



        What I like about this loop is:




        • It's short to write

        • No need to access (let alone cache) the length property

        • The item to access is automatically defined within the loop
          body under the name you pick.

        • Combines very naturally with array.push and array.splice to use arrays like lists/stacks


        The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.



        For me, this construct most closely emulates the Java 5 syntax that I love:



        for (String item : someArray) {
        }


        ... with the added benefit of also knowing about the current index inside the loop






        share|improve this answer





















        • 13





          Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

          – CMS
          Feb 28 '13 at 18:31






        • 3





          The loop condition could be (item=someArray[i]) !== undefined.

          – daniel1426
          Mar 20 '14 at 14:17



















        14














        There's a method to iterate over only own object properties, not including prototype's ones:



        for (var i in array) if (array.hasOwnProperty(i)) {
        // do something with array[i]
        }


        but it still will iterate over custom-defined properties.



        In javascript any custom property could be assigned to any object including array.



        If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.






        share|improve this answer
























        • This is interesting, is there any gotchas you have experienced except those mentioned?

          – Daniel Sokolowski
          Oct 9 '14 at 14:34











        • And how about using for (var i in array) if (++i) ?

          – Daniel Sokolowski
          Oct 9 '14 at 14:40



















        14














        There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.






        var myStringArray = ["hello", "World"];
        for(var i in myStringArray) {
        alert(myStringArray[i]);
        }








        var myStringArray = ["hello", "World"];
        for (var i=0; i < myStringArray.length; i++) {
        alert(myStringArray[i]);
        }








        var myStringArray = ["hello", "World"];
        $.each(myStringArray, function(index, value){
        alert(value);
        })

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>








        share|improve this answer


























        • for...in should be avoided for Array-like objects

          – brk
          Dec 5 '16 at 5:25



















        14














        The most elegant and fast way



        var arr = [1, 2, 3, 1023, 1024];
        for (var value; value = arr.pop();) {
        value + 1
        }


        http://jsperf.com/native-loop-performance/8





        Edited (because I was wrong)





        Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.




        • http://jsben.ch/#/BQhED


        Preparation:



        <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
        <script>
        Benchmark.prototype.setup = function() {
        // Fake function with minimal action on the value
        var tmp = 0;
        var process = function(value) {
        tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
        };

        // Declare the test Array
        var arr = ;
        for (var i = 0; i < 100000; i++)
        arr[i] = i;
        };
        </script>


        Tests:



        <a href="http://jsperf.com/native-loop-performance/16" 
        title="http://jsperf.com/native-loop-performance/16"
        ><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>





        share|improve this answer


























        • This loop doesn't seem to follow order of items in the array.

          – Deniz Ozger
          Mar 26 '14 at 15:36











        • My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

          – molokoloco
          Mar 27 '14 at 16:41






        • 14





          -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

          – Bergi
          Mar 30 '14 at 14:49













        • @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

          – Stijn de Witt
          May 15 '14 at 17:34






        • 4





          breaks on falsey items.

          – njzk2
          Jul 29 '14 at 14:59



















        10














        The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.



        var i, max, myStringArray = ["Hello","World"];
        for (i = 0, max = myStringArray.length; i < max; i++) {
        alert(myStringArray[i]);
        //Do something
        }


        If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:



        var i,myStringArray = ["item1","item2"];
        for (i = myStringArray.length; i--) {
        alert(myStringArray[i]);
        }


        or better and cleaner to use while loop:



        var myStringArray = ["item1","item2"],i = myStringArray.length;
        while(i--) {
        // do something with fruits[i]
        }





        share|improve this answer

































          10














          In JavaScript, there are so many solutions to loop an array.



          The code below are popular ones






          /** Declare inputs */
          const items = ['Hello', 'World']

          /** Solution 1. Simple for */
          console.log('solution 1. simple for')

          for (let i = 0; i < items.length; i++) {
          console.log(items[i])
          }

          console.log()
          console.log()

          /** Solution 2. Simple while */
          console.log('solution 2. simple while')

          let i = 0
          while (i < items.length) {
          console.log(items[i++])
          }

          console.log()
          console.log()

          /** Solution 3. forEach*/
          console.log('solution 3. forEach')

          items.forEach(item => {
          console.log(item)
          })

          console.log()
          console.log()

          /** Solution 4. for-of*/
          console.log('solution 4. for-of')

          for (const item of items) {
          console.log(item)
          }

          console.log()
          console.log()








          share|improve this answer

































            9














            Short answer: yes. You can do with this:



            var myArray = ["element1", "element2", "element3", "element4"];

            for (i = 0; i < myArray.length; i++) {
            console.log(myArray[i]);
            }


            In a browser console, you can see something like "element1", "element2", etc., printed.






            share|improve this answer

































              9














              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:



              var numbers = [1,11,22,33,44,55,66,77,88,99,111];
              var sum = 0;
              numbers.forEach(function(n){
              sum += n;
              });


              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:



              var sum = 0;
              var numbers = [1,11,22,33,44,55,66,77,88,99,111];

              for(var i = 0; i<numbers.length; ++i){
              sum += numbers[i];
              }

              alert(i);


              will output "11" - which may or may not be what you want.



              Working jsFiddle example:
              https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/






              share|improve this answer

































                8














                For example, I used in a Firefox console:



                .forEach.call(document.getElementsByTagName('pre'), function(e){ 
                console.log(e);
                })





                share|improve this answer































                  8














                  var x = [4, 5, 6];
                  for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
                  console.log(i,j);
                  }


                  A lot cleaner...






                  share|improve this answer


























                  • did you mean "x =" on the first line?

                    – Matiaan
                    Jan 7 '15 at 12:26



















                  8














                  If you want to use jQuery, it has a nice example in its documentation:



                   $.each([ 52, 97 ], function( index, value ) {
                  alert( index + ": " + value );
                  });





                  share|improve this answer

































                    7














                    Just a simple one line solution






                    arr = ["table", "chair"];

                    // solution
                    arr.map((e) => {
                    console.log(e);
                    return e;
                    });








                    share|improve this answer



















                    • 3





                      You'd rather want to use .forEach() and drop the return e;

                      – Michel Jung
                      Oct 6 '17 at 11:09






                    • 3





                      as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                      – marpme
                      Nov 17 '17 at 22:28



















                    7














                    It's not 100% identical, but similar:






                       var myStringArray = ['Hello', 'World']; // array uses  not {}
                    for (var i in myStringArray) {
                    console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                    }








                    share|improve this answer





















                    • 1





                      It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                      – Kzqai
                      Apr 18 '12 at 15:34















                    1 2
                    next


                    protected by Josh Crozier Mar 17 '14 at 2:31



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    39 Answers
                    39






                    active

                    oldest

                    votes








                    39 Answers
                    39






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    1 2
                    next










                    3270














                    Use a sequential for loop:






                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    @zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.



                    It shouldn't be used for array-like objects because:




                    • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.

                    • Inherited properties are also enumerated.


                    The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.



                    For example:






                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    The above code will console "a", "b", "c" and "foo!".



                    That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).



                    The for-in statement as I said before is there to enumerate object properties, for example:






                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }





                    In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.



                    I would recommend you to read the following article:




                    • Enumeration VS Iteration






                    share|improve this answer





















                    • 179





                      Why the down-vote? for...in should be avoided for Array-like objects!

                      – CMS
                      Jun 10 '10 at 0:10






                    • 16





                      This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                      – OscarRyz
                      Jun 10 '10 at 0:13






                    • 14





                      @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                      – Matthijs Wessels
                      Aug 14 '12 at 16:41






                    • 13





                      @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                      – Phrogz
                      Apr 27 '13 at 13:32






                    • 5





                      jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                      – Enrico
                      Aug 7 '13 at 7:26
















                    3270














                    Use a sequential for loop:






                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    @zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.



                    It shouldn't be used for array-like objects because:




                    • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.

                    • Inherited properties are also enumerated.


                    The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.



                    For example:






                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    The above code will console "a", "b", "c" and "foo!".



                    That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).



                    The for-in statement as I said before is there to enumerate object properties, for example:






                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }





                    In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.



                    I would recommend you to read the following article:




                    • Enumeration VS Iteration






                    share|improve this answer





















                    • 179





                      Why the down-vote? for...in should be avoided for Array-like objects!

                      – CMS
                      Jun 10 '10 at 0:10






                    • 16





                      This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                      – OscarRyz
                      Jun 10 '10 at 0:13






                    • 14





                      @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                      – Matthijs Wessels
                      Aug 14 '12 at 16:41






                    • 13





                      @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                      – Phrogz
                      Apr 27 '13 at 13:32






                    • 5





                      jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                      – Enrico
                      Aug 7 '13 at 7:26














                    3270












                    3270








                    3270







                    Use a sequential for loop:






                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    @zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.



                    It shouldn't be used for array-like objects because:




                    • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.

                    • Inherited properties are also enumerated.


                    The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.



                    For example:






                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    The above code will console "a", "b", "c" and "foo!".



                    That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).



                    The for-in statement as I said before is there to enumerate object properties, for example:






                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }





                    In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.



                    I would recommend you to read the following article:




                    • Enumeration VS Iteration






                    share|improve this answer















                    Use a sequential for loop:






                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    @zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.



                    It shouldn't be used for array-like objects because:




                    • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.

                    • Inherited properties are also enumerated.


                    The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.



                    For example:






                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    The above code will console "a", "b", "c" and "foo!".



                    That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).



                    The for-in statement as I said before is there to enumerate object properties, for example:






                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }





                    In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.



                    I would recommend you to read the following article:




                    • Enumeration VS Iteration






                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    var myStringArray = ["Hello","World"];
                    var arrayLength = myStringArray.length;
                    for (var i = 0; i < arrayLength; i++) {
                    console.log(myStringArray[i]);
                    //Do something
                    }





                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    Array.prototype.foo = "foo!";
                    var array = ['a', 'b', 'c'];

                    for (var i in array) {
                    console.log(array[i]);
                    }





                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }





                    var obj = {
                    "a": 1,
                    "b": 2,
                    "c": 3
                    };

                    for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                    // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
                    console.log("prop: " + prop + " value: " + obj[prop])
                    }
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 15 at 9:06









                    Jonathan

                    8111924




                    8111924










                    answered Jun 10 '10 at 0:07









                    CMSCMS

                    598k162845813




                    598k162845813








                    • 179





                      Why the down-vote? for...in should be avoided for Array-like objects!

                      – CMS
                      Jun 10 '10 at 0:10






                    • 16





                      This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                      – OscarRyz
                      Jun 10 '10 at 0:13






                    • 14





                      @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                      – Matthijs Wessels
                      Aug 14 '12 at 16:41






                    • 13





                      @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                      – Phrogz
                      Apr 27 '13 at 13:32






                    • 5





                      jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                      – Enrico
                      Aug 7 '13 at 7:26














                    • 179





                      Why the down-vote? for...in should be avoided for Array-like objects!

                      – CMS
                      Jun 10 '10 at 0:10






                    • 16





                      This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                      – OscarRyz
                      Jun 10 '10 at 0:13






                    • 14





                      @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                      – Matthijs Wessels
                      Aug 14 '12 at 16:41






                    • 13





                      @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                      – Phrogz
                      Apr 27 '13 at 13:32






                    • 5





                      jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                      – Enrico
                      Aug 7 '13 at 7:26








                    179




                    179





                    Why the down-vote? for...in should be avoided for Array-like objects!

                    – CMS
                    Jun 10 '10 at 0:10





                    Why the down-vote? for...in should be avoided for Array-like objects!

                    – CMS
                    Jun 10 '10 at 0:10




                    16




                    16





                    This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                    – OscarRyz
                    Jun 10 '10 at 0:13





                    This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

                    – OscarRyz
                    Jun 10 '10 at 0:13




                    14




                    14





                    @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                    – Matthijs Wessels
                    Aug 14 '12 at 16:41





                    @DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

                    – Matthijs Wessels
                    Aug 14 '12 at 16:41




                    13




                    13





                    @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                    – Phrogz
                    Apr 27 '13 at 13:32





                    @StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

                    – Phrogz
                    Apr 27 '13 at 13:32




                    5




                    5





                    jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                    – Enrico
                    Aug 7 '13 at 7:26





                    jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

                    – Enrico
                    Aug 7 '13 at 7:26













                    999





                    +50









                    Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.



                    It works like this:



                    // REQUIRES ECMASCRIPT 2015+
                    var s, myStringArray = ["Hello", "World"];
                    for (s of myStringArray) {
                    // ... do something with s ...
                    }


                    Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const:



                    // REQUIRES ECMASCRIPT 2015+
                    const myStringArray = ["Hello", "World"];
                    for (const s of myStringArray) {
                    // ... do something with s ...
                    }
                    // s is no longer defined here


                    Some JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.



                    If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:



                    var myStringArray = [ "Hello", "World" ];
                    myStringArray.forEach( function(s) {
                    // ... do something with s ...
                    } );


                    But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:



                    var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
                    for (i=0; i<len; ++i) {
                    if (i in myStringArray) {
                    s = myStringArray[i];
                    // ... do something with s ...
                    }
                    }


                    Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.



                    You will often see the length caching done in the loop initialization clause, like this:



                    var i, len, myStringArray = [ "Hello", "World" ];
                    for (len = myStringArray.length, i=0; i<len; ++i) {


                    The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.






                    share|improve this answer





















                    • 21





                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                      – Phrogz
                      Jun 4 '12 at 16:29






                    • 2





                      @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                      – Denis V
                      Nov 28 '13 at 21:08






                    • 2





                      @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                      – Mark Reed
                      Nov 29 '13 at 13:34








                    • 1





                      I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                      – Mark Reed
                      Nov 30 '13 at 1:14








                    • 2





                      @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                      – Mark Reed
                      Jan 14 '14 at 15:40
















                    999





                    +50









                    Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.



                    It works like this:



                    // REQUIRES ECMASCRIPT 2015+
                    var s, myStringArray = ["Hello", "World"];
                    for (s of myStringArray) {
                    // ... do something with s ...
                    }


                    Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const:



                    // REQUIRES ECMASCRIPT 2015+
                    const myStringArray = ["Hello", "World"];
                    for (const s of myStringArray) {
                    // ... do something with s ...
                    }
                    // s is no longer defined here


                    Some JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.



                    If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:



                    var myStringArray = [ "Hello", "World" ];
                    myStringArray.forEach( function(s) {
                    // ... do something with s ...
                    } );


                    But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:



                    var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
                    for (i=0; i<len; ++i) {
                    if (i in myStringArray) {
                    s = myStringArray[i];
                    // ... do something with s ...
                    }
                    }


                    Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.



                    You will often see the length caching done in the loop initialization clause, like this:



                    var i, len, myStringArray = [ "Hello", "World" ];
                    for (len = myStringArray.length, i=0; i<len; ++i) {


                    The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.






                    share|improve this answer





















                    • 21





                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                      – Phrogz
                      Jun 4 '12 at 16:29






                    • 2





                      @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                      – Denis V
                      Nov 28 '13 at 21:08






                    • 2





                      @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                      – Mark Reed
                      Nov 29 '13 at 13:34








                    • 1





                      I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                      – Mark Reed
                      Nov 30 '13 at 1:14








                    • 2





                      @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                      – Mark Reed
                      Jan 14 '14 at 15:40














                    999





                    +50







                    999





                    +50



                    999




                    +50





                    Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.



                    It works like this:



                    // REQUIRES ECMASCRIPT 2015+
                    var s, myStringArray = ["Hello", "World"];
                    for (s of myStringArray) {
                    // ... do something with s ...
                    }


                    Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const:



                    // REQUIRES ECMASCRIPT 2015+
                    const myStringArray = ["Hello", "World"];
                    for (const s of myStringArray) {
                    // ... do something with s ...
                    }
                    // s is no longer defined here


                    Some JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.



                    If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:



                    var myStringArray = [ "Hello", "World" ];
                    myStringArray.forEach( function(s) {
                    // ... do something with s ...
                    } );


                    But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:



                    var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
                    for (i=0; i<len; ++i) {
                    if (i in myStringArray) {
                    s = myStringArray[i];
                    // ... do something with s ...
                    }
                    }


                    Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.



                    You will often see the length caching done in the loop initialization clause, like this:



                    var i, len, myStringArray = [ "Hello", "World" ];
                    for (len = myStringArray.length, i=0; i<len; ++i) {


                    The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.






                    share|improve this answer















                    Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.



                    It works like this:



                    // REQUIRES ECMASCRIPT 2015+
                    var s, myStringArray = ["Hello", "World"];
                    for (s of myStringArray) {
                    // ... do something with s ...
                    }


                    Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const:



                    // REQUIRES ECMASCRIPT 2015+
                    const myStringArray = ["Hello", "World"];
                    for (const s of myStringArray) {
                    // ... do something with s ...
                    }
                    // s is no longer defined here


                    Some JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.



                    If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:



                    var myStringArray = [ "Hello", "World" ];
                    myStringArray.forEach( function(s) {
                    // ... do something with s ...
                    } );


                    But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:



                    var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
                    for (i=0; i<len; ++i) {
                    if (i in myStringArray) {
                    s = myStringArray[i];
                    // ... do something with s ...
                    }
                    }


                    Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.



                    You will often see the length caching done in the loop initialization clause, like this:



                    var i, len, myStringArray = [ "Hello", "World" ];
                    for (len = myStringArray.length, i=0; i<len; ++i) {


                    The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 2 at 16:44

























                    answered Apr 16 '12 at 2:03









                    Mark ReedMark Reed

                    66.1k989124




                    66.1k989124








                    • 21





                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                      – Phrogz
                      Jun 4 '12 at 16:29






                    • 2





                      @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                      – Denis V
                      Nov 28 '13 at 21:08






                    • 2





                      @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                      – Mark Reed
                      Nov 29 '13 at 13:34








                    • 1





                      I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                      – Mark Reed
                      Nov 30 '13 at 1:14








                    • 2





                      @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                      – Mark Reed
                      Jan 14 '14 at 15:40














                    • 21





                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                      – Phrogz
                      Jun 4 '12 at 16:29






                    • 2





                      @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                      – Denis V
                      Nov 28 '13 at 21:08






                    • 2





                      @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                      – Mark Reed
                      Nov 29 '13 at 13:34








                    • 1





                      I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                      – Mark Reed
                      Nov 30 '13 at 1:14








                    • 2





                      @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                      – Mark Reed
                      Jan 14 '14 at 15:40








                    21




                    21





                    Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                    – Phrogz
                    Jun 4 '12 at 16:29





                    Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

                    – Phrogz
                    Jun 4 '12 at 16:29




                    2




                    2





                    @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                    – Denis V
                    Nov 28 '13 at 21:08





                    @mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

                    – Denis V
                    Nov 28 '13 at 21:08




                    2




                    2





                    @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                    – Mark Reed
                    Nov 29 '13 at 13:34







                    @DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

                    – Mark Reed
                    Nov 29 '13 at 13:34






                    1




                    1





                    I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                    – Mark Reed
                    Nov 30 '13 at 1:14







                    I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

                    – Mark Reed
                    Nov 30 '13 at 1:14






                    2




                    2





                    @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                    – Mark Reed
                    Jan 14 '14 at 15:40





                    @GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

                    – Mark Reed
                    Jan 14 '14 at 15:40











                    415














                    You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.



                    [1,2,3,4].map( function(item) {
                    alert(item);
                    })


                    The general syntax is:



                    array.map(func)


                    In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.



                    The return value of array.map is another array, so you can use it like this:



                    var x = [1,2,3,4].map( function(item) {return item * 10;});


                    And now x is [10,20,30,40].



                    You don't have to write the function inline. It could be a separate function.



                    var item_processor = function(item) {
                    // Do something complicated to an item
                    }

                    new_list = my_list.map(item_processor);


                    which would be sort-of equivalent to:



                     for (item in my_list) {item_processor(item);}


                    Except you don't get the new_list.






                    share|improve this answer





















                    • 7





                      No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                      – hasen
                      Jun 10 '10 at 0:14






                    • 91





                      That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                      – harto
                      Jun 10 '10 at 0:20






                    • 21





                      @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                      – CMS
                      Jun 10 '10 at 0:30








                    • 3





                      The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                      – Mark Reed
                      Sep 10 '14 at 17:00








                    • 3





                      Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                      – gengkev
                      Apr 26 '16 at 23:47
















                    415














                    You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.



                    [1,2,3,4].map( function(item) {
                    alert(item);
                    })


                    The general syntax is:



                    array.map(func)


                    In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.



                    The return value of array.map is another array, so you can use it like this:



                    var x = [1,2,3,4].map( function(item) {return item * 10;});


                    And now x is [10,20,30,40].



                    You don't have to write the function inline. It could be a separate function.



                    var item_processor = function(item) {
                    // Do something complicated to an item
                    }

                    new_list = my_list.map(item_processor);


                    which would be sort-of equivalent to:



                     for (item in my_list) {item_processor(item);}


                    Except you don't get the new_list.






                    share|improve this answer





















                    • 7





                      No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                      – hasen
                      Jun 10 '10 at 0:14






                    • 91





                      That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                      – harto
                      Jun 10 '10 at 0:20






                    • 21





                      @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                      – CMS
                      Jun 10 '10 at 0:30








                    • 3





                      The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                      – Mark Reed
                      Sep 10 '14 at 17:00








                    • 3





                      Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                      – gengkev
                      Apr 26 '16 at 23:47














                    415












                    415








                    415







                    You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.



                    [1,2,3,4].map( function(item) {
                    alert(item);
                    })


                    The general syntax is:



                    array.map(func)


                    In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.



                    The return value of array.map is another array, so you can use it like this:



                    var x = [1,2,3,4].map( function(item) {return item * 10;});


                    And now x is [10,20,30,40].



                    You don't have to write the function inline. It could be a separate function.



                    var item_processor = function(item) {
                    // Do something complicated to an item
                    }

                    new_list = my_list.map(item_processor);


                    which would be sort-of equivalent to:



                     for (item in my_list) {item_processor(item);}


                    Except you don't get the new_list.






                    share|improve this answer















                    You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.



                    [1,2,3,4].map( function(item) {
                    alert(item);
                    })


                    The general syntax is:



                    array.map(func)


                    In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.



                    The return value of array.map is another array, so you can use it like this:



                    var x = [1,2,3,4].map( function(item) {return item * 10;});


                    And now x is [10,20,30,40].



                    You don't have to write the function inline. It could be a separate function.



                    var item_processor = function(item) {
                    // Do something complicated to an item
                    }

                    new_list = my_list.map(item_processor);


                    which would be sort-of equivalent to:



                     for (item in my_list) {item_processor(item);}


                    Except you don't get the new_list.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 6 '18 at 3:40









                    Peter Mortensen

                    13.7k1986113




                    13.7k1986113










                    answered Jun 10 '10 at 0:09









                    hasenhasen

                    83.4k58166212




                    83.4k58166212








                    • 7





                      No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                      – hasen
                      Jun 10 '10 at 0:14






                    • 91





                      That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                      – harto
                      Jun 10 '10 at 0:20






                    • 21





                      @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                      – CMS
                      Jun 10 '10 at 0:30








                    • 3





                      The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                      – Mark Reed
                      Sep 10 '14 at 17:00








                    • 3





                      Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                      – gengkev
                      Apr 26 '16 at 23:47














                    • 7





                      No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                      – hasen
                      Jun 10 '10 at 0:14






                    • 91





                      That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                      – harto
                      Jun 10 '10 at 0:20






                    • 21





                      @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                      – CMS
                      Jun 10 '10 at 0:30








                    • 3





                      The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                      – Mark Reed
                      Sep 10 '14 at 17:00








                    • 3





                      Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                      – gengkev
                      Apr 26 '16 at 23:47








                    7




                    7





                    No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                    – hasen
                    Jun 10 '10 at 0:14





                    No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

                    – hasen
                    Jun 10 '10 at 0:14




                    91




                    91





                    That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                    – harto
                    Jun 10 '10 at 0:20





                    That particular example is probably better implemented using Array.forEach. map is for generating a new array.

                    – harto
                    Jun 10 '10 at 0:20




                    21




                    21





                    @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                    – CMS
                    Jun 10 '10 at 0:30







                    @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

                    – CMS
                    Jun 10 '10 at 0:30






                    3




                    3





                    The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                    – Mark Reed
                    Sep 10 '14 at 17:00







                    The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

                    – Mark Reed
                    Sep 10 '14 at 17:00






                    3




                    3





                    Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                    – gengkev
                    Apr 26 '16 at 23:47





                    Downvote because if you're not actually mapping something, then using .map is misleading. .forEach makes semantic sense and also passes the same three arguments to the function.

                    – gengkev
                    Apr 26 '16 at 23:47











                    107














                    In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:



                    for(var i=0, len=myArray.length; i < len; i++){}


                    It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.






                    share|improve this answer





















                    • 2





                      myArray.forEach(function(obj) {}); is still the best

                      – Jan Sverre
                      Jan 2 '12 at 19:47











                    • a tiny improvement: you could use ++i instead of i++

                      – roberkules
                      Apr 12 '12 at 14:58






                    • 13





                      ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                      – ngryman
                      Apr 15 '12 at 0:45













                    • @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                      – Jose
                      May 8 '12 at 13:03






                    • 5





                      You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                      – Rui Marques
                      Nov 30 '12 at 13:12


















                    107














                    In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:



                    for(var i=0, len=myArray.length; i < len; i++){}


                    It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.






                    share|improve this answer





















                    • 2





                      myArray.forEach(function(obj) {}); is still the best

                      – Jan Sverre
                      Jan 2 '12 at 19:47











                    • a tiny improvement: you could use ++i instead of i++

                      – roberkules
                      Apr 12 '12 at 14:58






                    • 13





                      ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                      – ngryman
                      Apr 15 '12 at 0:45













                    • @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                      – Jose
                      May 8 '12 at 13:03






                    • 5





                      You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                      – Rui Marques
                      Nov 30 '12 at 13:12
















                    107












                    107








                    107







                    In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:



                    for(var i=0, len=myArray.length; i < len; i++){}


                    It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.






                    share|improve this answer















                    In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:



                    for(var i=0, len=myArray.length; i < len; i++){}


                    It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 4 '11 at 18:08









                    Nightfirecat

                    9,78563050




                    9,78563050










                    answered Dec 7 '10 at 7:24









                    sebarmelisebarmeli

                    15.5k62939




                    15.5k62939








                    • 2





                      myArray.forEach(function(obj) {}); is still the best

                      – Jan Sverre
                      Jan 2 '12 at 19:47











                    • a tiny improvement: you could use ++i instead of i++

                      – roberkules
                      Apr 12 '12 at 14:58






                    • 13





                      ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                      – ngryman
                      Apr 15 '12 at 0:45













                    • @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                      – Jose
                      May 8 '12 at 13:03






                    • 5





                      You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                      – Rui Marques
                      Nov 30 '12 at 13:12
















                    • 2





                      myArray.forEach(function(obj) {}); is still the best

                      – Jan Sverre
                      Jan 2 '12 at 19:47











                    • a tiny improvement: you could use ++i instead of i++

                      – roberkules
                      Apr 12 '12 at 14:58






                    • 13





                      ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                      – ngryman
                      Apr 15 '12 at 0:45













                    • @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                      – Jose
                      May 8 '12 at 13:03






                    • 5





                      You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                      – Rui Marques
                      Nov 30 '12 at 13:12










                    2




                    2





                    myArray.forEach(function(obj) {}); is still the best

                    – Jan Sverre
                    Jan 2 '12 at 19:47





                    myArray.forEach(function(obj) {}); is still the best

                    – Jan Sverre
                    Jan 2 '12 at 19:47













                    a tiny improvement: you could use ++i instead of i++

                    – roberkules
                    Apr 12 '12 at 14:58





                    a tiny improvement: you could use ++i instead of i++

                    – roberkules
                    Apr 12 '12 at 14:58




                    13




                    13





                    ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                    – ngryman
                    Apr 15 '12 at 0:45







                    ++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

                    – ngryman
                    Apr 15 '12 at 0:45















                    @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                    – Jose
                    May 8 '12 at 13:03





                    @Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

                    – Jose
                    May 8 '12 at 13:03




                    5




                    5





                    You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                    – Rui Marques
                    Nov 30 '12 at 13:12







                    You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

                    – Rui Marques
                    Nov 30 '12 at 13:12













                    101














                    for (var s of myStringArray) {



                    (Directly answering your question: now you can!)



                    Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.



                    This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.



                    It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.



                    It also works on Node (I tested it on version 0.12.0).



                    Iterating an array



                    // You could also use "let" instead of "var" for block scope.
                    for (var letter of ["a", "b", "c"]) {
                    console.log(letter);
                    }


                    Iterating an array of objects



                    var band = [
                    {firstName : 'John', lastName: 'Lennon'},
                    {firstName : 'Paul', lastName: 'McCartney'}
                    ];

                    for(var member of band){
                    console.log(member.firstName + ' ' + member.lastName);
                    }


                    Iterating a generator:



                    (example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)



                    function* fibonacci() { // a generator function
                    let [prev, curr] = [1, 1];
                    while (true) {
                    [prev, curr] = [curr, prev + curr];
                    yield curr;
                    }
                    }

                    for (let n of fibonacci()) {
                    console.log(n);
                    // truncate the sequence at 1000
                    if (n >= 1000) {
                    break;
                    }
                    }




                    Compatibility table:
                    http://kangax.github.io/es5-compat-table/es6/#For..of loops



                    Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators



                    }






                    share|improve this answer


























                    • If you're using ES6, I would suggest const s instead of var s

                      – joeytwiddle
                      Feb 10 '18 at 6:26
















                    101














                    for (var s of myStringArray) {



                    (Directly answering your question: now you can!)



                    Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.



                    This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.



                    It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.



                    It also works on Node (I tested it on version 0.12.0).



                    Iterating an array



                    // You could also use "let" instead of "var" for block scope.
                    for (var letter of ["a", "b", "c"]) {
                    console.log(letter);
                    }


                    Iterating an array of objects



                    var band = [
                    {firstName : 'John', lastName: 'Lennon'},
                    {firstName : 'Paul', lastName: 'McCartney'}
                    ];

                    for(var member of band){
                    console.log(member.firstName + ' ' + member.lastName);
                    }


                    Iterating a generator:



                    (example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)



                    function* fibonacci() { // a generator function
                    let [prev, curr] = [1, 1];
                    while (true) {
                    [prev, curr] = [curr, prev + curr];
                    yield curr;
                    }
                    }

                    for (let n of fibonacci()) {
                    console.log(n);
                    // truncate the sequence at 1000
                    if (n >= 1000) {
                    break;
                    }
                    }




                    Compatibility table:
                    http://kangax.github.io/es5-compat-table/es6/#For..of loops



                    Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators



                    }






                    share|improve this answer


























                    • If you're using ES6, I would suggest const s instead of var s

                      – joeytwiddle
                      Feb 10 '18 at 6:26














                    101












                    101








                    101







                    for (var s of myStringArray) {



                    (Directly answering your question: now you can!)



                    Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.



                    This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.



                    It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.



                    It also works on Node (I tested it on version 0.12.0).



                    Iterating an array



                    // You could also use "let" instead of "var" for block scope.
                    for (var letter of ["a", "b", "c"]) {
                    console.log(letter);
                    }


                    Iterating an array of objects



                    var band = [
                    {firstName : 'John', lastName: 'Lennon'},
                    {firstName : 'Paul', lastName: 'McCartney'}
                    ];

                    for(var member of band){
                    console.log(member.firstName + ' ' + member.lastName);
                    }


                    Iterating a generator:



                    (example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)



                    function* fibonacci() { // a generator function
                    let [prev, curr] = [1, 1];
                    while (true) {
                    [prev, curr] = [curr, prev + curr];
                    yield curr;
                    }
                    }

                    for (let n of fibonacci()) {
                    console.log(n);
                    // truncate the sequence at 1000
                    if (n >= 1000) {
                    break;
                    }
                    }




                    Compatibility table:
                    http://kangax.github.io/es5-compat-table/es6/#For..of loops



                    Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators



                    }






                    share|improve this answer















                    for (var s of myStringArray) {



                    (Directly answering your question: now you can!)



                    Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.



                    This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.



                    It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.



                    It also works on Node (I tested it on version 0.12.0).



                    Iterating an array



                    // You could also use "let" instead of "var" for block scope.
                    for (var letter of ["a", "b", "c"]) {
                    console.log(letter);
                    }


                    Iterating an array of objects



                    var band = [
                    {firstName : 'John', lastName: 'Lennon'},
                    {firstName : 'Paul', lastName: 'McCartney'}
                    ];

                    for(var member of band){
                    console.log(member.firstName + ' ' + member.lastName);
                    }


                    Iterating a generator:



                    (example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)



                    function* fibonacci() { // a generator function
                    let [prev, curr] = [1, 1];
                    while (true) {
                    [prev, curr] = [curr, prev + curr];
                    yield curr;
                    }
                    }

                    for (let n of fibonacci()) {
                    console.log(n);
                    // truncate the sequence at 1000
                    if (n >= 1000) {
                    break;
                    }
                    }




                    Compatibility table:
                    http://kangax.github.io/es5-compat-table/es6/#For..of loops



                    Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators



                    }







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 12 '17 at 10:13

























                    answered Aug 11 '13 at 15:54









                    Marlon BernardesMarlon Bernardes

                    6,59942742




                    6,59942742













                    • If you're using ES6, I would suggest const s instead of var s

                      – joeytwiddle
                      Feb 10 '18 at 6:26



















                    • If you're using ES6, I would suggest const s instead of var s

                      – joeytwiddle
                      Feb 10 '18 at 6:26

















                    If you're using ES6, I would suggest const s instead of var s

                    – joeytwiddle
                    Feb 10 '18 at 6:26





                    If you're using ES6, I would suggest const s instead of var s

                    – joeytwiddle
                    Feb 10 '18 at 6:26











                    84














                    Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.



                    You may not need all of them, but they can be very useful, or would be if every browser supported them.



                    Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.



                    filter returns an array of items that satisfy some condition or test.



                    every returns true if every array member passes the test.



                    some returns true if any pass the test.



                    forEach runs a function on each array member and doesn't return anything.



                    map is like forEach, but it returns an array of the results of the operation for each element.



                    These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.



                    Ignore it until you need it.



                    indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.



                    (function(){
                    var p, ap= Array.prototype, p2={
                    filter: function(fun, scope){
                    var L= this.length, A= , i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                    A[A.length]= val;
                    }
                    }
                    ++i;
                    }
                    }
                    return A;
                    },
                    every: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                    return false;
                    ++i;
                    }
                    return true;
                    }
                    return null;
                    },
                    forEach: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    }
                    return this;
                    },
                    indexOf: function(what, i){
                    i= i || 0;
                    var L= this.length;
                    while(i< L){
                    if(this[i]=== what)
                    return i;
                    ++i;
                    }
                    return -1;
                    },
                    lastIndexOf: function(what, i){
                    var L= this.length;
                    i= i || L-1;
                    if(isNaN(i) || i>= L)
                    i= L-1;
                    else
                    if(i< 0) i += L;
                    while(i> -1){
                    if(this[i]=== what)
                    return i;
                    --i;
                    }
                    return -1;
                    },
                    map: function(fun, scope){
                    var L= this.length, A= Array(this.length), i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    return A;
                    }
                    },
                    some: function(fun, scope){
                    var i= 0, L= this.length;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                    return true;
                    ++i;
                    }
                    return false;
                    }
                    }
                    }
                    for(p in p2){
                    if(!ap[p])
                    ap[p]= p2[p];
                    }
                    return true;
                    })();





                    share|improve this answer





















                    • 1





                      Addition: IE supports forEach since version 9, see forEach Method MSDN

                      – rwitzel
                      Apr 17 '15 at 15:12


















                    84














                    Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.



                    You may not need all of them, but they can be very useful, or would be if every browser supported them.



                    Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.



                    filter returns an array of items that satisfy some condition or test.



                    every returns true if every array member passes the test.



                    some returns true if any pass the test.



                    forEach runs a function on each array member and doesn't return anything.



                    map is like forEach, but it returns an array of the results of the operation for each element.



                    These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.



                    Ignore it until you need it.



                    indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.



                    (function(){
                    var p, ap= Array.prototype, p2={
                    filter: function(fun, scope){
                    var L= this.length, A= , i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                    A[A.length]= val;
                    }
                    }
                    ++i;
                    }
                    }
                    return A;
                    },
                    every: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                    return false;
                    ++i;
                    }
                    return true;
                    }
                    return null;
                    },
                    forEach: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    }
                    return this;
                    },
                    indexOf: function(what, i){
                    i= i || 0;
                    var L= this.length;
                    while(i< L){
                    if(this[i]=== what)
                    return i;
                    ++i;
                    }
                    return -1;
                    },
                    lastIndexOf: function(what, i){
                    var L= this.length;
                    i= i || L-1;
                    if(isNaN(i) || i>= L)
                    i= L-1;
                    else
                    if(i< 0) i += L;
                    while(i> -1){
                    if(this[i]=== what)
                    return i;
                    --i;
                    }
                    return -1;
                    },
                    map: function(fun, scope){
                    var L= this.length, A= Array(this.length), i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    return A;
                    }
                    },
                    some: function(fun, scope){
                    var i= 0, L= this.length;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                    return true;
                    ++i;
                    }
                    return false;
                    }
                    }
                    }
                    for(p in p2){
                    if(!ap[p])
                    ap[p]= p2[p];
                    }
                    return true;
                    })();





                    share|improve this answer





















                    • 1





                      Addition: IE supports forEach since version 9, see forEach Method MSDN

                      – rwitzel
                      Apr 17 '15 at 15:12
















                    84












                    84








                    84







                    Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.



                    You may not need all of them, but they can be very useful, or would be if every browser supported them.



                    Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.



                    filter returns an array of items that satisfy some condition or test.



                    every returns true if every array member passes the test.



                    some returns true if any pass the test.



                    forEach runs a function on each array member and doesn't return anything.



                    map is like forEach, but it returns an array of the results of the operation for each element.



                    These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.



                    Ignore it until you need it.



                    indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.



                    (function(){
                    var p, ap= Array.prototype, p2={
                    filter: function(fun, scope){
                    var L= this.length, A= , i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                    A[A.length]= val;
                    }
                    }
                    ++i;
                    }
                    }
                    return A;
                    },
                    every: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                    return false;
                    ++i;
                    }
                    return true;
                    }
                    return null;
                    },
                    forEach: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    }
                    return this;
                    },
                    indexOf: function(what, i){
                    i= i || 0;
                    var L= this.length;
                    while(i< L){
                    if(this[i]=== what)
                    return i;
                    ++i;
                    }
                    return -1;
                    },
                    lastIndexOf: function(what, i){
                    var L= this.length;
                    i= i || L-1;
                    if(isNaN(i) || i>= L)
                    i= L-1;
                    else
                    if(i< 0) i += L;
                    while(i> -1){
                    if(this[i]=== what)
                    return i;
                    --i;
                    }
                    return -1;
                    },
                    map: function(fun, scope){
                    var L= this.length, A= Array(this.length), i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    return A;
                    }
                    },
                    some: function(fun, scope){
                    var i= 0, L= this.length;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                    return true;
                    ++i;
                    }
                    return false;
                    }
                    }
                    }
                    for(p in p2){
                    if(!ap[p])
                    ap[p]= p2[p];
                    }
                    return true;
                    })();





                    share|improve this answer















                    Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.



                    You may not need all of them, but they can be very useful, or would be if every browser supported them.



                    Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.



                    filter returns an array of items that satisfy some condition or test.



                    every returns true if every array member passes the test.



                    some returns true if any pass the test.



                    forEach runs a function on each array member and doesn't return anything.



                    map is like forEach, but it returns an array of the results of the operation for each element.



                    These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.



                    Ignore it until you need it.



                    indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.



                    (function(){
                    var p, ap= Array.prototype, p2={
                    filter: function(fun, scope){
                    var L= this.length, A= , i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                    A[A.length]= val;
                    }
                    }
                    ++i;
                    }
                    }
                    return A;
                    },
                    every: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                    return false;
                    ++i;
                    }
                    return true;
                    }
                    return null;
                    },
                    forEach: function(fun, scope){
                    var L= this.length, i= 0;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    }
                    return this;
                    },
                    indexOf: function(what, i){
                    i= i || 0;
                    var L= this.length;
                    while(i< L){
                    if(this[i]=== what)
                    return i;
                    ++i;
                    }
                    return -1;
                    },
                    lastIndexOf: function(what, i){
                    var L= this.length;
                    i= i || L-1;
                    if(isNaN(i) || i>= L)
                    i= L-1;
                    else
                    if(i< 0) i += L;
                    while(i> -1){
                    if(this[i]=== what)
                    return i;
                    --i;
                    }
                    return -1;
                    },
                    map: function(fun, scope){
                    var L= this.length, A= Array(this.length), i= 0, val;
                    if(typeof fun== 'function'){
                    while(i< L){
                    if(i in this){
                    A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                    }
                    return A;
                    }
                    },
                    some: function(fun, scope){
                    var i= 0, L= this.length;
                    if(typeof fun== 'function'){
                    while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                    return true;
                    ++i;
                    }
                    return false;
                    }
                    }
                    }
                    for(p in p2){
                    if(!ap[p])
                    ap[p]= p2[p];
                    }
                    return true;
                    })();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 2 '16 at 19:57









                    Peter Mortensen

                    13.7k1986113




                    13.7k1986113










                    answered Jun 10 '10 at 2:43









                    kennebeckennebec

                    79.4k2286117




                    79.4k2286117








                    • 1





                      Addition: IE supports forEach since version 9, see forEach Method MSDN

                      – rwitzel
                      Apr 17 '15 at 15:12
















                    • 1





                      Addition: IE supports forEach since version 9, see forEach Method MSDN

                      – rwitzel
                      Apr 17 '15 at 15:12










                    1




                    1





                    Addition: IE supports forEach since version 9, see forEach Method MSDN

                    – rwitzel
                    Apr 17 '15 at 15:12







                    Addition: IE supports forEach since version 9, see forEach Method MSDN

                    – rwitzel
                    Apr 17 '15 at 15:12













                    62














                    Use the while loop...



                    var i=0, item, items = ['one','two','three'];
                    while(item = items[i++]){
                    console.log(item);
                    }


                    logs: 'one','two','three'



                    And for the reverse order, an even more efficient loop



                    var items = ['one','two','three'], i = items.length;
                    while(i--){
                    console.log(items[i]);
                    }


                    logs: 'three','two','one'



                    Or the classical for loop



                    var items = ['one','two','three']
                    for(var i=0, l = items.length; i < l; i++){
                    console.log(items[i]);
                    }


                    logs: 'one','two','three'



                    Reference:
                    http://www.sitepoint.com/google-closure-how-not-to-write-javascript/






                    share|improve this answer





















                    • 17





                      The first example of the "while" syntax won't work if any of the array elements is falsy.

                      – Chris Cooper
                      Apr 16 '12 at 14:42






                    • 2





                      ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                      – Stijn de Witt
                      Mar 31 '13 at 19:09






                    • 1





                      @StijndeWitt But for this applies: if the value is falsy, it won't work...

                      – yckart
                      Jun 22 '13 at 15:30











                    • While iterating over collection, you should care about optimization. As it may effect page performance.

                      – Zaheer Ahmed
                      Jan 11 '14 at 20:56
















                    62














                    Use the while loop...



                    var i=0, item, items = ['one','two','three'];
                    while(item = items[i++]){
                    console.log(item);
                    }


                    logs: 'one','two','three'



                    And for the reverse order, an even more efficient loop



                    var items = ['one','two','three'], i = items.length;
                    while(i--){
                    console.log(items[i]);
                    }


                    logs: 'three','two','one'



                    Or the classical for loop



                    var items = ['one','two','three']
                    for(var i=0, l = items.length; i < l; i++){
                    console.log(items[i]);
                    }


                    logs: 'one','two','three'



                    Reference:
                    http://www.sitepoint.com/google-closure-how-not-to-write-javascript/






                    share|improve this answer





















                    • 17





                      The first example of the "while" syntax won't work if any of the array elements is falsy.

                      – Chris Cooper
                      Apr 16 '12 at 14:42






                    • 2





                      ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                      – Stijn de Witt
                      Mar 31 '13 at 19:09






                    • 1





                      @StijndeWitt But for this applies: if the value is falsy, it won't work...

                      – yckart
                      Jun 22 '13 at 15:30











                    • While iterating over collection, you should care about optimization. As it may effect page performance.

                      – Zaheer Ahmed
                      Jan 11 '14 at 20:56














                    62












                    62








                    62







                    Use the while loop...



                    var i=0, item, items = ['one','two','three'];
                    while(item = items[i++]){
                    console.log(item);
                    }


                    logs: 'one','two','three'



                    And for the reverse order, an even more efficient loop



                    var items = ['one','two','three'], i = items.length;
                    while(i--){
                    console.log(items[i]);
                    }


                    logs: 'three','two','one'



                    Or the classical for loop



                    var items = ['one','two','three']
                    for(var i=0, l = items.length; i < l; i++){
                    console.log(items[i]);
                    }


                    logs: 'one','two','three'



                    Reference:
                    http://www.sitepoint.com/google-closure-how-not-to-write-javascript/






                    share|improve this answer















                    Use the while loop...



                    var i=0, item, items = ['one','two','three'];
                    while(item = items[i++]){
                    console.log(item);
                    }


                    logs: 'one','two','three'



                    And for the reverse order, an even more efficient loop



                    var items = ['one','two','three'], i = items.length;
                    while(i--){
                    console.log(items[i]);
                    }


                    logs: 'three','two','one'



                    Or the classical for loop



                    var items = ['one','two','three']
                    for(var i=0, l = items.length; i < l; i++){
                    console.log(items[i]);
                    }


                    logs: 'one','two','three'



                    Reference:
                    http://www.sitepoint.com/google-closure-how-not-to-write-javascript/







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 14 '14 at 19:26

























                    answered Jan 5 '12 at 9:15









                    Timo HuovinenTimo Huovinen

                    32.9k27109115




                    32.9k27109115








                    • 17





                      The first example of the "while" syntax won't work if any of the array elements is falsy.

                      – Chris Cooper
                      Apr 16 '12 at 14:42






                    • 2





                      ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                      – Stijn de Witt
                      Mar 31 '13 at 19:09






                    • 1





                      @StijndeWitt But for this applies: if the value is falsy, it won't work...

                      – yckart
                      Jun 22 '13 at 15:30











                    • While iterating over collection, you should care about optimization. As it may effect page performance.

                      – Zaheer Ahmed
                      Jan 11 '14 at 20:56














                    • 17





                      The first example of the "while" syntax won't work if any of the array elements is falsy.

                      – Chris Cooper
                      Apr 16 '12 at 14:42






                    • 2





                      ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                      – Stijn de Witt
                      Mar 31 '13 at 19:09






                    • 1





                      @StijndeWitt But for this applies: if the value is falsy, it won't work...

                      – yckart
                      Jun 22 '13 at 15:30











                    • While iterating over collection, you should care about optimization. As it may effect page performance.

                      – Zaheer Ahmed
                      Jan 11 '14 at 20:56








                    17




                    17





                    The first example of the "while" syntax won't work if any of the array elements is falsy.

                    – Chris Cooper
                    Apr 16 '12 at 14:42





                    The first example of the "while" syntax won't work if any of the array elements is falsy.

                    – Chris Cooper
                    Apr 16 '12 at 14:42




                    2




                    2





                    ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                    – Stijn de Witt
                    Mar 31 '13 at 19:09





                    ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

                    – Stijn de Witt
                    Mar 31 '13 at 19:09




                    1




                    1





                    @StijndeWitt But for this applies: if the value is falsy, it won't work...

                    – yckart
                    Jun 22 '13 at 15:30





                    @StijndeWitt But for this applies: if the value is falsy, it won't work...

                    – yckart
                    Jun 22 '13 at 15:30













                    While iterating over collection, you should care about optimization. As it may effect page performance.

                    – Zaheer Ahmed
                    Jan 11 '14 at 20:56





                    While iterating over collection, you should care about optimization. As it may effect page performance.

                    – Zaheer Ahmed
                    Jan 11 '14 at 20:56











                    53














                    Intro



                    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, and WHILE-loops.





                    A traditional for-loop



                    A traditional for loop has three components:





                    1. The initialization: executed before the look block is executed the first time


                    2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false


                    3. The afterthought: performed every time after the loop block is executed


                    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 minimal for loop possible:



                    for (;;) {
                    // Do stuff
                    }


                    Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-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:



                    for (var i = 0, length = 10; i < length; i++) {
                    console.log(i);
                    }




                    Using a traditional for loop to loop through an array



                    The traditional way to loop through an array, is this:



                    for (var i = 0, length = myArray.length; i < length; i++) {
                    console.log(myArray[i]);
                    }


                    Or, if you prefer to loop backwards, you do this:



                    for (var i = myArray.length - 1; i > -1; i--) {
                    console.log(myArray[i]);
                    }


                    There are, however, many variations possible, like for example this one:



                    for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
                    console.log(value);
                    }


                    ... or this one ...



                    var i = 0, length = myArray.length;
                    for (; i < length;) {
                    console.log(myArray[i]);
                    i++;
                    }


                    ... or this one:



                    var key = 0, value;
                    for (; value = myArray[key++];){
                    console.log(value);
                    }


                    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 loop



                    One alternative to a for loop is a while loop. To loop through an array, you could do this:



                    var key = 0;
                    while(value = myArray[key++]){
                    console.log(value);
                    }


                    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, the while loop hereabove behaves the exact same way as this for-loop:



                    for(var key = 0; value = myArray[key++];){
                    console.log(value);
                    }





                    For...in and for...of



                    In JavaScript, you can also do this:



                    for (i in myArray) {
                    console.log(myArray[i]);
                    }


                    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 for for...of. The following example shows the difference between a for...of loop and a for...in loop:



                    var myArray = [3, 5, 7];
                    myArray.foo = "hello";

                    for (var i in myArray) {
                    console.log(i); // logs 0, 1, 2, "foo"
                    }

                    for (var i of myArray) {
                    console.log(i); // logs 3, 5, 7
                    }


                    Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.





                    Array.prototype.forEach()



                    An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:



                    myArray.forEach(function(value, key, myArray) {
                    console.log(value);
                    });


                    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(myArray, function(key, value) {
                    console.log(value);
                    });


                    _.each(), in Underscore.js:



                    _.each(myArray, function(value, key, myArray) {
                    console.log(value);
                    });


                    _.forEach(), in Lodash.js:



                    _.forEach(myArray, function(value, key) {
                    console.log(value);
                    });





                    share|improve this answer






























                      53














                      Intro



                      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, and WHILE-loops.





                      A traditional for-loop



                      A traditional for loop has three components:





                      1. The initialization: executed before the look block is executed the first time


                      2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false


                      3. The afterthought: performed every time after the loop block is executed


                      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 minimal for loop possible:



                      for (;;) {
                      // Do stuff
                      }


                      Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-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:



                      for (var i = 0, length = 10; i < length; i++) {
                      console.log(i);
                      }




                      Using a traditional for loop to loop through an array



                      The traditional way to loop through an array, is this:



                      for (var i = 0, length = myArray.length; i < length; i++) {
                      console.log(myArray[i]);
                      }


                      Or, if you prefer to loop backwards, you do this:



                      for (var i = myArray.length - 1; i > -1; i--) {
                      console.log(myArray[i]);
                      }


                      There are, however, many variations possible, like for example this one:



                      for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
                      console.log(value);
                      }


                      ... or this one ...



                      var i = 0, length = myArray.length;
                      for (; i < length;) {
                      console.log(myArray[i]);
                      i++;
                      }


                      ... or this one:



                      var key = 0, value;
                      for (; value = myArray[key++];){
                      console.log(value);
                      }


                      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 loop



                      One alternative to a for loop is a while loop. To loop through an array, you could do this:



                      var key = 0;
                      while(value = myArray[key++]){
                      console.log(value);
                      }


                      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, the while loop hereabove behaves the exact same way as this for-loop:



                      for(var key = 0; value = myArray[key++];){
                      console.log(value);
                      }





                      For...in and for...of



                      In JavaScript, you can also do this:



                      for (i in myArray) {
                      console.log(myArray[i]);
                      }


                      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 for for...of. The following example shows the difference between a for...of loop and a for...in loop:



                      var myArray = [3, 5, 7];
                      myArray.foo = "hello";

                      for (var i in myArray) {
                      console.log(i); // logs 0, 1, 2, "foo"
                      }

                      for (var i of myArray) {
                      console.log(i); // logs 3, 5, 7
                      }


                      Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.





                      Array.prototype.forEach()



                      An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:



                      myArray.forEach(function(value, key, myArray) {
                      console.log(value);
                      });


                      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(myArray, function(key, value) {
                      console.log(value);
                      });


                      _.each(), in Underscore.js:



                      _.each(myArray, function(value, key, myArray) {
                      console.log(value);
                      });


                      _.forEach(), in Lodash.js:



                      _.forEach(myArray, function(value, key) {
                      console.log(value);
                      });





                      share|improve this answer




























                        53












                        53








                        53







                        Intro



                        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, and WHILE-loops.





                        A traditional for-loop



                        A traditional for loop has three components:





                        1. The initialization: executed before the look block is executed the first time


                        2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false


                        3. The afterthought: performed every time after the loop block is executed


                        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 minimal for loop possible:



                        for (;;) {
                        // Do stuff
                        }


                        Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-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:



                        for (var i = 0, length = 10; i < length; i++) {
                        console.log(i);
                        }




                        Using a traditional for loop to loop through an array



                        The traditional way to loop through an array, is this:



                        for (var i = 0, length = myArray.length; i < length; i++) {
                        console.log(myArray[i]);
                        }


                        Or, if you prefer to loop backwards, you do this:



                        for (var i = myArray.length - 1; i > -1; i--) {
                        console.log(myArray[i]);
                        }


                        There are, however, many variations possible, like for example this one:



                        for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
                        console.log(value);
                        }


                        ... or this one ...



                        var i = 0, length = myArray.length;
                        for (; i < length;) {
                        console.log(myArray[i]);
                        i++;
                        }


                        ... or this one:



                        var key = 0, value;
                        for (; value = myArray[key++];){
                        console.log(value);
                        }


                        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 loop



                        One alternative to a for loop is a while loop. To loop through an array, you could do this:



                        var key = 0;
                        while(value = myArray[key++]){
                        console.log(value);
                        }


                        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, the while loop hereabove behaves the exact same way as this for-loop:



                        for(var key = 0; value = myArray[key++];){
                        console.log(value);
                        }





                        For...in and for...of



                        In JavaScript, you can also do this:



                        for (i in myArray) {
                        console.log(myArray[i]);
                        }


                        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 for for...of. The following example shows the difference between a for...of loop and a for...in loop:



                        var myArray = [3, 5, 7];
                        myArray.foo = "hello";

                        for (var i in myArray) {
                        console.log(i); // logs 0, 1, 2, "foo"
                        }

                        for (var i of myArray) {
                        console.log(i); // logs 3, 5, 7
                        }


                        Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.





                        Array.prototype.forEach()



                        An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:



                        myArray.forEach(function(value, key, myArray) {
                        console.log(value);
                        });


                        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(myArray, function(key, value) {
                        console.log(value);
                        });


                        _.each(), in Underscore.js:



                        _.each(myArray, function(value, key, myArray) {
                        console.log(value);
                        });


                        _.forEach(), in Lodash.js:



                        _.forEach(myArray, function(value, key) {
                        console.log(value);
                        });





                        share|improve this answer















                        Intro



                        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, and WHILE-loops.





                        A traditional for-loop



                        A traditional for loop has three components:





                        1. The initialization: executed before the look block is executed the first time


                        2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false


                        3. The afterthought: performed every time after the loop block is executed


                        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 minimal for loop possible:



                        for (;;) {
                        // Do stuff
                        }


                        Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-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:



                        for (var i = 0, length = 10; i < length; i++) {
                        console.log(i);
                        }




                        Using a traditional for loop to loop through an array



                        The traditional way to loop through an array, is this:



                        for (var i = 0, length = myArray.length; i < length; i++) {
                        console.log(myArray[i]);
                        }


                        Or, if you prefer to loop backwards, you do this:



                        for (var i = myArray.length - 1; i > -1; i--) {
                        console.log(myArray[i]);
                        }


                        There are, however, many variations possible, like for example this one:



                        for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
                        console.log(value);
                        }


                        ... or this one ...



                        var i = 0, length = myArray.length;
                        for (; i < length;) {
                        console.log(myArray[i]);
                        i++;
                        }


                        ... or this one:



                        var key = 0, value;
                        for (; value = myArray[key++];){
                        console.log(value);
                        }


                        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 loop



                        One alternative to a for loop is a while loop. To loop through an array, you could do this:



                        var key = 0;
                        while(value = myArray[key++]){
                        console.log(value);
                        }


                        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, the while loop hereabove behaves the exact same way as this for-loop:



                        for(var key = 0; value = myArray[key++];){
                        console.log(value);
                        }





                        For...in and for...of



                        In JavaScript, you can also do this:



                        for (i in myArray) {
                        console.log(myArray[i]);
                        }


                        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 for for...of. The following example shows the difference between a for...of loop and a for...in loop:



                        var myArray = [3, 5, 7];
                        myArray.foo = "hello";

                        for (var i in myArray) {
                        console.log(i); // logs 0, 1, 2, "foo"
                        }

                        for (var i of myArray) {
                        console.log(i); // logs 3, 5, 7
                        }


                        Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.





                        Array.prototype.forEach()



                        An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:



                        myArray.forEach(function(value, key, myArray) {
                        console.log(value);
                        });


                        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(myArray, function(key, value) {
                        console.log(value);
                        });


                        _.each(), in Underscore.js:



                        _.each(myArray, function(value, key, myArray) {
                        console.log(value);
                        });


                        _.forEach(), in Lodash.js:



                        _.forEach(myArray, function(value, key) {
                        console.log(value);
                        });






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 14 '18 at 12:05

























                        answered Feb 29 '16 at 18:56









                        John SlegersJohn Slegers

                        28.3k13149132




                        28.3k13149132























                            36














                            If you want a terse way to write a fast loop and you can iterate in reverse:



                            for (var i=myArray.length;i--;){
                            var item=myArray[i];
                            }


                            This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.



                            There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.






                            share|improve this answer





















                            • 16





                              For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                              – Stijn de Witt
                              Mar 1 '13 at 12:09






                            • 5





                              falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                              – danwellman
                              Apr 27 '13 at 7:33






                            • 4





                              I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                              – Stijn de Witt
                              May 15 '14 at 17:23











                            • "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                              – Mouscellaneous
                              Jan 28 '16 at 8:54






                            • 1





                              @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                              – Phrogz
                              Jan 28 '16 at 18:33


















                            36














                            If you want a terse way to write a fast loop and you can iterate in reverse:



                            for (var i=myArray.length;i--;){
                            var item=myArray[i];
                            }


                            This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.



                            There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.






                            share|improve this answer





















                            • 16





                              For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                              – Stijn de Witt
                              Mar 1 '13 at 12:09






                            • 5





                              falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                              – danwellman
                              Apr 27 '13 at 7:33






                            • 4





                              I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                              – Stijn de Witt
                              May 15 '14 at 17:23











                            • "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                              – Mouscellaneous
                              Jan 28 '16 at 8:54






                            • 1





                              @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                              – Phrogz
                              Jan 28 '16 at 18:33
















                            36












                            36








                            36







                            If you want a terse way to write a fast loop and you can iterate in reverse:



                            for (var i=myArray.length;i--;){
                            var item=myArray[i];
                            }


                            This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.



                            There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.






                            share|improve this answer















                            If you want a terse way to write a fast loop and you can iterate in reverse:



                            for (var i=myArray.length;i--;){
                            var item=myArray[i];
                            }


                            This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.



                            There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 22 '15 at 17:16









                            falsarella

                            9,73545293




                            9,73545293










                            answered Jun 4 '12 at 16:26









                            PhrogzPhrogz

                            223k82544630




                            223k82544630








                            • 16





                              For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                              – Stijn de Witt
                              Mar 1 '13 at 12:09






                            • 5





                              falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                              – danwellman
                              Apr 27 '13 at 7:33






                            • 4





                              I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                              – Stijn de Witt
                              May 15 '14 at 17:23











                            • "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                              – Mouscellaneous
                              Jan 28 '16 at 8:54






                            • 1





                              @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                              – Phrogz
                              Jan 28 '16 at 18:33
















                            • 16





                              For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                              – Stijn de Witt
                              Mar 1 '13 at 12:09






                            • 5





                              falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                              – danwellman
                              Apr 27 '13 at 7:33






                            • 4





                              I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                              – Stijn de Witt
                              May 15 '14 at 17:23











                            • "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                              – Mouscellaneous
                              Jan 28 '16 at 8:54






                            • 1





                              @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                              – Phrogz
                              Jan 28 '16 at 18:33










                            16




                            16





                            For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                            – Stijn de Witt
                            Mar 1 '13 at 12:09





                            For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

                            – Stijn de Witt
                            Mar 1 '13 at 12:09




                            5




                            5





                            falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                            – danwellman
                            Apr 27 '13 at 7:33





                            falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

                            – danwellman
                            Apr 27 '13 at 7:33




                            4




                            4





                            I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                            – Stijn de Witt
                            May 15 '14 at 17:23





                            I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

                            – Stijn de Witt
                            May 15 '14 at 17:23













                            "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                            – Mouscellaneous
                            Jan 28 '16 at 8:54





                            "Caching the length"? The length is stored as an integer in the array, it's not measured every time you access it. There's no benefit here in copying the value of length into another variable.

                            – Mouscellaneous
                            Jan 28 '16 at 8:54




                            1




                            1





                            @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                            – Phrogz
                            Jan 28 '16 at 18:33







                            @Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

                            – Phrogz
                            Jan 28 '16 at 18:33













                            28














                            Some use cases of looping through an array in the functional programming way in JavaScript:



                            1. Just loop through an array



                            const myArray = [{x:100}, {x:200}, {x:300}];

                            myArray.forEach((element, index, array) => {
                            console.log(element.x); // 100, 200, 300
                            console.log(index); // 0, 1, 2
                            console.log(array); // same myArray object 3 times
                            });


                            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



                            const people = [
                            {name: 'John', age: 23},
                            {name: 'Andrew', age: 3},
                            {name: 'Peter', age: 8},
                            {name: 'Hanna', age: 14},
                            {name: 'Adam', age: 37}];

                            const anyAdult = people.some(person => person.age >= 18);
                            console.log(anyAdult); // true


                            3. Transform to a new array



                            const myArray = [{x:100}, {x:200}, {x:300}];

                            const newArray= myArray.map(element => element.x);
                            console.log(newArray); // [100, 200, 300]


                            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



                            const myArray = [{x:100}, {x:200}, {x:300}];

                            const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
                            console.log(sum); // 600 = 0 + 100 + 200 + 300

                            const average = sum / myArray.length;
                            console.log(average); // 200


                            5. Create a new array based on the original but without modifying it



                            const myArray = [{x:100}, {x:200}, {x:300}];

                            const newArray= myArray.map(element => {
                            return {
                            ...element,
                            x: element.x * 2
                            };
                            });

                            console.log(myArray); // [100, 200, 300]
                            console.log(newArray); // [200, 400, 600]


                            6. Count the number of each category



                            const people = [
                            {name: 'John', group: 'A'},
                            {name: 'Andrew', group: 'C'},
                            {name: 'Peter', group: 'A'},
                            {name: 'James', group: 'B'},
                            {name: 'Hanna', group: 'A'},
                            {name: 'Adam', group: 'B'}];

                            const groupInfo = people.reduce((groups, person) => {
                            const {A = 0, B = 0, C = 0} = groups;
                            if (person.group === 'A') {
                            return {...groups, A: A + 1};
                            } else if (person.group === 'B') {
                            return {...groups, B: B + 1};
                            } else {
                            return {...groups, C: C + 1};
                            }
                            }, {});

                            console.log(groupInfo); // {A: 3, C: 1, B: 2}


                            7. Retrieve a subset of an array based on particular criteria



                            const myArray = [{x:100}, {x:200}, {x:300}];

                            const newArray = myArray.filter(element => element.x > 250);
                            console.log(newArray); // [{x:300}]


                            Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.



                            8. Sort an array



                            const people = [
                            { name: "John", age: 21 },
                            { name: "Peter", age: 31 },
                            { name: "Andrew", age: 29 },
                            { name: "Thomas", age: 25 }
                            ];

                            let sortByAge = people.sort(function (p1, p2) {
                            return p1.age - p2.age;
                            });

                            console.log(sortByAge);


                            enter image description here



                            9. Find an element in an array



                            const people = [ {name: "john", age:23},
                            {name: "john", age:43},
                            {name: "jim", age:101},
                            {name: "bob", age:67} ];

                            const john = people.find(person => person.name === 'john');
                            console.log(john);


                            enter image description here



                            The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.



                            References




                            • Array.prototype.some()

                            • Array.prototype.forEach()

                            • Array.prototype.map()

                            • Array.prototype.filter()

                            • Array.prototype.sort()

                            • Spread syntax

                            • Array.prototype.find()






                            share|improve this answer






























                              28














                              Some use cases of looping through an array in the functional programming way in JavaScript:



                              1. Just loop through an array



                              const myArray = [{x:100}, {x:200}, {x:300}];

                              myArray.forEach((element, index, array) => {
                              console.log(element.x); // 100, 200, 300
                              console.log(index); // 0, 1, 2
                              console.log(array); // same myArray object 3 times
                              });


                              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



                              const people = [
                              {name: 'John', age: 23},
                              {name: 'Andrew', age: 3},
                              {name: 'Peter', age: 8},
                              {name: 'Hanna', age: 14},
                              {name: 'Adam', age: 37}];

                              const anyAdult = people.some(person => person.age >= 18);
                              console.log(anyAdult); // true


                              3. Transform to a new array



                              const myArray = [{x:100}, {x:200}, {x:300}];

                              const newArray= myArray.map(element => element.x);
                              console.log(newArray); // [100, 200, 300]


                              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



                              const myArray = [{x:100}, {x:200}, {x:300}];

                              const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
                              console.log(sum); // 600 = 0 + 100 + 200 + 300

                              const average = sum / myArray.length;
                              console.log(average); // 200


                              5. Create a new array based on the original but without modifying it



                              const myArray = [{x:100}, {x:200}, {x:300}];

                              const newArray= myArray.map(element => {
                              return {
                              ...element,
                              x: element.x * 2
                              };
                              });

                              console.log(myArray); // [100, 200, 300]
                              console.log(newArray); // [200, 400, 600]


                              6. Count the number of each category



                              const people = [
                              {name: 'John', group: 'A'},
                              {name: 'Andrew', group: 'C'},
                              {name: 'Peter', group: 'A'},
                              {name: 'James', group: 'B'},
                              {name: 'Hanna', group: 'A'},
                              {name: 'Adam', group: 'B'}];

                              const groupInfo = people.reduce((groups, person) => {
                              const {A = 0, B = 0, C = 0} = groups;
                              if (person.group === 'A') {
                              return {...groups, A: A + 1};
                              } else if (person.group === 'B') {
                              return {...groups, B: B + 1};
                              } else {
                              return {...groups, C: C + 1};
                              }
                              }, {});

                              console.log(groupInfo); // {A: 3, C: 1, B: 2}


                              7. Retrieve a subset of an array based on particular criteria



                              const myArray = [{x:100}, {x:200}, {x:300}];

                              const newArray = myArray.filter(element => element.x > 250);
                              console.log(newArray); // [{x:300}]


                              Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.



                              8. Sort an array



                              const people = [
                              { name: "John", age: 21 },
                              { name: "Peter", age: 31 },
                              { name: "Andrew", age: 29 },
                              { name: "Thomas", age: 25 }
                              ];

                              let sortByAge = people.sort(function (p1, p2) {
                              return p1.age - p2.age;
                              });

                              console.log(sortByAge);


                              enter image description here



                              9. Find an element in an array



                              const people = [ {name: "john", age:23},
                              {name: "john", age:43},
                              {name: "jim", age:101},
                              {name: "bob", age:67} ];

                              const john = people.find(person => person.name === 'john');
                              console.log(john);


                              enter image description here



                              The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.



                              References




                              • Array.prototype.some()

                              • Array.prototype.forEach()

                              • Array.prototype.map()

                              • Array.prototype.filter()

                              • Array.prototype.sort()

                              • Spread syntax

                              • Array.prototype.find()






                              share|improve this answer




























                                28












                                28








                                28







                                Some use cases of looping through an array in the functional programming way in JavaScript:



                                1. Just loop through an array



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                myArray.forEach((element, index, array) => {
                                console.log(element.x); // 100, 200, 300
                                console.log(index); // 0, 1, 2
                                console.log(array); // same myArray object 3 times
                                });


                                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



                                const people = [
                                {name: 'John', age: 23},
                                {name: 'Andrew', age: 3},
                                {name: 'Peter', age: 8},
                                {name: 'Hanna', age: 14},
                                {name: 'Adam', age: 37}];

                                const anyAdult = people.some(person => person.age >= 18);
                                console.log(anyAdult); // true


                                3. Transform to a new array



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray= myArray.map(element => element.x);
                                console.log(newArray); // [100, 200, 300]


                                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



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
                                console.log(sum); // 600 = 0 + 100 + 200 + 300

                                const average = sum / myArray.length;
                                console.log(average); // 200


                                5. Create a new array based on the original but without modifying it



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray= myArray.map(element => {
                                return {
                                ...element,
                                x: element.x * 2
                                };
                                });

                                console.log(myArray); // [100, 200, 300]
                                console.log(newArray); // [200, 400, 600]


                                6. Count the number of each category



                                const people = [
                                {name: 'John', group: 'A'},
                                {name: 'Andrew', group: 'C'},
                                {name: 'Peter', group: 'A'},
                                {name: 'James', group: 'B'},
                                {name: 'Hanna', group: 'A'},
                                {name: 'Adam', group: 'B'}];

                                const groupInfo = people.reduce((groups, person) => {
                                const {A = 0, B = 0, C = 0} = groups;
                                if (person.group === 'A') {
                                return {...groups, A: A + 1};
                                } else if (person.group === 'B') {
                                return {...groups, B: B + 1};
                                } else {
                                return {...groups, C: C + 1};
                                }
                                }, {});

                                console.log(groupInfo); // {A: 3, C: 1, B: 2}


                                7. Retrieve a subset of an array based on particular criteria



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray = myArray.filter(element => element.x > 250);
                                console.log(newArray); // [{x:300}]


                                Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.



                                8. Sort an array



                                const people = [
                                { name: "John", age: 21 },
                                { name: "Peter", age: 31 },
                                { name: "Andrew", age: 29 },
                                { name: "Thomas", age: 25 }
                                ];

                                let sortByAge = people.sort(function (p1, p2) {
                                return p1.age - p2.age;
                                });

                                console.log(sortByAge);


                                enter image description here



                                9. Find an element in an array



                                const people = [ {name: "john", age:23},
                                {name: "john", age:43},
                                {name: "jim", age:101},
                                {name: "bob", age:67} ];

                                const john = people.find(person => person.name === 'john');
                                console.log(john);


                                enter image description here



                                The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.



                                References




                                • Array.prototype.some()

                                • Array.prototype.forEach()

                                • Array.prototype.map()

                                • Array.prototype.filter()

                                • Array.prototype.sort()

                                • Spread syntax

                                • Array.prototype.find()






                                share|improve this answer















                                Some use cases of looping through an array in the functional programming way in JavaScript:



                                1. Just loop through an array



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                myArray.forEach((element, index, array) => {
                                console.log(element.x); // 100, 200, 300
                                console.log(index); // 0, 1, 2
                                console.log(array); // same myArray object 3 times
                                });


                                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



                                const people = [
                                {name: 'John', age: 23},
                                {name: 'Andrew', age: 3},
                                {name: 'Peter', age: 8},
                                {name: 'Hanna', age: 14},
                                {name: 'Adam', age: 37}];

                                const anyAdult = people.some(person => person.age >= 18);
                                console.log(anyAdult); // true


                                3. Transform to a new array



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray= myArray.map(element => element.x);
                                console.log(newArray); // [100, 200, 300]


                                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



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
                                console.log(sum); // 600 = 0 + 100 + 200 + 300

                                const average = sum / myArray.length;
                                console.log(average); // 200


                                5. Create a new array based on the original but without modifying it



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray= myArray.map(element => {
                                return {
                                ...element,
                                x: element.x * 2
                                };
                                });

                                console.log(myArray); // [100, 200, 300]
                                console.log(newArray); // [200, 400, 600]


                                6. Count the number of each category



                                const people = [
                                {name: 'John', group: 'A'},
                                {name: 'Andrew', group: 'C'},
                                {name: 'Peter', group: 'A'},
                                {name: 'James', group: 'B'},
                                {name: 'Hanna', group: 'A'},
                                {name: 'Adam', group: 'B'}];

                                const groupInfo = people.reduce((groups, person) => {
                                const {A = 0, B = 0, C = 0} = groups;
                                if (person.group === 'A') {
                                return {...groups, A: A + 1};
                                } else if (person.group === 'B') {
                                return {...groups, B: B + 1};
                                } else {
                                return {...groups, C: C + 1};
                                }
                                }, {});

                                console.log(groupInfo); // {A: 3, C: 1, B: 2}


                                7. Retrieve a subset of an array based on particular criteria



                                const myArray = [{x:100}, {x:200}, {x:300}];

                                const newArray = myArray.filter(element => element.x > 250);
                                console.log(newArray); // [{x:300}]


                                Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.



                                8. Sort an array



                                const people = [
                                { name: "John", age: 21 },
                                { name: "Peter", age: 31 },
                                { name: "Andrew", age: 29 },
                                { name: "Thomas", age: 25 }
                                ];

                                let sortByAge = people.sort(function (p1, p2) {
                                return p1.age - p2.age;
                                });

                                console.log(sortByAge);


                                enter image description here



                                9. Find an element in an array



                                const people = [ {name: "john", age:23},
                                {name: "john", age:43},
                                {name: "jim", age:101},
                                {name: "bob", age:67} ];

                                const john = people.find(person => person.name === 'john');
                                console.log(john);


                                enter image description here



                                The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.



                                References




                                • Array.prototype.some()

                                • Array.prototype.forEach()

                                • Array.prototype.map()

                                • Array.prototype.filter()

                                • Array.prototype.sort()

                                • Spread syntax

                                • Array.prototype.find()







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Jul 29 '18 at 10:36

























                                answered Feb 23 '18 at 11:29









                                YuciYuci

                                4,2363137




                                4,2363137























                                    26














                                    There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.



                                    var i = 0,
                                    item;

                                    // note this is weak to sparse arrays or falsey values
                                    for ( ; item = myStringArray[i++] ; ){
                                    item; // This is the string at the index.
                                    }


                                    Or if you really want to get the id and have a really classical for loop:



                                    var i = 0,
                                    len = myStringArray.length; // cache the length

                                    for ( ; i < len ; i++ ){
                                    myStringArray[i]; // Don't use this if you plan on changing the length of the array
                                    }


                                    Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.






                                    share|improve this answer





















                                    • 3





                                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                      – Phrogz
                                      Jun 4 '12 at 16:28











                                    • Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                      – Gabriel
                                      Jun 26 '12 at 1:43






                                    • 1





                                      @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                      – Stijn de Witt
                                      Mar 31 '13 at 19:06






                                    • 1





                                      @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                      – Gabriel
                                      Apr 4 '13 at 17:15






                                    • 1





                                      @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                      – Noz
                                      Jul 30 '14 at 18:14
















                                    26














                                    There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.



                                    var i = 0,
                                    item;

                                    // note this is weak to sparse arrays or falsey values
                                    for ( ; item = myStringArray[i++] ; ){
                                    item; // This is the string at the index.
                                    }


                                    Or if you really want to get the id and have a really classical for loop:



                                    var i = 0,
                                    len = myStringArray.length; // cache the length

                                    for ( ; i < len ; i++ ){
                                    myStringArray[i]; // Don't use this if you plan on changing the length of the array
                                    }


                                    Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.






                                    share|improve this answer





















                                    • 3





                                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                      – Phrogz
                                      Jun 4 '12 at 16:28











                                    • Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                      – Gabriel
                                      Jun 26 '12 at 1:43






                                    • 1





                                      @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                      – Stijn de Witt
                                      Mar 31 '13 at 19:06






                                    • 1





                                      @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                      – Gabriel
                                      Apr 4 '13 at 17:15






                                    • 1





                                      @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                      – Noz
                                      Jul 30 '14 at 18:14














                                    26












                                    26








                                    26







                                    There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.



                                    var i = 0,
                                    item;

                                    // note this is weak to sparse arrays or falsey values
                                    for ( ; item = myStringArray[i++] ; ){
                                    item; // This is the string at the index.
                                    }


                                    Or if you really want to get the id and have a really classical for loop:



                                    var i = 0,
                                    len = myStringArray.length; // cache the length

                                    for ( ; i < len ; i++ ){
                                    myStringArray[i]; // Don't use this if you plan on changing the length of the array
                                    }


                                    Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.






                                    share|improve this answer















                                    There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.



                                    var i = 0,
                                    item;

                                    // note this is weak to sparse arrays or falsey values
                                    for ( ; item = myStringArray[i++] ; ){
                                    item; // This is the string at the index.
                                    }


                                    Or if you really want to get the id and have a really classical for loop:



                                    var i = 0,
                                    len = myStringArray.length; // cache the length

                                    for ( ; i < len ; i++ ){
                                    myStringArray[i]; // Don't use this if you plan on changing the length of the array
                                    }


                                    Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Aug 4 '14 at 5:15

























                                    answered May 16 '11 at 22:52









                                    GabrielGabriel

                                    13.6k23040




                                    13.6k23040








                                    • 3





                                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                      – Phrogz
                                      Jun 4 '12 at 16:28











                                    • Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                      – Gabriel
                                      Jun 26 '12 at 1:43






                                    • 1





                                      @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                      – Stijn de Witt
                                      Mar 31 '13 at 19:06






                                    • 1





                                      @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                      – Gabriel
                                      Apr 4 '13 at 17:15






                                    • 1





                                      @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                      – Noz
                                      Jul 30 '14 at 18:14














                                    • 3





                                      Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                      – Phrogz
                                      Jun 4 '12 at 16:28











                                    • Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                      – Gabriel
                                      Jun 26 '12 at 1:43






                                    • 1





                                      @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                      – Stijn de Witt
                                      Mar 31 '13 at 19:06






                                    • 1





                                      @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                      – Gabriel
                                      Apr 4 '13 at 17:15






                                    • 1





                                      @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                      – Noz
                                      Jul 30 '14 at 18:14








                                    3




                                    3





                                    Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                    – Phrogz
                                    Jun 4 '12 at 16:28





                                    Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

                                    – Phrogz
                                    Jun 4 '12 at 16:28













                                    Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                    – Gabriel
                                    Jun 26 '12 at 1:43





                                    Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

                                    – Gabriel
                                    Jun 26 '12 at 1:43




                                    1




                                    1





                                    @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                    – Stijn de Witt
                                    Mar 31 '13 at 19:06





                                    @Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

                                    – Stijn de Witt
                                    Mar 31 '13 at 19:06




                                    1




                                    1





                                    @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                    – Gabriel
                                    Apr 4 '13 at 17:15





                                    @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

                                    – Gabriel
                                    Apr 4 '13 at 17:15




                                    1




                                    1





                                    @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                    – Noz
                                    Jul 30 '14 at 18:14





                                    @Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

                                    – Noz
                                    Jul 30 '14 at 18:14











                                    26














                                    There are various way to loop through array in JavaScript.



                                    Generic loop:



                                    var i;
                                    for (i = 0; i < substr.length; ++i) {
                                    // Do something with `substr[i]`
                                    }


                                    ES5's forEach:



                                    substr.forEach(function(item) {
                                    // Do something with `item`
                                    });


                                    jQuery.each:



                                    jQuery.each(substr, function(index, item) {
                                    // Do something with `item` (or `this` is also `item` if you like)
                                    });


                                    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.






                                    share|improve this answer





















                                    • 4





                                      It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                      – Pete
                                      Dec 30 '14 at 2:33
















                                    26














                                    There are various way to loop through array in JavaScript.



                                    Generic loop:



                                    var i;
                                    for (i = 0; i < substr.length; ++i) {
                                    // Do something with `substr[i]`
                                    }


                                    ES5's forEach:



                                    substr.forEach(function(item) {
                                    // Do something with `item`
                                    });


                                    jQuery.each:



                                    jQuery.each(substr, function(index, item) {
                                    // Do something with `item` (or `this` is also `item` if you like)
                                    });


                                    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.






                                    share|improve this answer





















                                    • 4





                                      It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                      – Pete
                                      Dec 30 '14 at 2:33














                                    26












                                    26








                                    26







                                    There are various way to loop through array in JavaScript.



                                    Generic loop:



                                    var i;
                                    for (i = 0; i < substr.length; ++i) {
                                    // Do something with `substr[i]`
                                    }


                                    ES5's forEach:



                                    substr.forEach(function(item) {
                                    // Do something with `item`
                                    });


                                    jQuery.each:



                                    jQuery.each(substr, function(index, item) {
                                    // Do something with `item` (or `this` is also `item` if you like)
                                    });


                                    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.






                                    share|improve this answer















                                    There are various way to loop through array in JavaScript.



                                    Generic loop:



                                    var i;
                                    for (i = 0; i < substr.length; ++i) {
                                    // Do something with `substr[i]`
                                    }


                                    ES5's forEach:



                                    substr.forEach(function(item) {
                                    // Do something with `item`
                                    });


                                    jQuery.each:



                                    jQuery.each(substr, function(index, item) {
                                    // Do something with `item` (or `this` is also `item` if you like)
                                    });


                                    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.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 23 '17 at 10:31









                                    Community

                                    11




                                    11










                                    answered Jul 23 '14 at 12:59









                                    RizN81RizN81

                                    7971322




                                    7971322








                                    • 4





                                      It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                      – Pete
                                      Dec 30 '14 at 2:33














                                    • 4





                                      It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                      – Pete
                                      Dec 30 '14 at 2:33








                                    4




                                    4





                                    It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                    – Pete
                                    Dec 30 '14 at 2:33





                                    It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

                                    – Pete
                                    Dec 30 '14 at 2:33











                                    25














                                    I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.



                                    For instance:



                                    _.each([1, 2, 3], function(num){ alert(num); });
                                    => alerts each number in turn...





                                    share|improve this answer



















                                    • 7





                                      For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                      – Mark Reed
                                      Oct 11 '13 at 10:59






                                    • 3





                                      Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                      – Walter Chapilliquen - wZVanG
                                      Jun 23 '15 at 23:32
















                                    25














                                    I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.



                                    For instance:



                                    _.each([1, 2, 3], function(num){ alert(num); });
                                    => alerts each number in turn...





                                    share|improve this answer



















                                    • 7





                                      For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                      – Mark Reed
                                      Oct 11 '13 at 10:59






                                    • 3





                                      Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                      – Walter Chapilliquen - wZVanG
                                      Jun 23 '15 at 23:32














                                    25












                                    25








                                    25







                                    I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.



                                    For instance:



                                    _.each([1, 2, 3], function(num){ alert(num); });
                                    => alerts each number in turn...





                                    share|improve this answer













                                    I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.



                                    For instance:



                                    _.each([1, 2, 3], function(num){ alert(num); });
                                    => alerts each number in turn...






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Apr 16 '12 at 23:33









                                    Andrew ThomsonAndrew Thomson

                                    1,97921215




                                    1,97921215








                                    • 7





                                      For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                      – Mark Reed
                                      Oct 11 '13 at 10:59






                                    • 3





                                      Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                      – Walter Chapilliquen - wZVanG
                                      Jun 23 '15 at 23:32














                                    • 7





                                      For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                      – Mark Reed
                                      Oct 11 '13 at 10:59






                                    • 3





                                      Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                      – Walter Chapilliquen - wZVanG
                                      Jun 23 '15 at 23:32








                                    7




                                    7





                                    For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                    – Mark Reed
                                    Oct 11 '13 at 10:59





                                    For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

                                    – Mark Reed
                                    Oct 11 '13 at 10:59




                                    3




                                    3





                                    Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                    – Walter Chapilliquen - wZVanG
                                    Jun 23 '15 at 23:32





                                    Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

                                    – Walter Chapilliquen - wZVanG
                                    Jun 23 '15 at 23:32











                                    24














                                    Array loop:



                                    for(var i = 0; i < things.length; i++){
                                    var thing = things[i];
                                    console.log(thing);
                                    }


                                    Object loop:



                                    for(var prop in obj){
                                    var propValue = obj[prop];
                                    console.log(propValue);
                                    }





                                    share|improve this answer






























                                      24














                                      Array loop:



                                      for(var i = 0; i < things.length; i++){
                                      var thing = things[i];
                                      console.log(thing);
                                      }


                                      Object loop:



                                      for(var prop in obj){
                                      var propValue = obj[prop];
                                      console.log(propValue);
                                      }





                                      share|improve this answer




























                                        24












                                        24








                                        24







                                        Array loop:



                                        for(var i = 0; i < things.length; i++){
                                        var thing = things[i];
                                        console.log(thing);
                                        }


                                        Object loop:



                                        for(var prop in obj){
                                        var propValue = obj[prop];
                                        console.log(propValue);
                                        }





                                        share|improve this answer















                                        Array loop:



                                        for(var i = 0; i < things.length; i++){
                                        var thing = things[i];
                                        console.log(thing);
                                        }


                                        Object loop:



                                        for(var prop in obj){
                                        var propValue = obj[prop];
                                        console.log(propValue);
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited May 21 '17 at 11:05









                                        Peter Mortensen

                                        13.7k1986113




                                        13.7k1986113










                                        answered Aug 1 '16 at 21:18









                                        bzimbzim

                                        763514




                                        763514























                                            22














                                            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:



                                            var arr = [1, 2, 3, 4, 5];


                                            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:



                                            for (var i=0, l=arr.length; i<l; i++) { 
                                            console.log(arr[i]);
                                            }


                                            2) While loop



                                            While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:



                                            let i=0;

                                            while (arr.length>i) {
                                            console.log(arr[i]);
                                            i++;
                                            }


                                            3) Do while

                                            Do while doing the same thing as while with some syntax difference as below:



                                            let i=0;
                                            do {
                                            console.log(arr[i]);
                                            i++;
                                            }
                                            while (arr.length>i);


                                            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 using while and for.



                                            This is good article if you like to learn more about the async functions over arrays in JavaScript.




                                            Functional programming has been making quite a splash in the
                                            development world these days. And for good reason: Functional
                                            techniques can help you write more declarative code that is easier to
                                            understand at a glance, refactor, and test.



                                            One of the cornerstones of functional programming is its special use
                                            of lists and list operations. And those things are exactly what the
                                            sound like they are: arrays of things, and the stuff you do to them.
                                            But the functional mindset treats them a bit differently than you
                                            might expect.



                                            This article will take a close look at what I like to call the "big
                                            three" list operations: map, filter, and reduce. Wrapping your head
                                            around these three functions is an important step towards being able
                                            to write clean functional code, and opens the doors to the vastly
                                            powerful techniques of functional and reactive programming.



                                            It also means you'll never have to write a for loop again.




                                            Read more>> here:






                                            share|improve this answer


























                                            • Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                              – shea
                                              Jun 29 '17 at 8:33
















                                            22














                                            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:



                                            var arr = [1, 2, 3, 4, 5];


                                            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:



                                            for (var i=0, l=arr.length; i<l; i++) { 
                                            console.log(arr[i]);
                                            }


                                            2) While loop



                                            While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:



                                            let i=0;

                                            while (arr.length>i) {
                                            console.log(arr[i]);
                                            i++;
                                            }


                                            3) Do while

                                            Do while doing the same thing as while with some syntax difference as below:



                                            let i=0;
                                            do {
                                            console.log(arr[i]);
                                            i++;
                                            }
                                            while (arr.length>i);


                                            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 using while and for.



                                            This is good article if you like to learn more about the async functions over arrays in JavaScript.




                                            Functional programming has been making quite a splash in the
                                            development world these days. And for good reason: Functional
                                            techniques can help you write more declarative code that is easier to
                                            understand at a glance, refactor, and test.



                                            One of the cornerstones of functional programming is its special use
                                            of lists and list operations. And those things are exactly what the
                                            sound like they are: arrays of things, and the stuff you do to them.
                                            But the functional mindset treats them a bit differently than you
                                            might expect.



                                            This article will take a close look at what I like to call the "big
                                            three" list operations: map, filter, and reduce. Wrapping your head
                                            around these three functions is an important step towards being able
                                            to write clean functional code, and opens the doors to the vastly
                                            powerful techniques of functional and reactive programming.



                                            It also means you'll never have to write a for loop again.




                                            Read more>> here:






                                            share|improve this answer


























                                            • Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                              – shea
                                              Jun 29 '17 at 8:33














                                            22












                                            22








                                            22







                                            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:



                                            var arr = [1, 2, 3, 4, 5];


                                            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:



                                            for (var i=0, l=arr.length; i<l; i++) { 
                                            console.log(arr[i]);
                                            }


                                            2) While loop



                                            While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:



                                            let i=0;

                                            while (arr.length>i) {
                                            console.log(arr[i]);
                                            i++;
                                            }


                                            3) Do while

                                            Do while doing the same thing as while with some syntax difference as below:



                                            let i=0;
                                            do {
                                            console.log(arr[i]);
                                            i++;
                                            }
                                            while (arr.length>i);


                                            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 using while and for.



                                            This is good article if you like to learn more about the async functions over arrays in JavaScript.




                                            Functional programming has been making quite a splash in the
                                            development world these days. And for good reason: Functional
                                            techniques can help you write more declarative code that is easier to
                                            understand at a glance, refactor, and test.



                                            One of the cornerstones of functional programming is its special use
                                            of lists and list operations. And those things are exactly what the
                                            sound like they are: arrays of things, and the stuff you do to them.
                                            But the functional mindset treats them a bit differently than you
                                            might expect.



                                            This article will take a close look at what I like to call the "big
                                            three" list operations: map, filter, and reduce. Wrapping your head
                                            around these three functions is an important step towards being able
                                            to write clean functional code, and opens the doors to the vastly
                                            powerful techniques of functional and reactive programming.



                                            It also means you'll never have to write a for loop again.




                                            Read more>> here:






                                            share|improve this answer















                                            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:



                                            var arr = [1, 2, 3, 4, 5];


                                            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:



                                            for (var i=0, l=arr.length; i<l; i++) { 
                                            console.log(arr[i]);
                                            }


                                            2) While loop



                                            While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:



                                            let i=0;

                                            while (arr.length>i) {
                                            console.log(arr[i]);
                                            i++;
                                            }


                                            3) Do while

                                            Do while doing the same thing as while with some syntax difference as below:



                                            let i=0;
                                            do {
                                            console.log(arr[i]);
                                            i++;
                                            }
                                            while (arr.length>i);


                                            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 using while and for.



                                            This is good article if you like to learn more about the async functions over arrays in JavaScript.




                                            Functional programming has been making quite a splash in the
                                            development world these days. And for good reason: Functional
                                            techniques can help you write more declarative code that is easier to
                                            understand at a glance, refactor, and test.



                                            One of the cornerstones of functional programming is its special use
                                            of lists and list operations. And those things are exactly what the
                                            sound like they are: arrays of things, and the stuff you do to them.
                                            But the functional mindset treats them a bit differently than you
                                            might expect.



                                            This article will take a close look at what I like to call the "big
                                            three" list operations: map, filter, and reduce. Wrapping your head
                                            around these three functions is an important step towards being able
                                            to write clean functional code, and opens the doors to the vastly
                                            powerful techniques of functional and reactive programming.



                                            It also means you'll never have to write a for loop again.




                                            Read more>> here:







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jan 18 '18 at 1:19

























                                            answered May 27 '17 at 2:57









                                            AlirezaAlireza

                                            50.2k13173123




                                            50.2k13173123













                                            • Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                              – shea
                                              Jun 29 '17 at 8:33



















                                            • Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                              – shea
                                              Jun 29 '17 at 8:33

















                                            Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                            – shea
                                            Jun 29 '17 at 8:33





                                            Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

                                            – shea
                                            Jun 29 '17 at 8:33











                                            19














                                            If you're using the jQuery library, consider using
                                            http://api.jquery.com/jQuery.each/



                                            From the documentation:




                                            jQuery.each( collection, callback(indexInArray, valueOfElement) )



                                            Returns: Object



                                            Description: A generic iterator function, which can be used to
                                            seamlessly iterate over both objects and arrays. Arrays and array-like
                                            objects with a length property (such as a function's arguments object)
                                            are iterated by numeric index, from 0 to length-1. Other objects are
                                            iterated via their named properties.



                                            The $.each() function is not the same as $(selector).each(), which is
                                            used to iterate, exclusively, over a jQuery object. The $.each()
                                            function can be used to iterate over any collection, whether it is a
                                            map (JavaScript object) or an array. In the case of an array, the
                                            callback is passed an array index and a corresponding array value each
                                            time. (The value can also be accessed through the this keyword, but
                                            Javascript will always wrap the this value as an Object even if it is
                                            a simple string or number value.) The method returns its first
                                            argument, the object that was iterated.







                                            share|improve this answer





















                                            • 7





                                              jQuery for everything?

                                              – Exception
                                              Feb 7 '13 at 19:03






                                            • 6





                                              Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                              – Stijn de Witt
                                              Mar 31 '13 at 19:04






                                            • 1





                                              Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                              – Stijn de Witt
                                              Jun 5 '17 at 10:50
















                                            19














                                            If you're using the jQuery library, consider using
                                            http://api.jquery.com/jQuery.each/



                                            From the documentation:




                                            jQuery.each( collection, callback(indexInArray, valueOfElement) )



                                            Returns: Object



                                            Description: A generic iterator function, which can be used to
                                            seamlessly iterate over both objects and arrays. Arrays and array-like
                                            objects with a length property (such as a function's arguments object)
                                            are iterated by numeric index, from 0 to length-1. Other objects are
                                            iterated via their named properties.



                                            The $.each() function is not the same as $(selector).each(), which is
                                            used to iterate, exclusively, over a jQuery object. The $.each()
                                            function can be used to iterate over any collection, whether it is a
                                            map (JavaScript object) or an array. In the case of an array, the
                                            callback is passed an array index and a corresponding array value each
                                            time. (The value can also be accessed through the this keyword, but
                                            Javascript will always wrap the this value as an Object even if it is
                                            a simple string or number value.) The method returns its first
                                            argument, the object that was iterated.







                                            share|improve this answer





















                                            • 7





                                              jQuery for everything?

                                              – Exception
                                              Feb 7 '13 at 19:03






                                            • 6





                                              Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                              – Stijn de Witt
                                              Mar 31 '13 at 19:04






                                            • 1





                                              Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                              – Stijn de Witt
                                              Jun 5 '17 at 10:50














                                            19












                                            19








                                            19







                                            If you're using the jQuery library, consider using
                                            http://api.jquery.com/jQuery.each/



                                            From the documentation:




                                            jQuery.each( collection, callback(indexInArray, valueOfElement) )



                                            Returns: Object



                                            Description: A generic iterator function, which can be used to
                                            seamlessly iterate over both objects and arrays. Arrays and array-like
                                            objects with a length property (such as a function's arguments object)
                                            are iterated by numeric index, from 0 to length-1. Other objects are
                                            iterated via their named properties.



                                            The $.each() function is not the same as $(selector).each(), which is
                                            used to iterate, exclusively, over a jQuery object. The $.each()
                                            function can be used to iterate over any collection, whether it is a
                                            map (JavaScript object) or an array. In the case of an array, the
                                            callback is passed an array index and a corresponding array value each
                                            time. (The value can also be accessed through the this keyword, but
                                            Javascript will always wrap the this value as an Object even if it is
                                            a simple string or number value.) The method returns its first
                                            argument, the object that was iterated.







                                            share|improve this answer















                                            If you're using the jQuery library, consider using
                                            http://api.jquery.com/jQuery.each/



                                            From the documentation:




                                            jQuery.each( collection, callback(indexInArray, valueOfElement) )



                                            Returns: Object



                                            Description: A generic iterator function, which can be used to
                                            seamlessly iterate over both objects and arrays. Arrays and array-like
                                            objects with a length property (such as a function's arguments object)
                                            are iterated by numeric index, from 0 to length-1. Other objects are
                                            iterated via their named properties.



                                            The $.each() function is not the same as $(selector).each(), which is
                                            used to iterate, exclusively, over a jQuery object. The $.each()
                                            function can be used to iterate over any collection, whether it is a
                                            map (JavaScript object) or an array. In the case of an array, the
                                            callback is passed an array index and a corresponding array value each
                                            time. (The value can also be accessed through the this keyword, but
                                            Javascript will always wrap the this value as an Object even if it is
                                            a simple string or number value.) The method returns its first
                                            argument, the object that was iterated.








                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Dec 22 '15 at 17:12









                                            falsarella

                                            9,73545293




                                            9,73545293










                                            answered Oct 21 '12 at 6:20









                                            justingordonjustingordon

                                            6,49564798




                                            6,49564798








                                            • 7





                                              jQuery for everything?

                                              – Exception
                                              Feb 7 '13 at 19:03






                                            • 6





                                              Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                              – Stijn de Witt
                                              Mar 31 '13 at 19:04






                                            • 1





                                              Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                              – Stijn de Witt
                                              Jun 5 '17 at 10:50














                                            • 7





                                              jQuery for everything?

                                              – Exception
                                              Feb 7 '13 at 19:03






                                            • 6





                                              Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                              – Stijn de Witt
                                              Mar 31 '13 at 19:04






                                            • 1





                                              Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                              – Stijn de Witt
                                              Jun 5 '17 at 10:50








                                            7




                                            7





                                            jQuery for everything?

                                            – Exception
                                            Feb 7 '13 at 19:03





                                            jQuery for everything?

                                            – Exception
                                            Feb 7 '13 at 19:03




                                            6




                                            6





                                            Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                            – Stijn de Witt
                                            Mar 31 '13 at 19:04





                                            Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

                                            – Stijn de Witt
                                            Mar 31 '13 at 19:04




                                            1




                                            1





                                            Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                            – Stijn de Witt
                                            Jun 5 '17 at 10:50





                                            Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

                                            – Stijn de Witt
                                            Jun 5 '17 at 10:50











                                            19














                                            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



                                            Performamce results



                                            Results :



                                            The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.



                                            let arr = [1,2,3,4,5];

                                            for(let i=0, size=arr.length; i<size; i++){
                                            // do something
                                            }


                                            The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead






                                            share|improve this answer
























                                            • is better use i = i +1 instead of i++

                                              – DarckBlezzer
                                              Dec 10 '18 at 18:19
















                                            19














                                            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



                                            Performamce results



                                            Results :



                                            The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.



                                            let arr = [1,2,3,4,5];

                                            for(let i=0, size=arr.length; i<size; i++){
                                            // do something
                                            }


                                            The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead






                                            share|improve this answer
























                                            • is better use i = i +1 instead of i++

                                              – DarckBlezzer
                                              Dec 10 '18 at 18:19














                                            19












                                            19








                                            19







                                            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



                                            Performamce results



                                            Results :



                                            The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.



                                            let arr = [1,2,3,4,5];

                                            for(let i=0, size=arr.length; i<size; i++){
                                            // do something
                                            }


                                            The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead






                                            share|improve this answer













                                            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



                                            Performamce results



                                            Results :



                                            The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.



                                            let arr = [1,2,3,4,5];

                                            for(let i=0, size=arr.length; i<size; i++){
                                            // do something
                                            }


                                            The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Aug 20 '18 at 23:36









                                            colxicolxi

                                            2,2651726




                                            2,2651726













                                            • is better use i = i +1 instead of i++

                                              – DarckBlezzer
                                              Dec 10 '18 at 18:19



















                                            • is better use i = i +1 instead of i++

                                              – DarckBlezzer
                                              Dec 10 '18 at 18:19

















                                            is better use i = i +1 instead of i++

                                            – DarckBlezzer
                                            Dec 10 '18 at 18:19





                                            is better use i = i +1 instead of i++

                                            – DarckBlezzer
                                            Dec 10 '18 at 18:19











                                            16














                                            I did not yet see this variation, which I personally like the best:



                                            Given an array:



                                            var someArray = ["some", "example", "array"];


                                            You can loop over it without ever accessing the length property:



                                            for (var i=0, item; item=someArray[i]; i++) {
                                            // item is "some", then "example", then "array"
                                            // i is the index of item in the array
                                            alert("someArray[" + i + "]: " + item);
                                            }


                                            See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/



                                            This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.



                                            Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)



                                            What I like about this loop is:




                                            • It's short to write

                                            • No need to access (let alone cache) the length property

                                            • The item to access is automatically defined within the loop
                                              body under the name you pick.

                                            • Combines very naturally with array.push and array.splice to use arrays like lists/stacks


                                            The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.



                                            For me, this construct most closely emulates the Java 5 syntax that I love:



                                            for (String item : someArray) {
                                            }


                                            ... with the added benefit of also knowing about the current index inside the loop






                                            share|improve this answer





















                                            • 13





                                              Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                              – CMS
                                              Feb 28 '13 at 18:31






                                            • 3





                                              The loop condition could be (item=someArray[i]) !== undefined.

                                              – daniel1426
                                              Mar 20 '14 at 14:17
















                                            16














                                            I did not yet see this variation, which I personally like the best:



                                            Given an array:



                                            var someArray = ["some", "example", "array"];


                                            You can loop over it without ever accessing the length property:



                                            for (var i=0, item; item=someArray[i]; i++) {
                                            // item is "some", then "example", then "array"
                                            // i is the index of item in the array
                                            alert("someArray[" + i + "]: " + item);
                                            }


                                            See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/



                                            This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.



                                            Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)



                                            What I like about this loop is:




                                            • It's short to write

                                            • No need to access (let alone cache) the length property

                                            • The item to access is automatically defined within the loop
                                              body under the name you pick.

                                            • Combines very naturally with array.push and array.splice to use arrays like lists/stacks


                                            The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.



                                            For me, this construct most closely emulates the Java 5 syntax that I love:



                                            for (String item : someArray) {
                                            }


                                            ... with the added benefit of also knowing about the current index inside the loop






                                            share|improve this answer





















                                            • 13





                                              Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                              – CMS
                                              Feb 28 '13 at 18:31






                                            • 3





                                              The loop condition could be (item=someArray[i]) !== undefined.

                                              – daniel1426
                                              Mar 20 '14 at 14:17














                                            16












                                            16








                                            16







                                            I did not yet see this variation, which I personally like the best:



                                            Given an array:



                                            var someArray = ["some", "example", "array"];


                                            You can loop over it without ever accessing the length property:



                                            for (var i=0, item; item=someArray[i]; i++) {
                                            // item is "some", then "example", then "array"
                                            // i is the index of item in the array
                                            alert("someArray[" + i + "]: " + item);
                                            }


                                            See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/



                                            This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.



                                            Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)



                                            What I like about this loop is:




                                            • It's short to write

                                            • No need to access (let alone cache) the length property

                                            • The item to access is automatically defined within the loop
                                              body under the name you pick.

                                            • Combines very naturally with array.push and array.splice to use arrays like lists/stacks


                                            The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.



                                            For me, this construct most closely emulates the Java 5 syntax that I love:



                                            for (String item : someArray) {
                                            }


                                            ... with the added benefit of also knowing about the current index inside the loop






                                            share|improve this answer















                                            I did not yet see this variation, which I personally like the best:



                                            Given an array:



                                            var someArray = ["some", "example", "array"];


                                            You can loop over it without ever accessing the length property:



                                            for (var i=0, item; item=someArray[i]; i++) {
                                            // item is "some", then "example", then "array"
                                            // i is the index of item in the array
                                            alert("someArray[" + i + "]: " + item);
                                            }


                                            See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/



                                            This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.



                                            Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)



                                            What I like about this loop is:




                                            • It's short to write

                                            • No need to access (let alone cache) the length property

                                            • The item to access is automatically defined within the loop
                                              body under the name you pick.

                                            • Combines very naturally with array.push and array.splice to use arrays like lists/stacks


                                            The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.



                                            For me, this construct most closely emulates the Java 5 syntax that I love:



                                            for (String item : someArray) {
                                            }


                                            ... with the added benefit of also knowing about the current index inside the loop







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Mar 1 '13 at 12:13

























                                            answered Feb 28 '13 at 13:59









                                            Stijn de WittStijn de Witt

                                            20.4k45564




                                            20.4k45564








                                            • 13





                                              Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                              – CMS
                                              Feb 28 '13 at 18:31






                                            • 3





                                              The loop condition could be (item=someArray[i]) !== undefined.

                                              – daniel1426
                                              Mar 20 '14 at 14:17














                                            • 13





                                              Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                              – CMS
                                              Feb 28 '13 at 18:31






                                            • 3





                                              The loop condition could be (item=someArray[i]) !== undefined.

                                              – daniel1426
                                              Mar 20 '14 at 14:17








                                            13




                                            13





                                            Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                            – CMS
                                            Feb 28 '13 at 18:31





                                            Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

                                            – CMS
                                            Feb 28 '13 at 18:31




                                            3




                                            3





                                            The loop condition could be (item=someArray[i]) !== undefined.

                                            – daniel1426
                                            Mar 20 '14 at 14:17





                                            The loop condition could be (item=someArray[i]) !== undefined.

                                            – daniel1426
                                            Mar 20 '14 at 14:17











                                            14














                                            There's a method to iterate over only own object properties, not including prototype's ones:



                                            for (var i in array) if (array.hasOwnProperty(i)) {
                                            // do something with array[i]
                                            }


                                            but it still will iterate over custom-defined properties.



                                            In javascript any custom property could be assigned to any object including array.



                                            If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.






                                            share|improve this answer
























                                            • This is interesting, is there any gotchas you have experienced except those mentioned?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:34











                                            • And how about using for (var i in array) if (++i) ?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:40
















                                            14














                                            There's a method to iterate over only own object properties, not including prototype's ones:



                                            for (var i in array) if (array.hasOwnProperty(i)) {
                                            // do something with array[i]
                                            }


                                            but it still will iterate over custom-defined properties.



                                            In javascript any custom property could be assigned to any object including array.



                                            If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.






                                            share|improve this answer
























                                            • This is interesting, is there any gotchas you have experienced except those mentioned?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:34











                                            • And how about using for (var i in array) if (++i) ?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:40














                                            14












                                            14








                                            14







                                            There's a method to iterate over only own object properties, not including prototype's ones:



                                            for (var i in array) if (array.hasOwnProperty(i)) {
                                            // do something with array[i]
                                            }


                                            but it still will iterate over custom-defined properties.



                                            In javascript any custom property could be assigned to any object including array.



                                            If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.






                                            share|improve this answer













                                            There's a method to iterate over only own object properties, not including prototype's ones:



                                            for (var i in array) if (array.hasOwnProperty(i)) {
                                            // do something with array[i]
                                            }


                                            but it still will iterate over custom-defined properties.



                                            In javascript any custom property could be assigned to any object including array.



                                            If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Apr 15 '12 at 12:50









                                            kirilloidkirilloid

                                            10k33248




                                            10k33248













                                            • This is interesting, is there any gotchas you have experienced except those mentioned?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:34











                                            • And how about using for (var i in array) if (++i) ?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:40



















                                            • This is interesting, is there any gotchas you have experienced except those mentioned?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:34











                                            • And how about using for (var i in array) if (++i) ?

                                              – Daniel Sokolowski
                                              Oct 9 '14 at 14:40

















                                            This is interesting, is there any gotchas you have experienced except those mentioned?

                                            – Daniel Sokolowski
                                            Oct 9 '14 at 14:34





                                            This is interesting, is there any gotchas you have experienced except those mentioned?

                                            – Daniel Sokolowski
                                            Oct 9 '14 at 14:34













                                            And how about using for (var i in array) if (++i) ?

                                            – Daniel Sokolowski
                                            Oct 9 '14 at 14:40





                                            And how about using for (var i in array) if (++i) ?

                                            – Daniel Sokolowski
                                            Oct 9 '14 at 14:40











                                            14














                                            There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.






                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>








                                            share|improve this answer


























                                            • for...in should be avoided for Array-like objects

                                              – brk
                                              Dec 5 '16 at 5:25
















                                            14














                                            There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.






                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>








                                            share|improve this answer


























                                            • for...in should be avoided for Array-like objects

                                              – brk
                                              Dec 5 '16 at 5:25














                                            14












                                            14








                                            14







                                            There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.






                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>








                                            share|improve this answer















                                            There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.






                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }








                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>








                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }





                                            var myStringArray = ["hello", "World"];
                                            for(var i in myStringArray) {
                                            alert(myStringArray[i]);
                                            }





                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }





                                            var myStringArray = ["hello", "World"];
                                            for (var i=0; i < myStringArray.length; i++) {
                                            alert(myStringArray[i]);
                                            }





                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>





                                            var myStringArray = ["hello", "World"];
                                            $.each(myStringArray, function(index, value){
                                            alert(value);
                                            })

                                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jul 2 '16 at 19:37









                                            Peter Mortensen

                                            13.7k1986113




                                            13.7k1986113










                                            answered Apr 21 '16 at 16:03









                                            Shubham KhatriShubham Khatri

                                            89.7k15110149




                                            89.7k15110149













                                            • for...in should be avoided for Array-like objects

                                              – brk
                                              Dec 5 '16 at 5:25



















                                            • for...in should be avoided for Array-like objects

                                              – brk
                                              Dec 5 '16 at 5:25

















                                            for...in should be avoided for Array-like objects

                                            – brk
                                            Dec 5 '16 at 5:25





                                            for...in should be avoided for Array-like objects

                                            – brk
                                            Dec 5 '16 at 5:25











                                            14














                                            The most elegant and fast way



                                            var arr = [1, 2, 3, 1023, 1024];
                                            for (var value; value = arr.pop();) {
                                            value + 1
                                            }


                                            http://jsperf.com/native-loop-performance/8





                                            Edited (because I was wrong)





                                            Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.




                                            • http://jsben.ch/#/BQhED


                                            Preparation:



                                            <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
                                            <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
                                            <script>
                                            Benchmark.prototype.setup = function() {
                                            // Fake function with minimal action on the value
                                            var tmp = 0;
                                            var process = function(value) {
                                            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
                                            };

                                            // Declare the test Array
                                            var arr = ;
                                            for (var i = 0; i < 100000; i++)
                                            arr[i] = i;
                                            };
                                            </script>


                                            Tests:



                                            <a href="http://jsperf.com/native-loop-performance/16" 
                                            title="http://jsperf.com/native-loop-performance/16"
                                            ><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>





                                            share|improve this answer


























                                            • This loop doesn't seem to follow order of items in the array.

                                              – Deniz Ozger
                                              Mar 26 '14 at 15:36











                                            • My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                              – molokoloco
                                              Mar 27 '14 at 16:41






                                            • 14





                                              -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                              – Bergi
                                              Mar 30 '14 at 14:49













                                            • @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                              – Stijn de Witt
                                              May 15 '14 at 17:34






                                            • 4





                                              breaks on falsey items.

                                              – njzk2
                                              Jul 29 '14 at 14:59
















                                            14














                                            The most elegant and fast way



                                            var arr = [1, 2, 3, 1023, 1024];
                                            for (var value; value = arr.pop();) {
                                            value + 1
                                            }


                                            http://jsperf.com/native-loop-performance/8





                                            Edited (because I was wrong)





                                            Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.




                                            • http://jsben.ch/#/BQhED


                                            Preparation:



                                            <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
                                            <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
                                            <script>
                                            Benchmark.prototype.setup = function() {
                                            // Fake function with minimal action on the value
                                            var tmp = 0;
                                            var process = function(value) {
                                            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
                                            };

                                            // Declare the test Array
                                            var arr = ;
                                            for (var i = 0; i < 100000; i++)
                                            arr[i] = i;
                                            };
                                            </script>


                                            Tests:



                                            <a href="http://jsperf.com/native-loop-performance/16" 
                                            title="http://jsperf.com/native-loop-performance/16"
                                            ><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>





                                            share|improve this answer


























                                            • This loop doesn't seem to follow order of items in the array.

                                              – Deniz Ozger
                                              Mar 26 '14 at 15:36











                                            • My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                              – molokoloco
                                              Mar 27 '14 at 16:41






                                            • 14





                                              -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                              – Bergi
                                              Mar 30 '14 at 14:49













                                            • @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                              – Stijn de Witt
                                              May 15 '14 at 17:34






                                            • 4





                                              breaks on falsey items.

                                              – njzk2
                                              Jul 29 '14 at 14:59














                                            14












                                            14








                                            14







                                            The most elegant and fast way



                                            var arr = [1, 2, 3, 1023, 1024];
                                            for (var value; value = arr.pop();) {
                                            value + 1
                                            }


                                            http://jsperf.com/native-loop-performance/8





                                            Edited (because I was wrong)





                                            Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.




                                            • http://jsben.ch/#/BQhED


                                            Preparation:



                                            <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
                                            <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
                                            <script>
                                            Benchmark.prototype.setup = function() {
                                            // Fake function with minimal action on the value
                                            var tmp = 0;
                                            var process = function(value) {
                                            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
                                            };

                                            // Declare the test Array
                                            var arr = ;
                                            for (var i = 0; i < 100000; i++)
                                            arr[i] = i;
                                            };
                                            </script>


                                            Tests:



                                            <a href="http://jsperf.com/native-loop-performance/16" 
                                            title="http://jsperf.com/native-loop-performance/16"
                                            ><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>





                                            share|improve this answer















                                            The most elegant and fast way



                                            var arr = [1, 2, 3, 1023, 1024];
                                            for (var value; value = arr.pop();) {
                                            value + 1
                                            }


                                            http://jsperf.com/native-loop-performance/8





                                            Edited (because I was wrong)





                                            Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.




                                            • http://jsben.ch/#/BQhED


                                            Preparation:



                                            <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
                                            <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
                                            <script>
                                            Benchmark.prototype.setup = function() {
                                            // Fake function with minimal action on the value
                                            var tmp = 0;
                                            var process = function(value) {
                                            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
                                            };

                                            // Declare the test Array
                                            var arr = ;
                                            for (var i = 0; i < 100000; i++)
                                            arr[i] = i;
                                            };
                                            </script>


                                            Tests:



                                            <a href="http://jsperf.com/native-loop-performance/16" 
                                            title="http://jsperf.com/native-loop-performance/16"
                                            ><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 17 '16 at 23:08









                                            Emile Bergeron

                                            10.6k44572




                                            10.6k44572










                                            answered Mar 8 '14 at 2:06









                                            molokolocomolokoloco

                                            3,64712523




                                            3,64712523













                                            • This loop doesn't seem to follow order of items in the array.

                                              – Deniz Ozger
                                              Mar 26 '14 at 15:36











                                            • My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                              – molokoloco
                                              Mar 27 '14 at 16:41






                                            • 14





                                              -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                              – Bergi
                                              Mar 30 '14 at 14:49













                                            • @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                              – Stijn de Witt
                                              May 15 '14 at 17:34






                                            • 4





                                              breaks on falsey items.

                                              – njzk2
                                              Jul 29 '14 at 14:59



















                                            • This loop doesn't seem to follow order of items in the array.

                                              – Deniz Ozger
                                              Mar 26 '14 at 15:36











                                            • My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                              – molokoloco
                                              Mar 27 '14 at 16:41






                                            • 14





                                              -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                              – Bergi
                                              Mar 30 '14 at 14:49













                                            • @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                              – Stijn de Witt
                                              May 15 '14 at 17:34






                                            • 4





                                              breaks on falsey items.

                                              – njzk2
                                              Jul 29 '14 at 14:59

















                                            This loop doesn't seem to follow order of items in the array.

                                            – Deniz Ozger
                                            Mar 26 '14 at 15:36





                                            This loop doesn't seem to follow order of items in the array.

                                            – Deniz Ozger
                                            Mar 26 '14 at 15:36













                                            My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                            – molokoloco
                                            Mar 27 '14 at 16:41





                                            My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

                                            – molokoloco
                                            Mar 27 '14 at 16:41




                                            14




                                            14





                                            -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                            – Bergi
                                            Mar 30 '14 at 14:49







                                            -1 for modifying the array, which a plain loop should not do. Probably affecting the performance test as well.

                                            – Bergi
                                            Mar 30 '14 at 14:49















                                            @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                            – Stijn de Witt
                                            May 15 '14 at 17:34





                                            @bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

                                            – Stijn de Witt
                                            May 15 '14 at 17:34




                                            4




                                            4





                                            breaks on falsey items.

                                            – njzk2
                                            Jul 29 '14 at 14:59





                                            breaks on falsey items.

                                            – njzk2
                                            Jul 29 '14 at 14:59











                                            10














                                            The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.



                                            var i, max, myStringArray = ["Hello","World"];
                                            for (i = 0, max = myStringArray.length; i < max; i++) {
                                            alert(myStringArray[i]);
                                            //Do something
                                            }


                                            If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:



                                            var i,myStringArray = ["item1","item2"];
                                            for (i = myStringArray.length; i--) {
                                            alert(myStringArray[i]);
                                            }


                                            or better and cleaner to use while loop:



                                            var myStringArray = ["item1","item2"],i = myStringArray.length;
                                            while(i--) {
                                            // do something with fruits[i]
                                            }





                                            share|improve this answer






























                                              10














                                              The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.



                                              var i, max, myStringArray = ["Hello","World"];
                                              for (i = 0, max = myStringArray.length; i < max; i++) {
                                              alert(myStringArray[i]);
                                              //Do something
                                              }


                                              If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:



                                              var i,myStringArray = ["item1","item2"];
                                              for (i = myStringArray.length; i--) {
                                              alert(myStringArray[i]);
                                              }


                                              or better and cleaner to use while loop:



                                              var myStringArray = ["item1","item2"],i = myStringArray.length;
                                              while(i--) {
                                              // do something with fruits[i]
                                              }





                                              share|improve this answer




























                                                10












                                                10








                                                10







                                                The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.



                                                var i, max, myStringArray = ["Hello","World"];
                                                for (i = 0, max = myStringArray.length; i < max; i++) {
                                                alert(myStringArray[i]);
                                                //Do something
                                                }


                                                If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:



                                                var i,myStringArray = ["item1","item2"];
                                                for (i = myStringArray.length; i--) {
                                                alert(myStringArray[i]);
                                                }


                                                or better and cleaner to use while loop:



                                                var myStringArray = ["item1","item2"],i = myStringArray.length;
                                                while(i--) {
                                                // do something with fruits[i]
                                                }





                                                share|improve this answer















                                                The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.



                                                var i, max, myStringArray = ["Hello","World"];
                                                for (i = 0, max = myStringArray.length; i < max; i++) {
                                                alert(myStringArray[i]);
                                                //Do something
                                                }


                                                If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:



                                                var i,myStringArray = ["item1","item2"];
                                                for (i = myStringArray.length; i--) {
                                                alert(myStringArray[i]);
                                                }


                                                or better and cleaner to use while loop:



                                                var myStringArray = ["item1","item2"],i = myStringArray.length;
                                                while(i--) {
                                                // do something with fruits[i]
                                                }






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Feb 2 '14 at 10:37

























                                                answered Jan 11 '14 at 20:53









                                                Zaheer AhmedZaheer Ahmed

                                                22.6k106099




                                                22.6k106099























                                                    10














                                                    In JavaScript, there are so many solutions to loop an array.



                                                    The code below are popular ones






                                                    /** Declare inputs */
                                                    const items = ['Hello', 'World']

                                                    /** Solution 1. Simple for */
                                                    console.log('solution 1. simple for')

                                                    for (let i = 0; i < items.length; i++) {
                                                    console.log(items[i])
                                                    }

                                                    console.log()
                                                    console.log()

                                                    /** Solution 2. Simple while */
                                                    console.log('solution 2. simple while')

                                                    let i = 0
                                                    while (i < items.length) {
                                                    console.log(items[i++])
                                                    }

                                                    console.log()
                                                    console.log()

                                                    /** Solution 3. forEach*/
                                                    console.log('solution 3. forEach')

                                                    items.forEach(item => {
                                                    console.log(item)
                                                    })

                                                    console.log()
                                                    console.log()

                                                    /** Solution 4. for-of*/
                                                    console.log('solution 4. for-of')

                                                    for (const item of items) {
                                                    console.log(item)
                                                    }

                                                    console.log()
                                                    console.log()








                                                    share|improve this answer






























                                                      10














                                                      In JavaScript, there are so many solutions to loop an array.



                                                      The code below are popular ones






                                                      /** Declare inputs */
                                                      const items = ['Hello', 'World']

                                                      /** Solution 1. Simple for */
                                                      console.log('solution 1. simple for')

                                                      for (let i = 0; i < items.length; i++) {
                                                      console.log(items[i])
                                                      }

                                                      console.log()
                                                      console.log()

                                                      /** Solution 2. Simple while */
                                                      console.log('solution 2. simple while')

                                                      let i = 0
                                                      while (i < items.length) {
                                                      console.log(items[i++])
                                                      }

                                                      console.log()
                                                      console.log()

                                                      /** Solution 3. forEach*/
                                                      console.log('solution 3. forEach')

                                                      items.forEach(item => {
                                                      console.log(item)
                                                      })

                                                      console.log()
                                                      console.log()

                                                      /** Solution 4. for-of*/
                                                      console.log('solution 4. for-of')

                                                      for (const item of items) {
                                                      console.log(item)
                                                      }

                                                      console.log()
                                                      console.log()








                                                      share|improve this answer




























                                                        10












                                                        10








                                                        10







                                                        In JavaScript, there are so many solutions to loop an array.



                                                        The code below are popular ones






                                                        /** Declare inputs */
                                                        const items = ['Hello', 'World']

                                                        /** Solution 1. Simple for */
                                                        console.log('solution 1. simple for')

                                                        for (let i = 0; i < items.length; i++) {
                                                        console.log(items[i])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 2. Simple while */
                                                        console.log('solution 2. simple while')

                                                        let i = 0
                                                        while (i < items.length) {
                                                        console.log(items[i++])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 3. forEach*/
                                                        console.log('solution 3. forEach')

                                                        items.forEach(item => {
                                                        console.log(item)
                                                        })

                                                        console.log()
                                                        console.log()

                                                        /** Solution 4. for-of*/
                                                        console.log('solution 4. for-of')

                                                        for (const item of items) {
                                                        console.log(item)
                                                        }

                                                        console.log()
                                                        console.log()








                                                        share|improve this answer















                                                        In JavaScript, there are so many solutions to loop an array.



                                                        The code below are popular ones






                                                        /** Declare inputs */
                                                        const items = ['Hello', 'World']

                                                        /** Solution 1. Simple for */
                                                        console.log('solution 1. simple for')

                                                        for (let i = 0; i < items.length; i++) {
                                                        console.log(items[i])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 2. Simple while */
                                                        console.log('solution 2. simple while')

                                                        let i = 0
                                                        while (i < items.length) {
                                                        console.log(items[i++])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 3. forEach*/
                                                        console.log('solution 3. forEach')

                                                        items.forEach(item => {
                                                        console.log(item)
                                                        })

                                                        console.log()
                                                        console.log()

                                                        /** Solution 4. for-of*/
                                                        console.log('solution 4. for-of')

                                                        for (const item of items) {
                                                        console.log(item)
                                                        }

                                                        console.log()
                                                        console.log()








                                                        /** Declare inputs */
                                                        const items = ['Hello', 'World']

                                                        /** Solution 1. Simple for */
                                                        console.log('solution 1. simple for')

                                                        for (let i = 0; i < items.length; i++) {
                                                        console.log(items[i])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 2. Simple while */
                                                        console.log('solution 2. simple while')

                                                        let i = 0
                                                        while (i < items.length) {
                                                        console.log(items[i++])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 3. forEach*/
                                                        console.log('solution 3. forEach')

                                                        items.forEach(item => {
                                                        console.log(item)
                                                        })

                                                        console.log()
                                                        console.log()

                                                        /** Solution 4. for-of*/
                                                        console.log('solution 4. for-of')

                                                        for (const item of items) {
                                                        console.log(item)
                                                        }

                                                        console.log()
                                                        console.log()





                                                        /** Declare inputs */
                                                        const items = ['Hello', 'World']

                                                        /** Solution 1. Simple for */
                                                        console.log('solution 1. simple for')

                                                        for (let i = 0; i < items.length; i++) {
                                                        console.log(items[i])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 2. Simple while */
                                                        console.log('solution 2. simple while')

                                                        let i = 0
                                                        while (i < items.length) {
                                                        console.log(items[i++])
                                                        }

                                                        console.log()
                                                        console.log()

                                                        /** Solution 3. forEach*/
                                                        console.log('solution 3. forEach')

                                                        items.forEach(item => {
                                                        console.log(item)
                                                        })

                                                        console.log()
                                                        console.log()

                                                        /** Solution 4. for-of*/
                                                        console.log('solution 4. for-of')

                                                        for (const item of items) {
                                                        console.log(item)
                                                        }

                                                        console.log()
                                                        console.log()






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited May 21 '17 at 11:05









                                                        Peter Mortensen

                                                        13.7k1986113




                                                        13.7k1986113










                                                        answered Oct 14 '16 at 10:31









                                                        Alongkorn ChetasumonAlongkorn Chetasumon

                                                        1,323928




                                                        1,323928























                                                            9














                                                            Short answer: yes. You can do with this:



                                                            var myArray = ["element1", "element2", "element3", "element4"];

                                                            for (i = 0; i < myArray.length; i++) {
                                                            console.log(myArray[i]);
                                                            }


                                                            In a browser console, you can see something like "element1", "element2", etc., printed.






                                                            share|improve this answer






























                                                              9














                                                              Short answer: yes. You can do with this:



                                                              var myArray = ["element1", "element2", "element3", "element4"];

                                                              for (i = 0; i < myArray.length; i++) {
                                                              console.log(myArray[i]);
                                                              }


                                                              In a browser console, you can see something like "element1", "element2", etc., printed.






                                                              share|improve this answer




























                                                                9












                                                                9








                                                                9







                                                                Short answer: yes. You can do with this:



                                                                var myArray = ["element1", "element2", "element3", "element4"];

                                                                for (i = 0; i < myArray.length; i++) {
                                                                console.log(myArray[i]);
                                                                }


                                                                In a browser console, you can see something like "element1", "element2", etc., printed.






                                                                share|improve this answer















                                                                Short answer: yes. You can do with this:



                                                                var myArray = ["element1", "element2", "element3", "element4"];

                                                                for (i = 0; i < myArray.length; i++) {
                                                                console.log(myArray[i]);
                                                                }


                                                                In a browser console, you can see something like "element1", "element2", etc., printed.







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Jul 2 '16 at 19:39









                                                                Peter Mortensen

                                                                13.7k1986113




                                                                13.7k1986113










                                                                answered Mar 17 '16 at 10:13









                                                                Juanjo SalvadorJuanjo Salvador

                                                                750826




                                                                750826























                                                                    9














                                                                    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:



                                                                    var numbers = [1,11,22,33,44,55,66,77,88,99,111];
                                                                    var sum = 0;
                                                                    numbers.forEach(function(n){
                                                                    sum += n;
                                                                    });


                                                                    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:



                                                                    var sum = 0;
                                                                    var numbers = [1,11,22,33,44,55,66,77,88,99,111];

                                                                    for(var i = 0; i<numbers.length; ++i){
                                                                    sum += numbers[i];
                                                                    }

                                                                    alert(i);


                                                                    will output "11" - which may or may not be what you want.



                                                                    Working jsFiddle example:
                                                                    https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/






                                                                    share|improve this answer






























                                                                      9














                                                                      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:



                                                                      var numbers = [1,11,22,33,44,55,66,77,88,99,111];
                                                                      var sum = 0;
                                                                      numbers.forEach(function(n){
                                                                      sum += n;
                                                                      });


                                                                      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:



                                                                      var sum = 0;
                                                                      var numbers = [1,11,22,33,44,55,66,77,88,99,111];

                                                                      for(var i = 0; i<numbers.length; ++i){
                                                                      sum += numbers[i];
                                                                      }

                                                                      alert(i);


                                                                      will output "11" - which may or may not be what you want.



                                                                      Working jsFiddle example:
                                                                      https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/






                                                                      share|improve this answer




























                                                                        9












                                                                        9








                                                                        9







                                                                        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:



                                                                        var numbers = [1,11,22,33,44,55,66,77,88,99,111];
                                                                        var sum = 0;
                                                                        numbers.forEach(function(n){
                                                                        sum += n;
                                                                        });


                                                                        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:



                                                                        var sum = 0;
                                                                        var numbers = [1,11,22,33,44,55,66,77,88,99,111];

                                                                        for(var i = 0; i<numbers.length; ++i){
                                                                        sum += numbers[i];
                                                                        }

                                                                        alert(i);


                                                                        will output "11" - which may or may not be what you want.



                                                                        Working jsFiddle example:
                                                                        https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/






                                                                        share|improve this answer















                                                                        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:



                                                                        var numbers = [1,11,22,33,44,55,66,77,88,99,111];
                                                                        var sum = 0;
                                                                        numbers.forEach(function(n){
                                                                        sum += n;
                                                                        });


                                                                        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:



                                                                        var sum = 0;
                                                                        var numbers = [1,11,22,33,44,55,66,77,88,99,111];

                                                                        for(var i = 0; i<numbers.length; ++i){
                                                                        sum += numbers[i];
                                                                        }

                                                                        alert(i);


                                                                        will output "11" - which may or may not be what you want.



                                                                        Working jsFiddle example:
                                                                        https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited May 21 '17 at 11:04









                                                                        Peter Mortensen

                                                                        13.7k1986113




                                                                        13.7k1986113










                                                                        answered Oct 26 '16 at 8:51









                                                                        EspenEspen

                                                                        8631015




                                                                        8631015























                                                                            8














                                                                            For example, I used in a Firefox console:



                                                                            .forEach.call(document.getElementsByTagName('pre'), function(e){ 
                                                                            console.log(e);
                                                                            })





                                                                            share|improve this answer




























                                                                              8














                                                                              For example, I used in a Firefox console:



                                                                              .forEach.call(document.getElementsByTagName('pre'), function(e){ 
                                                                              console.log(e);
                                                                              })





                                                                              share|improve this answer


























                                                                                8












                                                                                8








                                                                                8







                                                                                For example, I used in a Firefox console:



                                                                                .forEach.call(document.getElementsByTagName('pre'), function(e){ 
                                                                                console.log(e);
                                                                                })





                                                                                share|improve this answer













                                                                                For example, I used in a Firefox console:



                                                                                .forEach.call(document.getElementsByTagName('pre'), function(e){ 
                                                                                console.log(e);
                                                                                })






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Oct 21 '14 at 7:32









                                                                                victorq10victorq10

                                                                                14912




                                                                                14912























                                                                                    8














                                                                                    var x = [4, 5, 6];
                                                                                    for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
                                                                                    console.log(i,j);
                                                                                    }


                                                                                    A lot cleaner...






                                                                                    share|improve this answer


























                                                                                    • did you mean "x =" on the first line?

                                                                                      – Matiaan
                                                                                      Jan 7 '15 at 12:26
















                                                                                    8














                                                                                    var x = [4, 5, 6];
                                                                                    for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
                                                                                    console.log(i,j);
                                                                                    }


                                                                                    A lot cleaner...






                                                                                    share|improve this answer


























                                                                                    • did you mean "x =" on the first line?

                                                                                      – Matiaan
                                                                                      Jan 7 '15 at 12:26














                                                                                    8












                                                                                    8








                                                                                    8







                                                                                    var x = [4, 5, 6];
                                                                                    for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
                                                                                    console.log(i,j);
                                                                                    }


                                                                                    A lot cleaner...






                                                                                    share|improve this answer















                                                                                    var x = [4, 5, 6];
                                                                                    for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
                                                                                    console.log(i,j);
                                                                                    }


                                                                                    A lot cleaner...







                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    edited Nov 4 '15 at 20:39









                                                                                    Kasapo

                                                                                    3,91411420




                                                                                    3,91411420










                                                                                    answered Aug 6 '13 at 8:03









                                                                                    staticdstaticd

                                                                                    911612




                                                                                    911612













                                                                                    • did you mean "x =" on the first line?

                                                                                      – Matiaan
                                                                                      Jan 7 '15 at 12:26



















                                                                                    • did you mean "x =" on the first line?

                                                                                      – Matiaan
                                                                                      Jan 7 '15 at 12:26

















                                                                                    did you mean "x =" on the first line?

                                                                                    – Matiaan
                                                                                    Jan 7 '15 at 12:26





                                                                                    did you mean "x =" on the first line?

                                                                                    – Matiaan
                                                                                    Jan 7 '15 at 12:26











                                                                                    8














                                                                                    If you want to use jQuery, it has a nice example in its documentation:



                                                                                     $.each([ 52, 97 ], function( index, value ) {
                                                                                    alert( index + ": " + value );
                                                                                    });





                                                                                    share|improve this answer






























                                                                                      8














                                                                                      If you want to use jQuery, it has a nice example in its documentation:



                                                                                       $.each([ 52, 97 ], function( index, value ) {
                                                                                      alert( index + ": " + value );
                                                                                      });





                                                                                      share|improve this answer




























                                                                                        8












                                                                                        8








                                                                                        8







                                                                                        If you want to use jQuery, it has a nice example in its documentation:



                                                                                         $.each([ 52, 97 ], function( index, value ) {
                                                                                        alert( index + ": " + value );
                                                                                        });





                                                                                        share|improve this answer















                                                                                        If you want to use jQuery, it has a nice example in its documentation:



                                                                                         $.each([ 52, 97 ], function( index, value ) {
                                                                                        alert( index + ": " + value );
                                                                                        });






                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Mar 17 '18 at 0:41

























                                                                                        answered Mar 30 '16 at 2:37









                                                                                        jj_jj_

                                                                                        1,5692144




                                                                                        1,5692144























                                                                                            7














                                                                                            Just a simple one line solution






                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });








                                                                                            share|improve this answer



















                                                                                            • 3





                                                                                              You'd rather want to use .forEach() and drop the return e;

                                                                                              – Michel Jung
                                                                                              Oct 6 '17 at 11:09






                                                                                            • 3





                                                                                              as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                              – marpme
                                                                                              Nov 17 '17 at 22:28
















                                                                                            7














                                                                                            Just a simple one line solution






                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });








                                                                                            share|improve this answer



















                                                                                            • 3





                                                                                              You'd rather want to use .forEach() and drop the return e;

                                                                                              – Michel Jung
                                                                                              Oct 6 '17 at 11:09






                                                                                            • 3





                                                                                              as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                              – marpme
                                                                                              Nov 17 '17 at 22:28














                                                                                            7












                                                                                            7








                                                                                            7







                                                                                            Just a simple one line solution






                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });








                                                                                            share|improve this answer













                                                                                            Just a simple one line solution






                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });








                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });





                                                                                            arr = ["table", "chair"];

                                                                                            // solution
                                                                                            arr.map((e) => {
                                                                                            console.log(e);
                                                                                            return e;
                                                                                            });






                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered Sep 13 '17 at 22:11









                                                                                            BILAL AHMADBILAL AHMAD

                                                                                            56949




                                                                                            56949








                                                                                            • 3





                                                                                              You'd rather want to use .forEach() and drop the return e;

                                                                                              – Michel Jung
                                                                                              Oct 6 '17 at 11:09






                                                                                            • 3





                                                                                              as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                              – marpme
                                                                                              Nov 17 '17 at 22:28














                                                                                            • 3





                                                                                              You'd rather want to use .forEach() and drop the return e;

                                                                                              – Michel Jung
                                                                                              Oct 6 '17 at 11:09






                                                                                            • 3





                                                                                              as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                              – marpme
                                                                                              Nov 17 '17 at 22:28








                                                                                            3




                                                                                            3





                                                                                            You'd rather want to use .forEach() and drop the return e;

                                                                                            – Michel Jung
                                                                                            Oct 6 '17 at 11:09





                                                                                            You'd rather want to use .forEach() and drop the return e;

                                                                                            – Michel Jung
                                                                                            Oct 6 '17 at 11:09




                                                                                            3




                                                                                            3





                                                                                            as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                            – marpme
                                                                                            Nov 17 '17 at 22:28





                                                                                            as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

                                                                                            – marpme
                                                                                            Nov 17 '17 at 22:28











                                                                                            7














                                                                                            It's not 100% identical, but similar:






                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }








                                                                                            share|improve this answer





















                                                                                            • 1





                                                                                              It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                              – Kzqai
                                                                                              Apr 18 '12 at 15:34
















                                                                                            7














                                                                                            It's not 100% identical, but similar:






                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }








                                                                                            share|improve this answer





















                                                                                            • 1





                                                                                              It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                              – Kzqai
                                                                                              Apr 18 '12 at 15:34














                                                                                            7












                                                                                            7








                                                                                            7







                                                                                            It's not 100% identical, but similar:






                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }








                                                                                            share|improve this answer















                                                                                            It's not 100% identical, but similar:






                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }








                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }





                                                                                               var myStringArray = ['Hello', 'World']; // array uses  not {}
                                                                                            for (var i in myStringArray) {
                                                                                            console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
                                                                                            }






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Dec 26 '17 at 18:19









                                                                                            Mehdi Bouzidi

                                                                                            1,5963923




                                                                                            1,5963923










                                                                                            answered Apr 18 '12 at 14:46









                                                                                            Muhammad AlvinMuhammad Alvin

                                                                                            76458




                                                                                            76458








                                                                                            • 1





                                                                                              It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                              – Kzqai
                                                                                              Apr 18 '12 at 15:34














                                                                                            • 1





                                                                                              It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                              – Kzqai
                                                                                              Apr 18 '12 at 15:34








                                                                                            1




                                                                                            1





                                                                                            It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                            – Kzqai
                                                                                            Apr 18 '12 at 15:34





                                                                                            It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

                                                                                            – Kzqai
                                                                                            Apr 18 '12 at 15:34










                                                                                            1 2
                                                                                            next




                                                                                            protected by Josh Crozier Mar 17 '14 at 2:31



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            MongoDB - Not Authorized To Execute Command

                                                                                            How to fix TextFormField cause rebuild widget in Flutter

                                                                                            Npm cannot find a required file even through it is in the searched directory