How to loop through array in jQuery? - javascript

I am trying to loop through an array. I have the following code:
var currnt_image_list= '21,32,234,223';
var substr = currnt_image_list.split(','); // array here
Am trying to get all the data out of the array. Can some one lead me in the right path please?

(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each, isn't in it though.)
Four options:
Generic loop:
var i;
for (i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
or in ES2015+:
for (let i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).
ES5's forEach:
As of ECMAScript5, arrays have a forEach function on them which makes it easy to loop through the array:
substr.forEach(function(item) {
// do something with `item`
});
Link to docs
(Note: There are lots of other functions, not just forEach; see the answer referenced above for details.)
Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i variable in your containing scope.
Disadvantages: If you're using this in the containing code and you want to use this within your forEach callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach so forEach sets it as this during the callback, or C) Use an ES2015+ arrow function, which closes over this. If you don't do one of those things, in the callback this will be undefined (in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEach wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach is IE8 (and it can't be properly polyfilled there, either).
ES2015+'s for-of:
for (const s of substr) { // Or `let` if you want to modify it in the loop body
// do something with `s`
}
See the answer linked at the top of this answer for details on how that works.
Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.
Disadvantages: Not supported in any version of IE.
jQuery.each:
jQuery.each(substr, function(index, item) {
// do something with `item` (or `this` is also `item` if you like)
});
(Link to docs)
Advantages: All of the same advantages as forEach, plus you know it's there since you're using jQuery.
Disadvantages: If you're using this in the containing code, you have to stick it in a variable so you can use it within the function, since this means something else within the function.
You can avoid the this thing though, by either using $.proxy:
jQuery.each(substr, $.proxy(function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}, this));
...or Function#bind:
jQuery.each(substr, function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}.bind(this));
...or in ES2015 ("ES6"), an arrow function:
jQuery.each(substr, (index, item) => {
// do something with `item` (`this` is the same as it was outside)
});
What NOT to do:
Don't use for..in for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in does not do what many people think it does (it does something even more useful!). Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3
I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for..in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.

jQuery.each()
jQuery.each()
jQuery.each(array, callback)
array iteration
jQuery.each(array, function(Integer index, Object value){});
object iteration
jQuery.each(object, function(string propertyName, object propertyValue){});
example:
var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) {
console.log(index, val)
});
var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
javascript loops for array
for loop
for (initialExpression; condition; incrementExpression)
statement
example
var substr = [1, 2, 3, 4];
//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
console.log("loop", substr[i])
}
//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
console.log("reverse", substr[i])
}
//step loop
for(var i = 0; i < substr.length; i+=2) {
console.log("step", substr[i])
}
for in
//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
console.log(substr[i]) //note i returns index
}
for of
for(var i of subs) {
//can use break;
console.log(i); //note i returns value
}
forEach
substr.forEach(function(v, i, a){
//cannot use break;
console.log(v, i, a);
})
Resources
MDN loops and iterators

No need for jquery here, just a for loop works:
var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
alert(substr[i]);
}

Option 1 : The traditional for-loop
The basics
A traditional for-loop has three components :
the initialization : executed before the look block is executed the first time
the condition : checks a condition every time before the loop block is executed, and quits the loop if false
the afterthought : performed every time after the loop block is executed
These three components are seperated 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 tradtional 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 eg. this one :
for (var key = 0, value = myArray[key], var 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 :
Each of these variations is supported by all browsers, including véry old ones!
Option 2 : The 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);
}
Note :
Like traditional for-loops, while-loops are supported by even the oldest of browsers.
Also, 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);
}
Option 3 : 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 traditonal 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
}
Note :
You also need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least IE10.
Option 4 : 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);
});
Note :
Array.prototype.forEach() is supported by all modern browsers, as well as IE9+.
Option 5 : jQuery.each()
Additionally to the four other options mentioned, jQuery also had its own foreach variation.
It uses the following syntax :
$.each(myArray, function(key, value) {
console.log(value);
});

Use the each() function of jQuery.
Here is an example:
$.each(currnt_image_list.split(','), function(index, value) {
alert(index + ': ' + value);
});

ES6 syntax with arrow function and interpolation:
var data=["a","b","c"];
$(data).each((index, element) => {
console.log(`current index : ${index} element : ${element}`)
});

Use jQuery each(). There are other ways but each is designed for this purpose.
$.each(substr, function(index, value) {
alert(value);
});
And do not put the comma after the last number.

You can use a for() loop:
var things = currnt_image_list.split(',');
for(var i = 0; i < things.length; i++) {
//Do things with things[i]
}

Try this:
$.grep(array, function(element) {
})

$.map(data,function(elem) {...})
$.map(data,function(elem){
console.log(elem);
})

Alternative ways of iteration through array/string with side effects
var str = '21,32,234,223';
var substr = str.split(',');
substr.reduce((a,x)=> console.log('reduce',x), 0) // return undefined
substr.every(x=> { console.log('every',x); return true}) // return true
substr.some(x=> { console.log('some',x); return false}) // return false
substr.map(x=> console.log('map',x)); // return array
str.replace(/(\d+)/g, x=> console.log('replace',x)) // return string

for(var key in substr)
{
// do something with substr[key];
}

Related

adding values to TypeScript Object [duplicate]

How can I loop through all the entries in an array using JavaScript?
TL;DR
Your best bets are usually
a for-of loop (ES2015+ only; spec | MDN) - simple and async-friendly
for (const element of theArray) {
// ...use `element`...
}
forEach (ES5+ only; spec | MDN) (or its relatives some and such) - not async-friendly (but see details)
theArray.forEach(element => {
// ...use `element`...
});
a simple old-fashioned for loop - async-friendly
for (let index = 0; index < theArray.length; ++index) {
const element = theArray[index];
// ...use `element`...
}
(rarely) for-in with safeguards - async-friendly
for (const propertyName in theArray) {
if (/*...is an array element property (see below)...*/) {
const element = theArray[propertyName];
// ...use `element`...
}
}
Some quick "don't"s:
Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
Don't use map if you're not using its return value.(There's sadly someone out there teaching map [spec / MDN] as though it were forEach — but as I write on my blog, that's not what it's for. If you aren't using the array it creates, don't use map.)
Don't use forEach if the callback does asynchronous work and you want the forEach to wait until that work is done (because it won't).
But there's lots more to explore, read on...
JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the arguments object, other iterable objects (ES2015+), DOM collections, and so on.
Okay, let's look at our options:
For Actual Arrays
You have five options (two supported basically forever, another added by ECMAScript 5 ["ES5"], and two more added in ECMAScript 2015 ("ES2015", aka "ES6"):
Use for-of (use an iterator implicitly) (ES2015+)
Use forEach and related (ES5+)
Use a simple for loop
Use for-in correctly
Use an iterator explicitly (ES2015+)
(You can see those old specs here: ES5, ES2015, but both have been superceded; the current editor's draft is always here.)
Details:
1. Use for-of (use an iterator implicitly) (ES2015+)
ES2015 added iterators and iterables to JavaScript. Arrays are iterable (so are strings, Maps, and Sets, as well as DOM collections and lists, as you'll see later). Iterable objects provide iterators for their values. The new for-of statement loops through the values returned by an iterator:
const a = ["a", "b", "c"];
for (const element of a) { // You can use `let` instead of `const` if you like
console.log(element);
}
// a
// b
// c
It doesn't get simpler than that! Under the covers, that gets an iterator from the array and loops through the values the iterator returns. The iterator provided by arrays provides the values of the array elements, in order beginning to end.
Notice how element is scoped to each loop iteration; trying to use element after the end of the loop would fail because it doesn't exist outside the loop body.
In theory, a for-of loop involves several function calls (one to get the iterator, then one to get each value from it). Even when that's true, it's nothing to worry about, function calls are very cheap in modern JavaScript engines (it bothered me for forEach [below] until I looked into it; details). But additionally, JavaScript engines optimize those calls away (in performance-critical code) when dealing with native iterators for things like arrays.
for-of is entirely async-friendly. If you need the work in a loop body to be done in series (not in parallel), an await in the loop body will wait for the promise to settle before continuing. Here's a silly example:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function showSlowly(messages) {
for (const message of messages) {
await delay(400);
console.log(message);
}
}
showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);
// `.catch` omitted because we know it never rejects
Note how the words appear with a delay before each one.
It's a matter of coding style, but for-of is the first thing I reach for when looping through anything iterable.
2. Use forEach and related
In any even vaguely-modern environment (so, not IE8) where you have access to the Array features added by ES5, you can use forEach (spec | MDN) if you're only dealing with synchronous code (or you don't need to wait for an asynchronous process to finish during the loop):
const a = ["a", "b", "c"];
a.forEach((element) => {
console.log(element);
});
forEach accepts a callback function and, optionally, a value to use as this when calling that callback (not used above). The callback is called for each element in the array, in order, skipping non-existent elements in sparse arrays. Although I only used one parameter above, the callback is called with three arguments: The element for that iteration, the index of that element, and a reference to the array you're iterating over (in case your function doesn't already have it handy).
Like for-of, forEach has the advantage that you don't have to declare indexing and value variables in the containing scope; in this case, they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.
Unlike for-of, forEach has the disadvantage that it doesn't understand async functions and await. If you use an async function as the callback, forEach does not wait for that function's promise to settle before continuing. Here's the async example from for-of using forEach instead — notice how there's an initial delay, but then all the text appears right away instead of waiting:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function showSlowly(messages) {
// INCORRECT, doesn't wait before continuing,
// doesn't handle promise rejections
messages.forEach(async message => {
await delay(400);
console.log(message);
});
}
showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);
// `.catch` omitted because we know it never rejects
forEach is the "loop through them all" function, but ES5 defined several other useful "work your way through the array and do things" functions, including:
every (spec | MDN) - stops looping the first time the callback returns a falsy value
some (spec | MDN) - stops looping the first time the callback returns a truthy value
filter (spec | MDN) - creates a new array including elements where the callback returns a truthy value, omitting the ones where it doesn't
map (spec | MDN) - creates a new array from the values returned by the callback
reduce (spec | MDN) - builds up a value by repeatedly calling the callback, passing in previous values; see the spec for the details
reduceRight (spec | MDN) - like reduce, but works in descending rather than ascending order
As with forEach, if you use an async function as your callback, none of those waits for the function's promise to settle. That means:
Using an async function callback is never appropriate with every, some, and filter since they will treat the returned promise as though it were a truthy value; they don't wait for the promise to settle and then use the fulfillment value.
Using an async function callback is often appropriate with map, if the goal is to turn an array of something into an array of promises, perhaps for passing to one of the promise combinator functions (Promise.all, Promise.race, promise.allSettled, or Promise.any).
Using an async function callback is rarely appropriate with reduce or reduceRight, because (again) the callback will always return a promise. But there is an idiom of building a chain of promises from an array that uses reduce (const promise = array.reduce((p, element) => p.then(/*...something using `element`...*/));), but usually in those cases a for-of or for loop in an async function will be clearer and easier to debug.
3. Use a simple for loop
Sometimes the old ways are the best:
const a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
const element = a[index];
console.log(element);
}
If the length of the array won't change during the loop, and it's in highly performance-sensitive code, a slightly more complicated version grabbing the length up front might be a tiny bit faster:
const a = ["a", "b", "c"];
for (let index = 0, len = a.length; index < len; ++index) {
const element = a[index];
console.log(element);
}
And/or counting backward:
const a = ["a", "b", "c"];
for (let index = a.length - 1; index >= 0; --index) {
const element = a[index];
console.log(element);
}
But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.
Before ES2015, the loop variable had to exist in the containing scope, because var only has function-level scope, not block-level scope. But as you saw in the examples above, you can use let within the for to scope the variables to just the loop. And when you do that, the index variable is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index for that specific iteration, which solves the old "closures in loops" problem:
// (The `NodeList` from `querySelectorAll` is array-like)
const divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
divs[index].addEventListener('click', e => {
console.log("Index is: " + index);
});
}
<div>zero</div>
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
In the above, you get "Index is: 0" if you click the first and "Index is: 4" if you click the last. This does not work if you use var instead of let (you'd always see "Index is: 5").
Like for-of, for loops work well in async functions. Here's the earlier example using a for loop:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function showSlowly(messages) {
for (let i = 0; i < messages.length; ++i) {
const message = messages[i];
await delay(400);
console.log(message);
}
}
showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);
// `.catch` omitted because we know it never rejects
4. Use for-in correctly
for-in isn't for looping through arrays, it's for looping through the names of an object's properties. It does often seem to work for looping through arrays as a by-product of the fact that arrays are objects, but it doesn't just loop through the array indexes, it loops through all enumerable properties of the object (including inherited ones). (It also used to be that the order wasn't specified; it is now [details in this other answer], but even though the order is specified now, the rules are complex, there are exceptions, and relying on the order is not best practice.)
The only real use cases for for-in on an array are:
It's a sparse array with massive gaps in it, or
You're using non-element properties on the array object and you want to include them in the loop
Looking only at that first example: You can use for-in to visit those sparse array elements if you use appropriate safeguards:
// `a` is a sparse array
const a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (const name in a) {
if (Object.hasOwn(a, name) && // These checks are
/^0$|^[1-9]\d*$/.test(name) && // explained
name <= 4294967294 // below
) {
const element = a[name];
console.log(a[name]);
}
}
Note the three checks:
That the object has its own property by that name (not one it inherits from its prototype; this check is also often written as a.hasOwnProperty(name) but ES2022 adds Object.hasOwn which can be more reliable), and
That the name is all decimal digits (e.g., normal string form, not scientific notation), and
That the name's value when coerced to a number is <= 2^32 - 2 (which is 4,294,967,294). Where does that number come from? It's part of the definition of an array index in the specification. Other numbers (non-integers, negative numbers, numbers greater than 2^32 - 2) are not array indexes. The reason it's 2^32 - 2 is that that makes the greatest index value one lower than 2^32 - 1, which is the maximum value an array's length can have. (E.g., an array's length fits in a 32-bit unsigned integer.)
...although with that said, most code only does the hasOwnProperty check.
You wouldn't do that in inline code, of course. You'd write a utility function. Perhaps:
// Utility function for antiquated environments without `forEach`
const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
const rexNum = /^0$|^[1-9]\d*$/;
function sparseEach(array, callback, thisArg) {
for (const name in array) {
const index = +name;
if (hasOwn(a, name) &&
rexNum.test(name) &&
index <= 4294967294
) {
callback.call(thisArg, array[name], index, array);
}
}
}
const a = [];
a[5] = "five";
a[10] = "ten";
a[100000] = "one hundred thousand";
a.b = "bee";
sparseEach(a, (value, index) => {
console.log("Value at " + index + " is " + value);
});
Like for, for-in works well in asynchronous functions if the work within it needs to be done in series.
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function showSlowly(messages) {
for (const name in messages) {
if (messages.hasOwnProperty(name)) { // Almost always this is the only check people do
const message = messages[name];
await delay(400);
console.log(message);
}
}
}
showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);
// `.catch` omitted because we know it never rejects
5. Use an iterator explicitly (ES2015+)
for-of uses an iterator implicitly, doing all the scut work for you. Sometimes, you might want to use an iterator explicitly. It looks like this:
const a = ["a", "b", "c"];
const it = a.values(); // Or `const it = a[Symbol.iterator]();` if you like
let entry;
while (!(entry = it.next()).done) {
const element = entry.value;
console.log(element);
}
An iterator is an object matching the Iterator definition in the specification. Its next method returns a new result object each time you call it. The result object has a property, done, telling us whether it's done, and a property value with the value for that iteration. (done is optional if it would be false, value is optional if it would be undefined.)
What you get for value varies depending on the iterator. On arrays, the default iterator provides the value of each array element ("a", "b", and "c" in the example earlier). Arrays also have three other methods that return iterators:
values(): This is an alias for the [Symbol.iterator] method that returns the default iterator.
keys(): Returns an iterator that provides each key (index) in the array. In the example above, it would provide "0", then "1", then "2" (yes, as strings).
entries(): Returns an iterator that provides [key, value] arrays.
Since iterator objects don't advance until you call next, they work well in async function loops. Here's the earlier for-of example using the iterator explicitly:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function showSlowly(messages) {
const it = messages.values()
while (!(entry = it.next()).done) {
await delay(400);
const element = entry.value;
console.log(element);
}
}
showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);
// `.catch` omitted because we know it never rejects
For Array-Like Objects
Aside from true arrays, there are also array-like objects that have a length property and properties with all-digits names: NodeList instances, HTMLCollection instances, the arguments object, etc. How do we loop through their contents?
Use most of the options above
At least some, and possibly most or even all, of the array approaches above apply equally well to array-like objects:
Use for-of (use an iterator implicitly) (ES2015+)
for-of uses the iterator provided by the object (if any). That includes host-provided objects (like DOM collections and lists). For instance, HTMLCollection instances from getElementsByXYZ methods and NodeLists instances from querySelectorAll both support iteration. (This is defined quite subtly by the HTML and DOM specifications. Basically, any object with length and indexed access is automatically iterable. It doesn't have to be marked iterable; that is used only for collections that, in addition to being iterable, support forEach, values, keys, and entries methods. NodeList does; HTMLCollection doesn't, but both are iterable.)
Here's an example of looping through div elements:
const divs = document.querySelectorAll("div");
for (const div of divs) {
div.textContent = Math.random();
}
<div>zero</div>
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
Use forEach and related (ES5+)
The various functions on Array.prototype are "intentionally generic" and can be used on array-like objects via Function#call (spec | MDN) or Function#apply (spec | MDN). (If you have to deal with IE8 or earlier [ouch], see the "Caveat for host-provided objects" at the end of this answer, but it's not an issue with vaguely-modern browsers.)
Suppose you wanted to use forEach on a Node's childNodes collection (which, being an HTMLCollection, doesn't have forEach natively). You'd do this:
Array.prototype.forEach.call(node.childNodes, (child) => {
// Do something with `child`
});
(Note, though, that you could just use for-of on node.childNodes.)
If you're going to do that a lot, you might want to grab a copy of the function reference into a variable for reuse, e.g.:
// (This is all presumably in a module or some scoping function)
const forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// Then later...
forEach(node.childNodes, (child) => {
// Do something with `child`
});
Use a simple for loop
Perhaps obviously, a simple for loop works for array-like objects.
Use an iterator explicitly (ES2015+)
See #1.
You may be able to get away with for-in (with safeguards), but with all of these more appropriate options, there's no reason to try.
Create a true array
Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:
Use Array.from
Array.from (spec) | (MDN) (ES2015+, but easily polyfilled) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:
const divs = Array.from(document.querySelectorAll("div"));
...takes the NodeList from querySelectorAll and makes an array from it.
The mapping function is handy if you were going to map the contents in some way. For instance, if you wanted to get an array of the tag names of the elements with a given class:
// Typical use (with an arrow function):
const divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);
// Traditional function (since `Array.from` can be polyfilled):
var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
return element.tagName;
});
Use spread syntax (...)
It's also possible to use ES2015's spread syntax. Like for-of, this uses the iterator provided by the object (see #1 in the previous section):
const trueArray = [...iterableObject];
So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:
const divs = [...document.querySelectorAll("div")];
Use the slice method of arrays
We can use the slice method of arrays, which like the other methods mentioned above is "intentionally generic" and so can be used with array-like objects, like this:
const trueArray = Array.prototype.slice.call(arrayLikeObject);
So for instance, if we want to convert a NodeList into a true array, we could do this:
const divs = Array.prototype.slice.call(document.querySelectorAll("div"));
(If you still have to handle IE8 [ouch], will fail; IE8 didn't let you use host-provided objects as this like that.)
Caveat for host-provided objects
If you use Array.prototype functions with host-provided array-like objects (for example, DOM collections and such provided by the browser rather than the JavaScript engine), obsolete browsers like IE8 didn't necessarily handle that way, so if you have to support them, be sure to test in your target environments. But it's not an issue with vaguely-modern browsers. (For non-browser environments, naturally it'll depend on the environment.)
Note: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:
forEach
map
filter
zip
reduce
every
some
The standard way to iterate an array in JavaScript is a vanilla for-loop:
var length = arr.length,
element = null;
for (var i = 0; i < length; i++) {
element = arr[i];
// Do something with element
}
Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a for .. in-loop might be a better idea. However, you must use the appropriate safeguards to ensure that only the desired properties of the array (that is, the array elements) are acted upon, since the for..in-loop will also be enumerated in legacy browsers, or if the additional properties are defined as enumerable.
In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include.
If you’re using the jQuery library, you can use jQuery.each:
$.each(yourArray, function(index, value) {
// do your stuff here
});
EDIT :
As per question, user want code in javascript instead of jquery so the edit is
var length = yourArray.length;
for (var i = 0; i < length; i++) {
// Do something with yourArray[i].
}
Loop backwards
I think the reverse for loop deserves a mention here:
for (var i = array.length; i--; ) {
// process array[i]
}
Advantages:
You do not need to declare a temporary len variable, or compare against array.length on each iteration, either of which might be a minute optimisation.
Removing siblings from the DOM in reverse order is usually more efficient. (The browser needs to do less shifting of elements in its internal arrays.)
If you modify the array while looping, at or after index i (for example you remove or insert an item at array[i]), then a forward loop would skip the item that shifted left into position i, or re-process the ith item that was shifted right. In a traditional for loop, you could update i to point to the next item that needs processing - 1, but simply reversing the direction of iteration is often a simpler and more elegant solution.
Similarly, when modifying or removing nested DOM elements, processing in reverse can circumvent errors. For example, consider modifying the innerHTML of a parent node before handling its children. By the time the child node is reached it will be detached from the DOM, having been replaced by a newly created child when the parent's innerHTML was written.
It is shorter to type, and read, than some of the other options available. Although it loses to forEach() and to ES6's for ... of.
Disadvantages:
It processes the items in reverse order. If you were building a new array from the results, or printing things on screen, naturally the output will be reversed with respect to the original order.
Repeatedly inserting siblings into the DOM as a first child in order to retain their order is less efficient. (The browser would keep having to shift things right.) To create DOM nodes efficiently and in order, just loop forwards and append as normal (and also use a "document fragment").
The reverse loop is confusing to junior developers. (You may consider that an advantage, depending on your outlook.)
Should I always use it?
Some developers use the reverse for loop by default, unless there is a good reason to loop forwards.
Although the performance gains are usually insignificant, it sort of screams:
"Just do this to every item in the list, I don't care about the order!"
However in practice that is not actually a reliable indication of intent, since it is indistinguishable from those occasions when you do care about the order, and really do need to loop in reverse. So in fact another construct would be needed to accurately express the "don't care" intent, something currently unavailable in most languages, including ECMAScript, but which could be called, for example, forEachUnordered().
If order doesn't matter, and efficiency is a concern (in the innermost loop of a game or animation engine), then it may be acceptable to use the reverse for loop as your go-to pattern. Just remember that seeing a reverse for loop in existing code does not necessarily mean that the order irrelevant!
It was better to use forEach()
In general for higher level code where clarity and safety are greater concerns, I previously recommended using Array::forEach as your default pattern for looping (although these days I prefer to use for..of). Reasons to prefer forEach over a reverse loop are:
It is clearer to read.
It indicates that i is not going to be shifted within the block (which is always a possible surprise hiding in long for and while loops).
It gives you a free scope for closures.
It reduces leakage of local variables and accidental collision with (and mutation of) outer variables.
Then when you do see the reverse for loop in your code, that is a hint that it is reversed for a good reason (perhaps one of the reasons described above). And seeing a traditional forward for loop may indicate that shifting can take place.
(If the discussion of intent makes no sense to you, then you and your code may benefit from watching Crockford's lecture on Programming Style & Your Brain.)
It is now even better to use for..of!
There is a debate about whether for..of or forEach() are preferable:
For maximum browser support, for..of requires a polyfill for iterators, making your app slightly slower to execute and slightly larger to download.
For that reason (and to encourage use of map and filter), some front-end style guides ban for..of completely!
But the above concerns is not applicable to Node.js applications, where for..of is now well supported.
And furthermore await does not work inside forEach(). Using for..of is the clearest pattern in this case.
Personally, I tend to use whatever looks easiest to read, unless performance or minification has become a major concern. So these days I prefer to use for..of instead of forEach(), but I will always use map or filter or find or some when applicable.
(For the sake of my colleagues, I rarely use reduce.)
How does it work?
for (var i = 0; i < array.length; i++) { ... } // Forwards
for (var i = array.length; i--; ) { ... } // Reverse
You will notice that i-- is the middle clause (where we usually see a comparison) and the last clause is empty (where we usually see i++). That means that i-- is also used as the condition for continuation. Crucially, it is executed and checked before each iteration.
How can it start at array.length without exploding?
Because i-- runs before each iteration, on the first iteration we will actually be accessing the item at array.length - 1 which avoids any issues with Array-out-of-bounds undefined items.
Why doesn't it stop iterating before index 0?
The loop will stop iterating when the condition i-- evaluates to a falsey value (when it yields 0).
The trick is that unlike --i, the trailing i-- operator decrements i but yields the value before the decrement. Your console can demonstrate this:
> var i = 5; [i, i--, i];
[5, 5, 4]
So on the final iteration, i was previously 1 and the i-- expression changes it to 0 but actually yields 1 (truthy), and so the condition passes. On the next iteration i-- changes i to -1 but yields 0 (falsey), causing execution to immediately drop out of the bottom of the loop.
In the traditional forwards for loop, i++ and ++i are interchangeable (as Douglas Crockford points out). However in the reverse for loop, because our decrement is also our condition expression, we must stick with i-- if we want to process the item at index 0.
Trivia
Some people like to draw a little arrow in the reverse for loop, and end with a wink:
for (var i = array.length; i --> 0 ;) {
Credits go to WYL for showing me the benefits and horrors of the reverse for loop.
Some C-style languages use foreach to loop through enumerations. In JavaScript this is done with the for..in loop structure:
var index,
value;
for (index in obj) {
value = obj[index];
}
There is a catch. for..in will loop through each of the object's enumerable members, and the members on its prototype. To avoid reading values that are inherited through the object's prototype, simply check if the property belongs to the object:
for (i in obj) {
if (obj.hasOwnProperty(i)) {
//do stuff
}
}
Additionally, ECMAScript 5 has added a forEach method to Array.prototype which can be used to enumerate over an array using a calback (the polyfill is in the docs so you can still use it for older browsers):
arr.forEach(function (val, index, theArray) {
//do stuff
});
It's important to note that Array.prototype.forEach doesn't break when the callback returns false. jQuery and Underscore.js provide their own variations on each to provide loops that can be short-circuited.
for...of | forEach | map
Using modern JavaScript syntax to iterate through arrays
const fruits = ['🍎', '🍋', '🍌' ]
👉🏽   for...of
for (const fruit of fruits) {
console.log(fruit) // '🍎', '🍋', '🍌'
}
👉🏽   forEach
fruits.forEach(fruit => {
console.log(fruit) // '🍎', '🍋', '🍌'
})
👉🏽   map
*Different from the two above, map() creates a new array and expects you to return something after each iteration.
fruits.map(fruit => fruit) // ['🍎', '🍋', '🍌' ]
🛑  Important: As map() is meant to return a value at each iteration, it is an ideal method for transforming elements in arrays:
fruits.map(fruit => 'cool ' + fruit) // ['cool 🍎', 'cool 🍋', 'cool 🍌' ]
On the other hand, for...of and forEach( ) don't need to return anything and that's why we typically use them to perform logic tasks that manipulate stuff outside.
So to speak, you're going to find if () statements, side effects, and logging activities in these two.
👌🏾  TIP: you can also have the index (as well as the whole array) in each iteration in your .map() or .forEach() functions.
Just pass additional arguments to them:
fruits.map((fruit, i) => i + ' ' + fruit)
// ['0 🍎', '1 🍋', '2 🍌' ]
fruits.forEach((f, i, arr) => {
console.log( f + ' ' + i + ' ' + arr )
})
// 🍎 0 🍎, 🍋, 🍌,
// 🍋 1 🍎, 🍋, 🍌,
// 🍌 2 🍎, 🍋, 🍌,
If you want to loop over an array, use the standard three-part for loop.
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
You can get some performance optimisations by caching myArray.length or iterating over it backwards.
If you don't mind emptying the array:
var x;
while(x = y.pop()){
alert(x); //do something
}
x will contain the last value of y and it will be removed from the array. You can also use shift() which will give and remove the first item from y.
A forEach implementation (see in jsFiddle):
function forEach(list,callback) {
var length = list.length;
for (var n = 0; n < length; n++) {
callback.call(list[n]);
}
}
var myArray = ['hello','world'];
forEach(
myArray,
function(){
alert(this); // do something
}
);
I know this is an old post, and there are so many great answers already. For a little more completeness I figured I'd throw in another one using AngularJS. Of course, this only applies if you're using Angular, obviously, nonetheless I'd like to put it anyway.
angular.forEach takes 2 arguments and an optional third argument. The first argument is the object (array) to iterate over, the second argument is the iterator function, and the optional third argument is the object context (basically referred to inside the loop as 'this'.
There are different ways to use the forEach loop of angular. The simplest and probably most used is
var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
//item will be each element in the array
//do something
});
Another way that is useful for copying items from one array to another is
var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);
Though, you don't have to do that, you can simply do the following and it's equivalent to the previous example:
angular.forEach(temp, function(item) {
temp2.push(item);
});
Now there are pros and cons of using the angular.forEach function as opposed to the built in vanilla-flavored for loop.
Pros
Easy readability
Easy writability
If available, angular.forEach will use the ES5 forEach loop. Now, I will get to efficientcy in the cons section, as the forEach loops are much slower than the for loops. I mention this as a pro because it's nice to be consistent and standardized.
Consider the following 2 nested loops, which do exactly the same thing. Let's say that we have 2 arrays of objects and each object contains an array of results, each of which has a Value property that's a string (or whatever). And let's say we need to iterate over each of the results and if they're equal then perform some action:
angular.forEach(obj1.results, function(result1) {
angular.forEach(obj2.results, function(result2) {
if (result1.Value === result2.Value) {
//do something
}
});
});
//exact same with a for loop
for (var i = 0; i < obj1.results.length; i++) {
for (var j = 0; j < obj2.results.length; j++) {
if (obj1.results[i].Value === obj2.results[j].Value) {
//do something
}
}
}
Granted this is a very simple hypothetical example, but I've written triple embedded for loops using the second approach and it was very hard to read, and write for that matter.
Cons
Efficiency. angular.forEach, and the native forEach, for that matter, are both so much slower than the normal for loop....about 90% slower. So for large data sets, best to stick to the native for loop.
No break, continue, or return support. continue is actually supported by "accident", to continue in an angular.forEach you simple put a return; statement in the function like angular.forEach(array, function(item) { if (someConditionIsTrue) return; }); which will cause it to continue out of the function for that iteration. This is also due to the fact that the native forEach does not support break or continue either.
I'm sure there's various other pros and cons as well, and please feel free to add any that you see fit. I feel that, bottom line, if you need efficiency, stick with just the native for loop for your looping needs. But, if your datasets are smaller and a some efficiency is okay to give up in exchange for readability and writability, then by all means throw an angular.forEach in that bad boy.
As of ECMAScript 6:
list = [0, 1, 2, 3]
for (let obj of list) {
console.log(obj)
}
Where of avoids the oddities associated with in and makes it work like the for loop of any other language, and let binds i within the loop as opposed to within the function.
The braces ({}) can be omitted when there is only one command (e.g. in the example above).
Probably the for(i = 0; i < array.length; i++) loop is not the best choice. Why? If you have this:
var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";
The method will call from array[0] to array[2]. First, this will first reference variables you don't even have, second you would not have the variables in the array, and third this will make the code bolder. Look here, it's what I use:
for(var i in array){
var el = array[i];
//If you want 'i' to be INT just put parseInt(i)
//Do something with el
}
And if you want it to be a function, you can do this:
function foreach(array, call){
for(var i in array){
call(array[i]);
}
}
If you want to break, a little more logic:
function foreach(array, call){
for(var i in array){
if(call(array[i]) == false){
break;
}
}
}
Example:
foreach(array, function(el){
if(el != "!"){
console.log(el);
} else {
console.log(el+"!!");
}
});
It returns:
//Hello
//World
//!!!
There are three implementations of foreach in jQuery as follows.
var a = [3,2];
$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3
An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as each and will automatically delegate the job to the native forEach if available.
A CodePen example of how it works is:
var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});
See also
Documentation for native Array.prototype.forEach().
In for_each...in (MDN) it is explained that for each (variable in object) is deprecated as the part of ECMA-357 (EAX) standard.
for...of (MDN) describes the next way of iterating using for (variable of object) as the part of the Harmony (ECMAScript 6) proposal.
There isn't any for each loop in native JavaScript. You can either use libraries to get this functionality (I recommend Underscore.js), use a simple for in loop.
for (var instance in objects) {
...
}
However, note that there may be reasons to use an even simpler for loop (see Stack Overflow question Why is using “for…in” with array iteration such a bad idea?)
var instance;
for (var i=0; i < objects.length; i++) {
var instance = objects[i];
...
}
ECMAScript 5 (the version on JavaScript) to work with Arrays:
forEach - Iterates through every item in the array and do whatever you need with each item.
['C', 'D', 'E'].forEach(function(element, index) {
console.log(element + " is #" + (index+1) + " in the musical scale");
});
// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale
In case, more interested on operation on array using some inbuilt feature.
map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.
// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
return elem.toUpperCase();
});
// Output: ['BOB', 'JOE', 'JEN']
reduce - As the name says, it reduces the array to a single value by calling the given function passing in the current element and the result of the previous execution.
[1,2,3,4].reduce(function(previous, current) {
return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10
every - Returns true or false if all the elements in the array pass the test in the callback function.
// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
return elem >= 18;
});
// Output: false
filter - Very similar to every except that filter returns an array with the elements that return true to the given function.
// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
return (elem % 2 == 0)
});
// Output: [2,4,6]
There are a few ways to loop through an array in JavaScript, as below:
for - it's the most common one. Full block of code for looping
var languages = ["Java", "JavaScript", "C#", "Python"];
var i, len, text;
for (i = 0, len = languages.length, text = ""; i < len; i++) {
text += languages[i] + "<br>";
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>
while - loop while a condition is through. It seems to be the fastest loop
var text = "";
var i = 0;
while (i < 10) {
text += i + ") something<br>";
i++;
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>
do/while - also loop through a block of code while the condition is true, will run at least one time
var text = ""
var i = 0;
do {
text += i + ") something <br>";
i++;
}
while (i < 10);
document.getElementById("example").innerHTML = text;
<p id="example"></p>
Functional loops - forEach, map, filter, also reduce (they loop through the function, but they are used if you need to do something with your array, etc.
// For example, in this case we loop through the number and double them up using the map function
var numbers = [65, 44, 12, 4];
document.getElementById("example").innerHTML = numbers.map(function(num){return num * 2});
<p id="example"></p>
For more information and examples about functional programming on arrays, look at the blog post Functional programming in JavaScript: map, filter and reduce.
This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)
function each( fn, data ) {
if(typeof fn == 'string')
eval('fn = function(data, i){' + fn + '}');
for(var i=0, L=this.length; i < L; i++)
fn.call( this[i], data, i );
return this;
}
Array.prototype.each = each;
Examples of usage:
Example #1
var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]
Example #2
each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');
Each p tag gets class="blue"
Example #3
each.call(document.getElementsByTagName('p'),
"if( i % 2 == 0) this.className = data;",
'red'
);
Every other p tag gets class="red">
Example #4
each.call(document.querySelectorAll('p.blue'),
function(newClass, i) {
if( i < 20 )
this.className = newClass;
}, 'green'
);
And finally the first 20 blue p tags are changed to green
Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive.
There's no inbuilt ability to break in forEach. To interrupt execution use the Array#some like below:
[1,2,3].some(function(number) {
return number === 1;
});
This works because some returns true as soon as any of the callbacks, executed in array order, returns true, short-circuiting the execution of the rest.
Original Answer
see Array prototype for some
I also would like to add this as a composition of a reverse loop and an answer above for someone that would like this syntax too.
var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
console.log(item);
}
Pros:
The benefit for this: You have the reference already in the first like that won't need to be declared later with another line. It is handy when looping trough the object array.
Cons:
This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. And also depending on the browser it can be "not" optimized to work faster than the original one.
jQuery way using $.map:
var data = [1, 2, 3, 4, 5, 6, 7];
var newData = $.map(data, function(element) {
if (element % 2 == 0) {
return element;
}
});
// newData = [2, 4, 6];
Use for...of where possible
async/await support
Skips non-numeric props
Immutable index
for...of
✅
✅
✅
forEach()
❌
✅
✅
for...in
✅
❌
✅
Regular for
✅
✅
❌
As one can see in the table above, for...of should be used wherever it fits. Since it supports async functions, skips non-numeric properties and prevents messing up the loop by accidentally modifying the loop index.
Syntax
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
/* Do something with num */
}
See for...of reference for more examples, link to specification and difference between for...of and for...in. Or maybe check this tutorial for some explanation on how they differ.
Using loops with ECMAScript 6 destructuring and the spread operator
Destructuring and using of the spread operator have proven quite useful for newcomers to ECMAScript 6 as being more human-readable/aesthetic, although some JavaScript veterans might consider it messy. Juniors or some other people might find it useful.
The following examples will use the for...of statement and the .forEach method.
Examples 6, 7, and 8 can be used with any functional loops like .map, .filter, .reduce, .sort, .every, .some. For more information about these methods, check out the Array Object.
Example 1: Normal for...of loop - no tricks here.
let arrSimple = ['a', 'b', 'c'];
for (let letter of arrSimple) {
console.log(letter);
}
Example 2: Split words to characters
let arrFruits = ['apple', 'orange', 'banana'];
for (let [firstLetter, ...restOfTheWord] of arrFruits) {
// Create a shallow copy using the spread operator
let [lastLetter] = [...restOfTheWord].reverse();
console.log(firstLetter, lastLetter, restOfTheWord);
}
Example 3: Looping with a key and value
// let arrSimple = ['a', 'b', 'c'];
// Instead of keeping an index in `i` as per example `for(let i = 0 ; i<arrSimple.length;i++)`
// this example will use a multi-dimensional array of the following format type:
// `arrWithIndex: [number, string][]`
let arrWithIndex = [
[0, 'a'],
[1, 'b'],
[2, 'c'],
];
// Same thing can be achieved using `.map` method
// let arrWithIndex = arrSimple.map((i, idx) => [idx, i]);
// Same thing can be achieved using `Object.entries`
// NOTE: `Object.entries` method doesn't work on Internet Explorer unless it's polyfilled
// let arrWithIndex = Object.entries(arrSimple);
for (let [key, value] of arrWithIndex) {
console.log(key, value);
}
Example 4: Get object properties inline
let arrWithObjects = [{
name: 'Jon',
age: 32
},
{
name: 'Elise',
age: 33
}
];
for (let { name, age: aliasForAge } of arrWithObjects) {
console.log(name, aliasForAge);
}
Example 5: Get deep object properties of what you need
let arrWithObjectsWithArr = [{
name: 'Jon',
age: 32,
tags: ['driver', 'chef', 'jogger']
},
{
name: 'Elise',
age: 33,
tags: ['best chef', 'singer', 'dancer']
}
];
for (let { name, tags: [firstItemFromTags, ...restOfTags] } of arrWithObjectsWithArr) {
console.log(name, firstItemFromTags, restOfTags);
}
Example 6: Is Example 3 used with .forEach
let arrWithIndex = [
[0, 'a'],
[1, 'b'],
[2, 'c'],
];
// Not to be confused here, `forEachIndex` is the real index
// `mappedIndex` was created by "another user", so you can't really trust it
arrWithIndex.forEach(([mappedIndex, item], forEachIndex) => {
console.log(forEachIndex, mappedIndex, item);
});
Example 7: Is Example 4 used with .forEach
let arrWithObjects = [{
name: 'Jon',
age: 32
},
{
name: 'Elise',
age: 33
}
];
// NOTE: Destructuring objects while using shorthand functions
// are required to be surrounded by parentheses
arrWithObjects.forEach( ({ name, age: aliasForAge }) => {
console.log(name, aliasForAge)
});
Example 8: Is Example 5 used with .forEach
let arrWithObjectsWithArr = [{
name: 'Jon',
age: 32,
tags: ['driver', 'chef', 'jogger']
},
{
name: 'Elise',
age: 33,
tags: ['best chef', 'singer', 'dancer']
}
];
arrWithObjectsWithArr.forEach(({
name,
tags: [firstItemFromTags, ...restOfTags]
}) => {
console.log(name, firstItemFromTags, restOfTags);
});
Summary:
When iterating over an array, we often want to accomplish one of the following goals:
We want to iterate over the array and create a new array:
Array.prototype.map
We want to iterate over the array and don't create a new array:
Array.prototype.forEach
for..of loop
In JavaScript, there are many ways of accomplishing both of these goals. However, some are more convenient than others. Below you can find some commonly used methods (the most convenient IMO) to accomplish array iteration in JavaScript.
Creating new array: Map
map() is a function located on Array.prototype which can transform every element of an array and then returns a new array. map() takes as an argument a callback function and works in the following manner:
let arr = [1, 2, 3, 4, 5];
let newArr = arr.map((element, index, array) => {
return element * 2;
})
console.log(arr);
console.log(newArr);
The callback which we have passed into map() as an argument gets executed for every element. Then an array gets returned which has the same length as the original array. In this new array element is transformed by the callback function passed in as an argument to map().
The distinct difference between map and another loop mechanism like forEach and a for..of loop is that map returns a new array and leaves the old array intact (except if you explicitly manipulate it with thinks like splice).
Also, note that the map function's callback provides the index number of the current iteration as a second argument. Furthermore, does the third argument provide the array on which map was called? Sometimes these properties can be very useful.
Loop using forEach
forEach is a function which is located on Array.prototype which takes a callback function as an argument. It then executes this callback function for every element in the array. In contrast to the map() function, the forEach function returns nothing (undefined). For example:
let arr = [1, 2, 3, 4, 5];
arr.forEach((element, index, array) => {
console.log(element * 2);
if (index === 4) {
console.log(array)
}
// index, and oldArray are provided as 2nd and 3th argument by the callback
})
console.log(arr);
Just like the map function, the forEach callback provides the index number of the current iteration as a second argument. Also, does the third argument provide the array on which forEach was called?
Loop through elements using for..of
The for..of loop loops through every element of an array (or any other iterable object). It works in the following manner:
let arr = [1, 2, 3, 4, 5];
for(let element of arr) {
console.log(element * 2);
}
In the above example, element stands for an array element and arr is the array which we want to loop. Note that the name element is arbitrary, and we could have picked any other name like 'el' or something more declarative when this is applicable.
Don't confuse the for..in loop with the for..of loop. for..in will loop through all enumerable properties of the array whereas the for..of loop will only loop through the array elements. For example:
let arr = [1, 2, 3, 4, 5];
arr.foo = 'foo';
for(let element of arr) {
console.log(element);
}
for(let element in arr) {
console.log(element);
}
Performance
Today (2019-12-18) I perform test on my macOS v10.13.6 (High Sierra), on Chrome v 79.0, Safari v13.0.4 and Firefox v71.0 (64 bit) - conclusions about optimisation (and micro-optimisation which usually is not worth to introduce it to code because the benefit is small, but code complexity grows).
It looks like the traditional for i (Aa) is a good choice to write fast code on all browsers.
The other solutions, like for-of (Ad), all in group C.... are usually 2 - 10 (and more) times slower than Aa, but for small arrays it is ok to use it - for the sake of increase code clarity.
The loops with array length cached in n (Ab, Bb, Be) are sometimes faster, sometimes not. Probably compilers automatically detect this situation and introduce caching. The speed differences between the cached and no-cached versions (Aa, Ba, Bd) are about ~1%, so it looks like introduce n is a micro-optimisation.
The i-- like solutions where the loop starts from the last array element (Ac, Bc) are usually ~30% slower than forward solutions - probably the reason is the way of CPU memory cache working - forward memory reading is more optimal for CPU caching). Is recommended to NOT USE such solutions.
Details
In tests we calculate the sum of array elements. I perform a test for small arrays (10 elements) and big arrays (1M elements) and divide them into three groups:
A - for tests
B - while tests
C - other/alternative methods
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
//let arr = Array.from(Array(1000000), (x, i) => i%10);
function Aa(a, s=0) {
for(let i=0; i<a.length; i++) {
s += a[i];
}
console.log('Aa=', s);
}
function Ab(a, s=0) {
let n = a.length;
for(let i=0; i<n; i++) {
s += a[i];
}
console.log('Ab=', s);
}
function Ac(a, s=0) {
for(let i=a.length; i--;) {
s += a[i];
}
console.log('Ac=', s);
}
function Ad(a, s=0) {
for(let x of a) {
s += x;
}
console.log('Ad=', s);
}
function Ae(a, s=0) {
for(let i in a) if (a.hasOwnProperty(i)) {
s += a[i];
}
console.log('Ae=', s);
}
function Ba(a, s=0) {
let i = -1;
while(++i < a.length) {
s+= a[i];
}
console.log('Ba=', s);
}
function Bb(a, s=0) {
let i = -1;
let n = a.length;
while(++i < n) {
s+= a[i];
}
console.log('Bb=', s);
}
function Bc(a, s=0) {
let i = a.length;
while(i--) {
s += a[i];
}
console.log('Bc=', s);
}
function Bd(a, s=0) {
let i = 0;
do {
s+= a[i]
} while (++i < a.length);
console.log('Bd=', s);
}
function Be(a, s=0) {
let i = 0;
let n = a.length;
do {
s += a[i]
} while (++i < n);
console.log('Be=', s);
}
function Bf(a, s=0) {
const it = a.values();
let e;
while (!(e = it.next()).done) {
s+= e.value;
}
console.log('Bf=', s);
}
function Ca(a, s=0) {
a.map(x => { s+=x });
console.log('Ca=', s);
}
function Cb(a, s=0) {
a.forEach(x => { s+=x });
console.log('Cb=', s);
}
function Cc(a, s=0) {
a.every(x => (s += x, 1));
console.log('Cc=', s);
}
function Cd(a, s=0) {
a.filter(x => { s+=x });
console.log('Cd=',s);
}
function Ce(a, s=0) {
a.reduce((z, c) => { s+=c }, 0);
console.log('Ce=', s);
}
function Cf(a, s=0) {
a.reduceRight((z, c) => { s += c }, 0);
console.log('Cf=', s);
}
function Cg(a, s=0) {
a.some(x => { s += x } );
console.log('Cg=', s);
}
function Ch(a, s=0) {
Array.from(a, x=> s += x);
console.log('Cc=', s);
}
Aa(arr);
Ab(arr);
Ac(arr);
Ad(arr);
Ae(arr);
Ba(arr);
Bb(arr);
Bc(arr);
Bd(arr);
Be(arr);
Bf(arr);
Ca(arr);
Cb(arr);
Cc(arr);
Cd(arr);
Ce(arr);
Cf(arr);
Cg(arr);
Ch(arr);
<p style="color: red">This snippets only PRESENTS code used for benchmark - it not perform test itself</p>
Cross browser results
Results for all tested browsers
browsers**
Array with 10 elements
Results for Chrome. You can perform the test on your machine here.
Array with 1,000,000 elements
Results for Chrome. You can perform the test on your machine here
A way closest to your idea would be to use Array.forEach() which accepts a closure function which will be executed for each element of the array.
myArray.forEach(
(item) => {
// Do something
console.log(item);
}
);
Another viable way would be to use Array.map() which works in the same way, but it also takes all values that you return and returns them in a new array (essentially mapping each element to a new one), like this:
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]
As per the new updated feature ECMAScript 6 (ES6) and ECMAScript 2015, you can use the following options with loops:
for loops
for(var i = 0; i < 5; i++){
console.log(i);
}
// Output: 0,1,2,3,4
for...in loops
let obj = {"a":1, "b":2}
for(let k in obj){
console.log(k)
}
// Output: a,b
Array.forEach()
let array = [1,2,3,4]
array.forEach((x) => {
console.log(x);
})
// Output: 1,2,3,4
for...of loops
let array = [1,2,3,4]
for(let x of array){
console.log(x);
}
// Output: 1,2,3,4
while loops
let x = 0
while(x < 5){
console.log(x)
x++
}
// Output: 1,2,3,4
do...while loops
let x = 0
do{
console.log(x)
x++
}while(x < 5)
// Output: 1,2,3,4
The lambda syntax doesn't usually work in Internet Explorer 10 or below.
I usually use the
[].forEach.call(arrayName,function(value,index){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
If you are a jQuery fan and already have a jQuery file running, you should reverse the positions of the index and value parameters
$("#ul>li").each(function(**index, value**){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
You can call forEach like this:
forEach will iterate over the array you provide and for each iteration it will have element which holds the value of that iteration. If you need index you can get the current index by passing the i as the second parameter in the callback function for forEach.
Foreach is basically a High Order Function, Which takes another function as its parameter.
let theArray= [1,3,2];
theArray.forEach((element) => {
// Use the element of the array
console.log(element)
}
Output:
1
3
2
You can also iterate over an array like this:
for (let i=0; i<theArray.length; i++) {
console.log(i); // i will have the value of each index
}
If you want to use forEach(), it will look like -
theArray.forEach ( element => {
console.log(element);
});
If you want to use for(), it will look like -
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}

For loop in javascript on mongoshell [duplicate]

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 I do the same in JavaScript?
Three main options:
for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
xs.forEach((x, i) => console.log(x));
for (const x of xs) { console.log(x); }
Detailed examples are below.
1. Sequential for loop:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Pros
Works on every environment
You can use break and continue flow control statements
Cons
Too verbose
Imperative
Easy to have off-by-one errors (sometimes also called a fence post error)
2. Array.prototype.forEach:
The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach, gave us a concise way to iterate over an array:
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
console.log(item, index);
});
Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.
And with the ES6 arrow function syntax, it's even more succinct:
array.forEach(item => console.log(item));
Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.
Pros
Very short and succinct.
Declarative
Cons
Cannot use break / continue
Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:
array.filter(item => item.condition < 10)
.forEach(item => console.log(item))
Keep in mind if you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.
Anti-pattern:
const numbers = [1,2,3,4,5], doubled = [];
numbers.forEach((n, i) => { doubled[i] = n * 2 });
Proper use case of map:
const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.
Anti-pattern:
const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });
Proper use of reduce:
const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum);
3. ES6 for-of statement:
The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.
This statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).
Array objects are by definition built-in iterables in ES6, so you can use this statement on them:
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}
Pros
It can iterate over a large variety of objects.
Can use normal flow control statements (break / continue).
Useful to iterate serially asynchronous values.
Cons
If you are targeting older browsers, the transpiled output might surprise you.
Do not use for...in
#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 also be 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 log "a", "b", "c", and "foo!".
That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).
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
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:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
(The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn't modified there.)
A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its length; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; the length of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:
> a // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0] // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a // it now looks like this
[ undefined, <11 empty items>, 1 ]
So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process undefineds for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.
If you iterate over an array with for..of, the body of the loop is executed length times, and the loop control variable is set to undefined for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.
Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support for...of.
As long as your JavaScript implementation 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 Array#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 ...
} );
You can of course use an arrow function if your implementation supports ES6+:
myStringArray.forEach( s => {
// ... do something with s ...
} );
Unlike for...of, .forEach only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.
The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
s = myStringArray[i];
// ... do something with s ...
}
One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full length times, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:
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 ...
}
}
Depending on your implementation's optimizations, 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. You may 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 explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to forEach, so you can access it that way as well:
myStringArray.forEach( (s,i) => {
// ... do something with s and i ...
});
for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array (and not one of the other iterable types for..of works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:
for (const [i, s] of myStringArray.entries()) {
// ... do something with s and 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 is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.
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.
for (const 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 ECMAScript  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).
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JavaScript compilers (such as Babel) that allow us to use next-generation features today.
It also works on Node.js (I tested it on version 0.12.0).
Iterating an array
// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
Iterating an array of objects
const band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(const 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 (const n of fibonacci()) {
console.log(n);
// Truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops
Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better to use 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.
6 different methods to loop through the array
You can loop through an array by many different methods. I have sorted my 6 favorite methods from top to bottom.
1. Using for loop
When it's to simply loop through an array, the for loop is my first choice.
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
2. Using forEach loop
forEach loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.
let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});
3. Using for...of
for...of loop gives you direct access to the array elements.
let array = [1, 2, 3, 4, 5];
for (let element of array) {
console.log(element);
}
4. Using for...in loop
for...in gives you a key using which you can access array elements.
let array = [1, 2, 3, 4, 5];
for(let index in array){
console.log(array[index]);
}
5. Using while loop
while loop is can be used to loop through the array as well.
let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
console.log(array[array.length - length]);
length--;
}
6. Using do...while loop
Likewise, I use do...while loop
let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
console.log(array[array.length - length]);
length--;
}
while (length > 0)
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;
})();
Introduction
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:
The initialization: executed before the look block is executed the first time
The condition: checks a condition every time before the loop block is executed, and quits the loop if false
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" for 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:
_.forEach(myArray, function(value, key) {
console.log(value);
});
Use the while loop...
var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
console.log(item);
}
It logs: 'one', 'two', and '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]);
}
It logs: 'three', 'two', and '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]);
}
It logs: 'one','two','three'
Reference: Google Closure: How not to write JavaScript
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.
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);
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);
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()
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are many ways to do a loop over arrays in JavaScript. 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
A for loop is a common way looping through arrays in JavaScript, but it is 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
A while loop is considered as the fastest way to loop through long arrays, but it is usually less used in the JavaScript code:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
A do while is 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 a few more ways to do that.
Also we use a for in loop for looping over objects in JavaScript.
Also look at the map(), filter(), reduce(), etc. functions on an Array in JavaScript. They may do things much faster and better than using while and for.
This is a good article if you like to learn more about the asynchronous 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:
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.
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.
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);
}
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...
If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:
https://jsperf.com/fastest-array-iterator
Results:
The traditional for() iterator, is by far the fastest method, especially 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.
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
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.
There are 4 ways of array iteration:
// 1: for
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
// 2: forEach
arr.forEach((v, i) => console.log(v));
// 3: for in
for (let i in arr) {
console.log(arr[i]);
}
// 4: for of
for (const v of arr) {
console.log(v);
}
Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The best way is 4th - "for of".
Esoteric
let a= ["Hello", "World"];
while(a.length) { console.log( a.shift() ); }
Performance test
Today (2022-11-13) I perform a test on Chrome 107, Safari 15.2 and Firefox 106 on chosen solutions.
Conclusions
solutions C and D are fast or fastest on all browsers for all arrays.
solution A and B are slowest on all browsers for all arrays
Results
Details
I perform 3 tests:
small - for 2 elements array (like OP) - you can run it here
medium - for 10K elements array and - you can run it here
big - for 100K elements array - you can run it here
The below snippet presents code used in the test.
function A(a) {
let r=0;
while(a.length) r+= a.shift().length;
return r;
}
function B(a) {
let r=0;
for(i in a) r+= a[i].length;
return r;
}
function C(a) {
let r=0;
for(x of a) r+= x.length;
return r;
}
function D(a) {
let r=0;
for (i=0; i<a.length; ++i) r+= a[i].length;
return r;
}
function E(a) {
let r=0;
a.forEach(x=> r+= x.length);
return r;
}
let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))
Here are example results for Chrome for a medium array:
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 an 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.
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>
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>
The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single var keyword.
var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
// Do something
}
If the order of iteration does not matter then you should try reversed loop. It is the fastest as it reduces 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 a while loop:
var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
// Do something with fruits[i]
}
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()
If you want to use jQuery, it has a nice example in its documentation:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
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 it available, it is certainly the safest way to iterate over an array in JavaScript.
Array.prototype.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 its 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.
A working jsFiddle example:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
It's not 100% identical, but similar:
var myStringArray = ['Hello', 'World']; // The array uses [] not {}
for (var i in myStringArray) {
console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
}
For example, I used in a Firefox console:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
You can use querySelectorAll to get same result
document.querySelectorAll('pre').forEach( (e) => {
console.log(e.textContent);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

Looping through multiple JSON objects in AJAX [duplicate]

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 I do the same in JavaScript?
Three main options:
for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
xs.forEach((x, i) => console.log(x));
for (const x of xs) { console.log(x); }
Detailed examples are below.
1. Sequential for loop:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Pros
Works on every environment
You can use break and continue flow control statements
Cons
Too verbose
Imperative
Easy to have off-by-one errors (sometimes also called a fence post error)
2. Array.prototype.forEach:
The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach, gave us a concise way to iterate over an array:
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
console.log(item, index);
});
Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.
And with the ES6 arrow function syntax, it's even more succinct:
array.forEach(item => console.log(item));
Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.
Pros
Very short and succinct.
Declarative
Cons
Cannot use break / continue
Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:
array.filter(item => item.condition < 10)
.forEach(item => console.log(item))
Keep in mind if you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.
Anti-pattern:
const numbers = [1,2,3,4,5], doubled = [];
numbers.forEach((n, i) => { doubled[i] = n * 2 });
Proper use case of map:
const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.
Anti-pattern:
const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });
Proper use of reduce:
const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum);
3. ES6 for-of statement:
The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.
This statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).
Array objects are by definition built-in iterables in ES6, so you can use this statement on them:
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}
Pros
It can iterate over a large variety of objects.
Can use normal flow control statements (break / continue).
Useful to iterate serially asynchronous values.
Cons
If you are targeting older browsers, the transpiled output might surprise you.
Do not use for...in
#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 also be 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 log "a", "b", "c", and "foo!".
That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).
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
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:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
(The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn't modified there.)
A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its length; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; the length of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:
> a // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0] // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a // it now looks like this
[ undefined, <11 empty items>, 1 ]
So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process undefineds for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.
If you iterate over an array with for..of, the body of the loop is executed length times, and the loop control variable is set to undefined for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.
Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support for...of.
As long as your JavaScript implementation 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 Array#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 ...
} );
You can of course use an arrow function if your implementation supports ES6+:
myStringArray.forEach( s => {
// ... do something with s ...
} );
Unlike for...of, .forEach only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.
The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
s = myStringArray[i];
// ... do something with s ...
}
One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full length times, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:
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 ...
}
}
Depending on your implementation's optimizations, 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. You may 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 explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to forEach, so you can access it that way as well:
myStringArray.forEach( (s,i) => {
// ... do something with s and i ...
});
for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array (and not one of the other iterable types for..of works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:
for (const [i, s] of myStringArray.entries()) {
// ... do something with s and 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 is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.
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.
for (const 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 ECMAScript  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).
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JavaScript compilers (such as Babel) that allow us to use next-generation features today.
It also works on Node.js (I tested it on version 0.12.0).
Iterating an array
// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
Iterating an array of objects
const band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(const 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 (const n of fibonacci()) {
console.log(n);
// Truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops
Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better to use 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.
6 different methods to loop through the array
You can loop through an array by many different methods. I have sorted my 6 favorite methods from top to bottom.
1. Using for loop
When it's to simply loop through an array, the for loop is my first choice.
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
2. Using forEach loop
forEach loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.
let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});
3. Using for...of
for...of loop gives you direct access to the array elements.
let array = [1, 2, 3, 4, 5];
for (let element of array) {
console.log(element);
}
4. Using for...in loop
for...in gives you a key using which you can access array elements.
let array = [1, 2, 3, 4, 5];
for(let index in array){
console.log(array[index]);
}
5. Using while loop
while loop is can be used to loop through the array as well.
let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
console.log(array[array.length - length]);
length--;
}
6. Using do...while loop
Likewise, I use do...while loop
let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
console.log(array[array.length - length]);
length--;
}
while (length > 0)
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;
})();
Introduction
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:
The initialization: executed before the look block is executed the first time
The condition: checks a condition every time before the loop block is executed, and quits the loop if false
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" for 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:
_.forEach(myArray, function(value, key) {
console.log(value);
});
Use the while loop...
var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
console.log(item);
}
It logs: 'one', 'two', and '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]);
}
It logs: 'three', 'two', and '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]);
}
It logs: 'one','two','three'
Reference: Google Closure: How not to write JavaScript
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.
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);
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);
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()
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are many ways to do a loop over arrays in JavaScript. 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
A for loop is a common way looping through arrays in JavaScript, but it is 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
A while loop is considered as the fastest way to loop through long arrays, but it is usually less used in the JavaScript code:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
A do while is 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 a few more ways to do that.
Also we use a for in loop for looping over objects in JavaScript.
Also look at the map(), filter(), reduce(), etc. functions on an Array in JavaScript. They may do things much faster and better than using while and for.
This is a good article if you like to learn more about the asynchronous 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:
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.
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.
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);
}
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...
If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:
https://jsperf.com/fastest-array-iterator
Results:
The traditional for() iterator, is by far the fastest method, especially 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.
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
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.
There are 4 ways of array iteration:
// 1: for
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
// 2: forEach
arr.forEach((v, i) => console.log(v));
// 3: for in
for (let i in arr) {
console.log(arr[i]);
}
// 4: for of
for (const v of arr) {
console.log(v);
}
Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The best way is 4th - "for of".
Esoteric
let a= ["Hello", "World"];
while(a.length) { console.log( a.shift() ); }
Performance test
Today (2022-11-13) I perform a test on Chrome 107, Safari 15.2 and Firefox 106 on chosen solutions.
Conclusions
solutions C and D are fast or fastest on all browsers for all arrays.
solution A and B are slowest on all browsers for all arrays
Results
Details
I perform 3 tests:
small - for 2 elements array (like OP) - you can run it here
medium - for 10K elements array and - you can run it here
big - for 100K elements array - you can run it here
The below snippet presents code used in the test.
function A(a) {
let r=0;
while(a.length) r+= a.shift().length;
return r;
}
function B(a) {
let r=0;
for(i in a) r+= a[i].length;
return r;
}
function C(a) {
let r=0;
for(x of a) r+= x.length;
return r;
}
function D(a) {
let r=0;
for (i=0; i<a.length; ++i) r+= a[i].length;
return r;
}
function E(a) {
let r=0;
a.forEach(x=> r+= x.length);
return r;
}
let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))
Here are example results for Chrome for a medium array:
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 an 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.
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>
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>
The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single var keyword.
var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
// Do something
}
If the order of iteration does not matter then you should try reversed loop. It is the fastest as it reduces 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 a while loop:
var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
// Do something with fruits[i]
}
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()
If you want to use jQuery, it has a nice example in its documentation:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
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 it available, it is certainly the safest way to iterate over an array in JavaScript.
Array.prototype.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 its 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.
A working jsFiddle example:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
It's not 100% identical, but similar:
var myStringArray = ['Hello', 'World']; // The array uses [] not {}
for (var i in myStringArray) {
console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
}
For example, I used in a Firefox console:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
You can use querySelectorAll to get same result
document.querySelectorAll('pre').forEach( (e) => {
console.log(e.textContent);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

How to simplify nested calls in nodejs/javascript for inquirer [duplicate]

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 I do the same in JavaScript?
Three main options:
for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
xs.forEach((x, i) => console.log(x));
for (const x of xs) { console.log(x); }
Detailed examples are below.
1. Sequential for loop:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Pros
Works on every environment
You can use break and continue flow control statements
Cons
Too verbose
Imperative
Easy to have off-by-one errors (sometimes also called a fence post error)
2. Array.prototype.forEach:
The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach, gave us a concise way to iterate over an array:
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
console.log(item, index);
});
Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.
And with the ES6 arrow function syntax, it's even more succinct:
array.forEach(item => console.log(item));
Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.
Pros
Very short and succinct.
Declarative
Cons
Cannot use break / continue
Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:
array.filter(item => item.condition < 10)
.forEach(item => console.log(item))
Keep in mind if you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.
Anti-pattern:
const numbers = [1,2,3,4,5], doubled = [];
numbers.forEach((n, i) => { doubled[i] = n * 2 });
Proper use case of map:
const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.
Anti-pattern:
const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });
Proper use of reduce:
const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum);
3. ES6 for-of statement:
The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.
This statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).
Array objects are by definition built-in iterables in ES6, so you can use this statement on them:
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}
Pros
It can iterate over a large variety of objects.
Can use normal flow control statements (break / continue).
Useful to iterate serially asynchronous values.
Cons
If you are targeting older browsers, the transpiled output might surprise you.
Do not use for...in
#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 also be 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 log "a", "b", "c", and "foo!".
That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).
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
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:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
(The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn't modified there.)
A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its length; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; the length of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:
> a // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0] // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a // it now looks like this
[ undefined, <11 empty items>, 1 ]
So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process undefineds for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.
If you iterate over an array with for..of, the body of the loop is executed length times, and the loop control variable is set to undefined for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.
Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support for...of.
As long as your JavaScript implementation 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 Array#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 ...
} );
You can of course use an arrow function if your implementation supports ES6+:
myStringArray.forEach( s => {
// ... do something with s ...
} );
Unlike for...of, .forEach only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.
The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
s = myStringArray[i];
// ... do something with s ...
}
One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full length times, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:
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 ...
}
}
Depending on your implementation's optimizations, 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. You may 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 explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to forEach, so you can access it that way as well:
myStringArray.forEach( (s,i) => {
// ... do something with s and i ...
});
for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array (and not one of the other iterable types for..of works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:
for (const [i, s] of myStringArray.entries()) {
// ... do something with s and 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 is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.
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.
for (const 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 ECMAScript  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).
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JavaScript compilers (such as Babel) that allow us to use next-generation features today.
It also works on Node.js (I tested it on version 0.12.0).
Iterating an array
// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
Iterating an array of objects
const band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(const 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 (const n of fibonacci()) {
console.log(n);
// Truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops
Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better to use 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.
6 different methods to loop through the array
You can loop through an array by many different methods. I have sorted my 6 favorite methods from top to bottom.
1. Using for loop
When it's to simply loop through an array, the for loop is my first choice.
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
2. Using forEach loop
forEach loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.
let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});
3. Using for...of
for...of loop gives you direct access to the array elements.
let array = [1, 2, 3, 4, 5];
for (let element of array) {
console.log(element);
}
4. Using for...in loop
for...in gives you a key using which you can access array elements.
let array = [1, 2, 3, 4, 5];
for(let index in array){
console.log(array[index]);
}
5. Using while loop
while loop is can be used to loop through the array as well.
let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
console.log(array[array.length - length]);
length--;
}
6. Using do...while loop
Likewise, I use do...while loop
let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
console.log(array[array.length - length]);
length--;
}
while (length > 0)
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;
})();
Introduction
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:
The initialization: executed before the look block is executed the first time
The condition: checks a condition every time before the loop block is executed, and quits the loop if false
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" for 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:
_.forEach(myArray, function(value, key) {
console.log(value);
});
Use the while loop...
var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
console.log(item);
}
It logs: 'one', 'two', and '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]);
}
It logs: 'three', 'two', and '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]);
}
It logs: 'one','two','three'
Reference: Google Closure: How not to write JavaScript
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.
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);
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);
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()
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are many ways to do a loop over arrays in JavaScript. 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
A for loop is a common way looping through arrays in JavaScript, but it is 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
A while loop is considered as the fastest way to loop through long arrays, but it is usually less used in the JavaScript code:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
A do while is 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 a few more ways to do that.
Also we use a for in loop for looping over objects in JavaScript.
Also look at the map(), filter(), reduce(), etc. functions on an Array in JavaScript. They may do things much faster and better than using while and for.
This is a good article if you like to learn more about the asynchronous 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:
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.
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.
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);
}
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...
If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:
https://jsperf.com/fastest-array-iterator
Results:
The traditional for() iterator, is by far the fastest method, especially 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.
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
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.
There are 4 ways of array iteration:
// 1: for
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
// 2: forEach
arr.forEach((v, i) => console.log(v));
// 3: for in
for (let i in arr) {
console.log(arr[i]);
}
// 4: for of
for (const v of arr) {
console.log(v);
}
Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The best way is 4th - "for of".
Esoteric
let a= ["Hello", "World"];
while(a.length) { console.log( a.shift() ); }
Performance test
Today (2022-11-13) I perform a test on Chrome 107, Safari 15.2 and Firefox 106 on chosen solutions.
Conclusions
solutions C and D are fast or fastest on all browsers for all arrays.
solution A and B are slowest on all browsers for all arrays
Results
Details
I perform 3 tests:
small - for 2 elements array (like OP) - you can run it here
medium - for 10K elements array and - you can run it here
big - for 100K elements array - you can run it here
The below snippet presents code used in the test.
function A(a) {
let r=0;
while(a.length) r+= a.shift().length;
return r;
}
function B(a) {
let r=0;
for(i in a) r+= a[i].length;
return r;
}
function C(a) {
let r=0;
for(x of a) r+= x.length;
return r;
}
function D(a) {
let r=0;
for (i=0; i<a.length; ++i) r+= a[i].length;
return r;
}
function E(a) {
let r=0;
a.forEach(x=> r+= x.length);
return r;
}
let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))
Here are example results for Chrome for a medium array:
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 an 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.
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>
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>
The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single var keyword.
var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
// Do something
}
If the order of iteration does not matter then you should try reversed loop. It is the fastest as it reduces 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 a while loop:
var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
// Do something with fruits[i]
}
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()
If you want to use jQuery, it has a nice example in its documentation:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
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 it available, it is certainly the safest way to iterate over an array in JavaScript.
Array.prototype.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 its 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.
A working jsFiddle example:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
It's not 100% identical, but similar:
var myStringArray = ['Hello', 'World']; // The array uses [] not {}
for (var i in myStringArray) {
console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
}
For example, I used in a Firefox console:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
You can use querySelectorAll to get same result
document.querySelectorAll('pre').forEach( (e) => {
console.log(e.textContent);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

for loop or for-in loop [duplicate]

Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?
Let's say we have an array of associative arrays:
var myArray = [{'key': 'value'}, {'key': 'value1'}];
So we can iterate:
for (var i = 0; i < myArray.length; i++)
And:
for (var i in myArray)
I don't see a big difference. Are there any performance issues?
The choice should be based on the which idiom is best understood.
An array is iterated using:
for (var i = 0; i < a.length; i++)
//do stuff with a[i]
An object being used as an associative array is iterated using:
for (var key in o)
//do stuff with o[key]
Unless you have earth shattering reasons, stick to the established pattern of usage.
Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.
If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.
Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:
for (var name in obj) {
if (Object.prototype.hasOwnProperty.call(obj, name)) {
// DO STUFF
}
}
FYI - jQuery Users
jQuery's each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined.
Therefore, I would say it is safe to assume the correct order when using this function.
Example:
$(['a','b','c']).each(function() {
alert(this);
});
//Outputs "a" then "b" then "c"
The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.
there are performance differences depending on what kind of loop you use and on what browser.
For instance:
for (var i = myArray.length-1; i >= 0; i--)
is almost twice as fast on some browsers than:
for (var i = 0; i < myArray.length; i++)
However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)
Note that the native Array.forEach method is now widely supported.
Updated answer for 2012 current version of all major browsers - Chrome, Firefox, IE9, Safari and Opera support ES5's native array.forEach.
Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it's cleaner to simply use the language's proper syntax:
myArray.forEach(function(item, index) {
console.log(item, index);
});
Full documentation for array.forEach() is at MDN.
The two are not the same when the array is sparse.
var array = [0, 1, 2, , , 5];
for (var k in array) {
// Not guaranteed by the language spec to iterate in order.
alert(k); // Outputs 0, 1, 2, 5.
// Behavior when loop body adds to the array is unclear.
}
for (var i = 0; i < array.length; ++i) {
// Iterates in order.
// i is a number, not a string.
alert(i); // Outputs 0, 1, 2, 3, 4, 5
// Behavior when loop body modifies array is clearer.
}
Using forEach to skip the prototype chain
Just a quick addendum to #nailer's answer above, using forEach with Object.keys means you can avoid iterating over the prototype chain without having to use hasOwnProperty.
var Base = function () {
this.coming = "hey";
};
var Sub = function () {
this.leaving = "bye";
};
Sub.prototype = new Base();
var tst = new Sub();
for (var i in tst) {
console.log(tst.hasOwnProperty(i) + i + tst[i]);
}
Object.keys(tst).forEach(function (val) {
console.log(val + tst[val]);
});
I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native Array with for in structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.
There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.
I would use for in to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:
l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\n' } console.log(l);
It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.
I'd use the different methods based on how I wanted to reference the items.
Use foreach if you just want the current item.
Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)
I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.
here is something i did.
function foreach(o, f) {
for(var i = 0; i < o.length; i++) { // simple for loop
f(o[i], i); // execute a function and make the obj, objIndex available
}
}
this is how you would use it
this will work on arrays and objects( such as a list of HTML elements )
foreach(o, function(obj, i) { // for each obj in o
alert(obj); // obj
alert(i); // obj index
/*
say if you were dealing with an html element may be you have a collection of divs
*/
if(typeof obj == 'object') {
obj.style.marginLeft = '20px';
}
});
I just made this so I'm open to suggestions :)
With for (var i in myArray) you can loop over objects too, i will contain the key name and you can access the property via myArray[i]. Additionaly, any methods you will have added to the object will be included in the loop, too, i.e., if you use any external framework like jQuery or prototype, or if you add methods to object prototypes directly, at one point i will point to those methods.
Watch out!
If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.
https://developer.mozilla.org/en/DOM/HTMLCollection
If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!
var scriptTags = document.getElementsByTagName("script");
for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)
for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!
Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection:
https://developer.mozilla.org/en/DOM/document.getElementsByTagName
For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.
http://www.prototypejs.org/api/array
I have seen problems with the "for each" using objects and prototype and arrays
my understanding is that the for each is for properties of objects and NOT arrays
If you really want to speed up your code, what about that?
for( var i=0,j=null; j=array[i++]; foo(j) );
it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter
A shorter and best code according to jsperf is
keys = Object.keys(obj);
for (var i = keys.length; i--;){
value = obj[keys[i]];// or other action
}
for(;;) is for Arrays : [20,55,33]
for..in is for Objects : {x:20,y:55:z:33}
Use the Array().forEach loop to take advantage of parallelism
Be careful!!!
I am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.
I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.
var MyTest = {
a:string = "a",
b:string = "b"
};
myfunction = function(dicts) {
for (var dict in dicts) {
alert(dict);
alert(typeof dict); // print 'string' (incorrect)
}
for (var i = 0; i < dicts.length; i++) {
alert(dicts[i]);
alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: "xyz"})
}
};
MyObj = function() {
this.aaa = function() {
myfunction([MyTest]);
};
};
new MyObj().aaa(); // This does not work
myfunction([MyTest]); // This works
There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the "remove" function it has.
for (var i = 0; i < myArray.length; i++) {
console.log(i)
}
//Output
0
1
for (var i in myArray) {
console.log(i)
}
// Output
0
1
remove
You could use the for-in with an if(myArray.hasOwnProperty(i)). Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.
Although they both are very much alike there is a minor difference :
var array = ["a", "b", "c"];
array["abc"] = 123;
console.log("Standard for loop:");
for (var index = 0; index < array.length; index++)
{
console.log(" array[" + index + "] = " + array[index]); //Standard for loop
}
in this case the output is :
STANDARD FOR LOOP:
ARRAY[0] = A
ARRAY[1] = B
ARRAY[2] = C
console.log("For-in loop:");
for (var key in array)
{
console.log(" array[" + key + "] = " + array[key]); //For-in loop output
}
while in this case the output is:
FOR-IN LOOP:
ARRAY[1] = B
ARRAY[2] = C
ARRAY[10] = D
ARRAY[ABC] = 123

Categories