Rectangle 27 1

2 - within the loop

Run your loops through and get your results (outside of the range), then force the data to be within your min/max values with:

M[which(M<min)] = min
M[which(M>max)] = max

for the addition case and

for (i in 1:50){
    M[which(M>min)] <- M[which(M>min)]-0.01
}

Setting min and max values for matrix cells when running a for loop in...

r for-loop matrix max min
Rectangle 27 5549

2. Use a simple for loop

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • a for-of loop (ES2015+ only),
  • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
  • a simple old-fashioned for loop,
  • or for-in with safeguards.

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.

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

You have three options in ECMAScript5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:

  • Use a simple for loop

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach (spec | MDN):

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

Additionally, 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 (stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
reduceRight
reduce

Sometimes the old ways are the best:

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}
var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

In ES2015 and higher, you can make your index and value variables local to the for loop:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
}
//console.log(index); // Would cause "ReferenceError: index is not defined"
//console.log(value); // Would cause "ReferenceError: value is not defined"

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        alert("Index is: " + index);
    });
}

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

You'll get people telling you to use for-in, but that's not what for-in is for. for-in loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6). ES2015 does define an order to object properties (via [[OwnPropertyKeys]], [[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0", "10", and "10000" remember, they're strings), not 10,001 times.

Now, you won't want to write that every time, so you might put this in your toolkit:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}
for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.

(As of this writing, Firefox 29 supports entries and keys but not values.)

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

forEach
Node
childNodes
Array.prototype.forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

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 some scoping function)
var forEach = Array.prototype.forEach;

// Then later...
forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

Use a simple for loop

Obviously, a simple for loop applies to array-like objects.

for-in

for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

for-of

for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

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:

var trueArray = Array.prototype.slice.call(arrayLikeObject);
var divs = Array.prototype.slice.call(document.querySelectorAll("div"));

See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

...

It's also possible to use ES2015's spread notation (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:

var trueArray = [...iterableObject];

So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

var divs = [...document.querySelectorAll("div")];
Array.from

Array.from (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

var divs = Array.from(document.querySelectorAll("div"));

Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

// Arrow function (ES2015):
var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);

// Standard function (since `Array.from` can be shimmed):
var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
    return element.tagName;
});

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in 8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break.

@Pius: If you want to break the loop, you can use some. (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )

@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.

@user889030: You need a , after k=0, not a ;. Remember, programming is many things, one of which is close attention to detail... :-)

@JimB: That's covered above (and length isn't a method). :-)

For-each over an array in JavaScript? - Stack Overflow

javascript arrays loops foreach iteration
Rectangle 27 5493

2. Use a simple for loop

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • a for-of loop (ES2015+ only),
  • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
  • a simple old-fashioned for loop,
  • or for-in with safeguards.

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.

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

You have three options in ECMAScript5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:

  • Use a simple for loop

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach (spec | MDN):

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

Additionally, 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 (stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
reduceRight
reduce

Sometimes the old ways are the best:

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}
var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

In ES2015 and higher, you can make your index and value variables local to the for loop:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
}
//console.log(index); // Would cause "ReferenceError: index is not defined"
//console.log(value); // Would cause "ReferenceError: value is not defined"

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        alert("Index is: " + index);
    });
}

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

You'll get people telling you to use for-in, but that's not what for-in is for. for-in loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6). ES2015 does define an order to object properties (via [[OwnPropertyKeys]], [[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0", "10", and "10000" remember, they're strings), not 10,001 times.

Now, you won't want to write that every time, so you might put this in your toolkit:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}
for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.

(As of this writing, Firefox 29 supports entries and keys but not values.)

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

forEach
Node
childNodes
Array.prototype.forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

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 some scoping function)
var forEach = Array.prototype.forEach;

// Then later...
forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

Use a simple for loop

Obviously, a simple for loop applies to array-like objects.

for-in

for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

for-of

for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

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:

var trueArray = Array.prototype.slice.call(arrayLikeObject);
var divs = Array.prototype.slice.call(document.querySelectorAll("div"));

See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

...

It's also possible to use ES2015's spread notation (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:

var trueArray = [...iterableObject];

So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

var divs = [...document.querySelectorAll("div")];
Array.from

Array.from (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

var divs = Array.from(document.querySelectorAll("div"));

Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

// Arrow function (ES2015):
var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);

// Standard function (since `Array.from` can be shimmed):
var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
    return element.tagName;
});

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in 8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break.

@Pius: If you want to break the loop, you can use some. (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )

@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.

@user889030: You need a , after k=0, not a ;. Remember, programming is many things, one of which is close attention to detail... :-)

@JimB: That's covered above (and length isn't a method). :-)

For-each over an array in JavaScript? - Stack Overflow

javascript arrays loops foreach iteration
Rectangle 27 5484

2. Use a simple for loop

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • a for-of loop (ES2015+ only),
  • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
  • a simple old-fashioned for loop,
  • or for-in with safeguards.

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.

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

You have three options in ECMAScript5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:

  • Use a simple for loop

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach (spec | MDN):

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

Additionally, 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 (stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
reduceRight
reduce

Sometimes the old ways are the best:

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}
var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

In ES2015 and higher, you can make your index and value variables local to the for loop:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
}
//console.log(index); // Would cause "ReferenceError: index is not defined"
//console.log(value); // Would cause "ReferenceError: value is not defined"

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        alert("Index is: " + index);
    });
}

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

You'll get people telling you to use for-in, but that's not what for-in is for. for-in loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6). ES2015 does define an order to object properties (via [[OwnPropertyKeys]], [[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0", "10", and "10000" remember, they're strings), not 10,001 times.

Now, you won't want to write that every time, so you might put this in your toolkit:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}
for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.

(As of this writing, Firefox 29 supports entries and keys but not values.)

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

forEach
Node
childNodes
Array.prototype.forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

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 some scoping function)
var forEach = Array.prototype.forEach;

// Then later...
forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

Use a simple for loop

Obviously, a simple for loop applies to array-like objects.

for-in

for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

for-of

for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

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:

var trueArray = Array.prototype.slice.call(arrayLikeObject);
var divs = Array.prototype.slice.call(document.querySelectorAll("div"));

See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

...

It's also possible to use ES2015's spread notation (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:

var trueArray = [...iterableObject];

So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

var divs = [...document.querySelectorAll("div")];
Array.from

Array.from (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

var divs = Array.from(document.querySelectorAll("div"));

Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

// Arrow function (ES2015):
var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);

// Standard function (since `Array.from` can be shimmed):
var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
    return element.tagName;
});

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in 8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break.

@Pius: If you want to break the loop, you can use some. (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )

@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.

@user889030: You need a , after k=0, not a ;. Remember, programming is many things, one of which is close attention to detail... :-)

@JimB: That's covered above (and length isn't a method). :-)

For-each over an array in JavaScript? - Stack Overflow

javascript arrays loops foreach iteration
Rectangle 27 5476

2. Use a simple for loop

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • a for-of loop (ES2015+ only),
  • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
  • a simple old-fashioned for loop,
  • or for-in with safeguards.

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.

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

You have three options in ECMAScript5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:

  • Use a simple for loop

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach (spec | MDN):

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

Additionally, 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 (stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
reduceRight
reduce

Sometimes the old ways are the best:

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}
var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

In ES2015 and higher, you can make your index and value variables local to the for loop:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
}
//console.log(index); // Would cause "ReferenceError: index is not defined"
//console.log(value); // Would cause "ReferenceError: value is not defined"

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        alert("Index is: " + index);
    });
}

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

You'll get people telling you to use for-in, but that's not what for-in is for. for-in loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6). ES2015 does define an order to object properties (via [[OwnPropertyKeys]], [[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0", "10", and "10000" remember, they're strings), not 10,001 times.

Now, you won't want to write that every time, so you might put this in your toolkit:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}
for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.

(As of this writing, Firefox 29 supports entries and keys but not values.)

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

forEach
Node
childNodes
Array.prototype.forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

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 some scoping function)
var forEach = Array.prototype.forEach;

// Then later...
forEach.call(node.childNodes, function(child) {
    // Do something with `child`
});

Use a simple for loop

Obviously, a simple for loop applies to array-like objects.

for-in

for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

for-of

for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

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:

var trueArray = Array.prototype.slice.call(arrayLikeObject);
var divs = Array.prototype.slice.call(document.querySelectorAll("div"));

See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

...

It's also possible to use ES2015's spread notation (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:

var trueArray = [...iterableObject];

So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

var divs = [...document.querySelectorAll("div")];
Array.from

Array.from (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

var divs = Array.from(document.querySelectorAll("div"));

Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

// Arrow function (ES2015):
var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);

// Standard function (since `Array.from` can be shimmed):
var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
    return element.tagName;
});

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in 8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break.

@Pius: If you want to break the loop, you can use some. (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )

@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.

@user889030: You need a , after k=0, not a ;. Remember, programming is many things, one of which is close attention to detail... :-)

@JimB: That's covered above (and length isn't a method). :-)

For-each over an array in JavaScript? - Stack Overflow

javascript arrays loops foreach iteration
Rectangle 27 1

For saving setTimeout within a index in a loop

You could use 2 dimensional array for this, first dimension will change along with the for loop index, whilst second dimension could remain in 0 to take control of the assigned timeout's IDs for each iteration.

var timeouts = []; // Two  dimensional array
for (i = 0; i < 5; i++)  
    timeouts[i] = [];

for(var i=0; i < 5 ; i++) {
    ...
    (function(delay, $element, savedtimeout){
        savedtimeout[0] = setTimeout(function() {
            countInView--;
        }, delay, savedtimeout);
    }(delay, $element, timeouts[i]));
    ...
}
if(timeouts[i][0] != null) {
    //Removes the timeout from the queue
    clearTimeout(timeouts[i][0]);
}

Thank you, is like all examples I have seen so far using this. But I have never seen someone removing it with a given index. I'd like to clear a specific position in the array of setTimeout, rather than using pop() or shift().

@Roizpi: Does this update approach help you, where I have maintained 2 dimensional array for time outs...

@Roizpi : Then you can clearTimeout(timeouts[0][0]) //so it will clear first timeout of first iteration

@Pa If the 1st time loop executes I trigger only 3 delayed actions for 1minute delay, the 2nd time loop executes, I want to remove 2, I will be already on second dimension(or maybe 3rd), and I will only not be able to remove the past setTimeouts, but also I will be creating a second timeout for the same iteration. I only want to save a single setTimeout per iteration, in the example I am trying to save 5, but in future iterations I want to be able to clear the same index that was saved previously, if a condition occurs. Sorry if I misunderstood, (still you're not using push).

javascript - How to save/clear setTimeout's array using loop's index? ...

javascript arrays loops closures settimeout
Rectangle 27 8

This is a bug in state saving of <ui:repeat> in Mojarra. There are several similar issue reports at http://java.net/jira/browse/JAVASERVERFACES, among others issue 2243.

You have basically 2 options: use another iterating component (e.g. <c:forEach>, <h:dataTable>, <t:dataList>, <p:dataList>, etc), or replace Mojarra by MyFaces (the <ui:repeat> in this construct works properly in there).

jsf 2 - within not entirely working, only the las...

forms jsf-2 uirepeat
Rectangle 27 8

This is a bug in state saving of <ui:repeat> in Mojarra. There are several similar issue reports at http://java.net/jira/browse/JAVASERVERFACES, among others issue 2243.

You have basically 2 options: use another iterating component (e.g. <c:forEach>, <h:dataTable>, <t:dataList>, <p:dataList>, etc), or replace Mojarra by MyFaces (the <ui:repeat> in this construct works properly in there).

jsf 2 - within not entirely working, only the las...

forms jsf-2 uirepeat
Rectangle 27 25

break, like goto, can only jump locally within the same function, but if you absolutely have to, you can use setjmp and longjmp:

#include <stdio.h>
#include <setjmp.h>

jmp_buf jump_target;

void foo(void)
{
    printf("Inside foo!\n");
    longjmp(jump_target, 1);
    printf("Still inside foo!\n");
}

int main(void) {
    if (setjmp(jump_target) == 0)
        foo();
    else
        printf("Jumped out!\n");
    return 0;
}

The call to longjmp will cause a jump back to the setjmp call. The return value from setjmp shows if it is returning after setting the jump target, or if it is returning from a jump.

Inside foo!
Jumped out!

Nonlocal jumps are safe when used correctly, but there are a number of things to think carefully about:

  • Since longjmp jumps "through" all the function activations between the setjmp call and the longjmp call, if any of those functions expect to be able to do additional work after the current place in execution, that work will simply not be done.
  • If the function activation that called setjmp has terminated, the behaviour is undefined. Anything can happen.
  • If setjmp hasn't yet been called, then jump_target is not set, and the behaviour is undefined.
  • Local variables in the function that called setjmp can under certain conditions have undefined values.
  • Other things, such as that floating-point status flags might not be retained, and that there are restrictions on where you can put the setjmp call.

Most of these follow naturally if you have a good understanding of what a nonlocal jump does on the level of machine instructions and CPU registers, but unless you have that, and have read what the C standard does and does not guarantee, I would advise some caution.

@Magisch: I'm curious how setjmp/longjmp would reduce the 'rewrite' necessary as compared to returning a vale to be checked? Using setjmp/longjmp will require both the call site and the function to be modified. Adding a return value is the same in many cases - except that only call sites that need to be able to perform the break need to be modified. Other call sites can just continue to call the function and ignore the return value.

@Magisch I still don't understand why you can't modify that badly written part to return something else than void, but you can modify it introducing the setjmp/longjmp fuzz.

@Magisch: beware that you might still be breaking the code despite the fact that you've worked around the explicit requirement for a void-return. If your function "must return void", then your former colleague's code might in particular have been written on the assumption that it "must return" at all. But you've now written a function that doesn't return, it jumps out instead. Check very carefully that your colleague didn't write clean-up code which you're now jumping past, because if so then skipping it likely will cause resource leaks, or leave some data structures in an inconsistent state.

@Magisch: Especially having read your latest comment, I would want to be a bit careful stomping around with longjumps in this program. But if it's the only way, and careful testing fails to find any problems, then perhaps you can cross your fingers and hope for the best. Just tell me which type of airplane this will be installed in, so I know which flights to avoid...

Might be worth adding a big "This is usually a very bad idea" warning on top of this answer.

c - Breaking out of a loop from within a function called in that loop ...

c for-loop break
Rectangle 27 180

Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to var. Therefore these two snippets have the same overhead.

I wish those guys who teach at out college at least knew this basic thing. Once he laughed at me declaring a variable inside a loop and I was wondering what's wrong until he cited performance as the reason not to do so and I was like "WTF!?".

Are you sure you should be talking about stack space right away. A variable like this could also be in a register.

@toto A variable like this could also be nowhere the var variable is initialized but never used, so a reasonable optimiser can just remove it completely (except the second snippet if the variable was used somewhere after the loop).

@Mehrdad Afshari a variable in a loop gets its constructor called once per iteration. EDIT - I see you mentioned this below, but I think it deserves mention in the accepted answer as well.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 178

Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to var. Therefore these two snippets have the same overhead.

I wish those guys who teach at out college at least knew this basic thing. Once he laughed at me declaring a variable inside a loop and I was wondering what's wrong until he cited performance as the reason not to do so and I was like "WTF!?".

Are you sure you should be talking about stack space right away. A variable like this could also be in a register.

@toto A variable like this could also be nowhere the var variable is initialized but never used, so a reasonable optimiser can just remove it completely (except the second snippet if the variable was used somewhere after the loop).

@Mehrdad Afshari a variable in a loop gets its constructor called once per iteration. EDIT - I see you mentioned this below, but I think it deserves mention in the accepted answer as well.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 96

For primitive types and POD types, it makes no difference. The compiler will allocate the stack space for the variable at the beginning of the function and deallocate it when the function returns in both cases.

For non-POD class types that have non-trivial constructors, it WILL make a difference -- in that case, putting the variable outside the loop will only call the constructor and destructor once and the assignment operator each iteration, whereas putting it inside the loop will call the constructor and destructor for every iteration of the loop. Depending on what the class' constructor, destructor, and assignment operator do, this may or may not be desirable.

Correct idea wrong reason. Variable outside the loop. Constructed once, destroyed once but asignment operator applied every iteration. Variable inside the loop. Constructe/Desatructor aplied every iteration but zero assignment operations.

This is the best answer but these comments are confusing. There's a big difference between calling a constructor and an assignment operator.

It is true if the loop body does the assignment anyway, not just for initialization. And if there's just a body-independent/constant initialization, the optimizer can hoist it.

@Andrew Grant: Why. Assignment operator is usually defined as copy construct into tmp followed by swap (to be exception safe) followed by destroy tmp. Thus assignment operator is not that different to construction/destroy cycle above. See stackoverflow.com/questions/255612/ for example of typical assignment operator.

If construct/destruct are expensive, their total cost is a reasonable upper limit on the cost of the operator=. But the assignment could indeed be cheaper. Also, as we expand this discussion from ints to C++ types, one could generalize 'var=4' as some other operation than 'assign variable from a value of the same type'.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 96

For primitive types and POD types, it makes no difference. The compiler will allocate the stack space for the variable at the beginning of the function and deallocate it when the function returns in both cases.

For non-POD class types that have non-trivial constructors, it WILL make a difference -- in that case, putting the variable outside the loop will only call the constructor and destructor once and the assignment operator each iteration, whereas putting it inside the loop will call the constructor and destructor for every iteration of the loop. Depending on what the class' constructor, destructor, and assignment operator do, this may or may not be desirable.

Correct idea wrong reason. Variable outside the loop. Constructed once, destroyed once but asignment operator applied every iteration. Variable inside the loop. Constructe/Desatructor aplied every iteration but zero assignment operations.

This is the best answer but these comments are confusing. There's a big difference between calling a constructor and an assignment operator.

It is true if the loop body does the assignment anyway, not just for initialization. And if there's just a body-independent/constant initialization, the optimizer can hoist it.

@Andrew Grant: Why. Assignment operator is usually defined as copy construct into tmp followed by swap (to be exception safe) followed by destroy tmp. Thus assignment operator is not that different to construction/destroy cycle above. See stackoverflow.com/questions/255612/ for example of typical assignment operator.

If construct/destruct are expensive, their total cost is a reasonable upper limit on the cost of the operator=. But the assignment could indeed be cheaper. Also, as we expand this discussion from ints to C++ types, one could generalize 'var=4' as some other operation than 'assign variable from a value of the same type'.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 4

2. Testing for assignment done in FOR loop

set variable="value with spaces"

This assigns "value with spaces" and everything else up to end of line like trailing spaces to variable.

The correct positioning of first double quote is:

set "variable=value with spaces"

This assigns just value with spaces to variable independent on trailing spaces or tabs on this line.

for /f "delims=" %%a in ('findstr /b "URL=" "%~1"') do set URL="%%a"
echo. %URL% | FIND /I "URL=">Nul || (set URL=""&goto chrome)

Much easier to read and faster on execution would be:

@echo off
set "URL="
for /F "delims=" %%a in ('%SystemRoot%\System32\findstr.exe /b "URL=" "%~1" 2^>nul') do set "URL=%%a"

if "%URL%"=="" goto Chrome

rem Remove URL= from string value.
set "URL=%URL:~4%"

echo URL found: %URL%
goto :EOF

:Chrome
echo No URL found.

Removing URL= case-insensitive is now much easier as the double quotes are not part of string value assigned to variable URL because of quoting value assignment to variable right.

In German countries the code page used on GUI for non Unicode strings is Windows-1252.

But in console windows by default OEM code page 850 is used in German countries.

It can be seen on comparing the two tables that the German umlauts have different byte values in those two code pages which explains what you see.

The code page used by default in console windows can be seen by opening a command prompt window and run there either command chcp without any parameter or command mode without any parameter. In both cases the used code page is output in console window.

Command chcp means change code page and can be therefore used to switch the code page for active command prompt.

What you have to do in the batch file depends on which encoding is used for file name string passed as parameter to the batch file.

Edit after questioner provided additional information about how batch file is called.

findstr is not needed for this task. Usage of findstr just makes the batch file slower and more complex than necessary.

Therefore I suggest a much easier batch solution for this task:

@echo off
for /F "usebackq tokens=1* delims==" %%a in ("%~1") do (
    if /I "%%a"=="URL" (
        set "URL=%%b"
        goto FoundURL
    )
)
echo No URL found.
goto :EOF

:FoundURL
echo URL found: %URL%

The *.url file is parsed now directly by command line interpreter with for instead of using findstr.

Run in a command prompt window for /? for help on this command.

A string in double quotes is parsed by default directly when using for with parameter /F. But for this task a file with full path specified in double quotes must be parsed. Therefore usebackq is used to change for behavior on string parsing to get file name with path in double quotes interpreted as name of a file to parse.

Next this batch file is only interested in the line:

URL=https://stackoverflow.com/

So delims== is used to split up each line into strings with using equal sign as delimiter.

Wanted is the string left to first equal sign and everything right of first equal sign which of course could contain also 1 or more equal signs. We get exactly that split behavior with tokens=1*. The string left to first equal sign is token 1 which is assigned to loop variable a while everything else after first equal sign is token 2 which is assigned to loop variable b.

With a case-insensitive comparison of string left to equal sign with string URL a check is made if line of interest is found in the file. In this case token 2 being the URL string is assigned to environment variable URL and the loop is exited with a jump to a label as there is no need to further parse the remaining lines of the file.

In case of for loop finishes normally, there is no line in *.url file starting with URL= in any case. Then the result is an appropriate information message before batch file is exited with goto :EOF (EOF - end of file - a nowadays always existing because predefined label).

Otherwise the found URL is output before also exiting this demo batch file.

This batch file called within a command prompt window with

D:\4all\reisen\istanbul\verkehr\fhren\Bosp_eminn_2h_14h30_12tl_SehirHatlari.url

or from Windows Explorer has no problem to open the file with the German umlauts and parse it.

Can it be that windows passes parameters differently depending on whether it calls .bat or .exe?

"%1" in a file association is a placeholder for an argument, usually the name of a file or directory.

There are now 3 possibilities for Windows to pass a directory or file name to an application:

ANSI strings use an array of type char in C/C++ coded applications for Windows while an array of type wchar_t is used for Unicode strings. Details for C/C++ programmers for Windows can be found

  • and lots of other web pages and documentations.

"%L" can be used instead of "%1" for a file association in HKEY_CLASSES_ROOT in Windows registry if Windows should pass a file or directory name always in long format and never in short format to an application. This is sometimes needed if an application is a hybrid like a C/C++ console application compiled with DJGPP which is a 16-bit application, but supports nevertheless long ANSI encoded file names because of special startup code.

But back to the question: Yes, of course, Windows passes file and directory names differently to a batch file or an executable depending on header of the executable, i.e. which type of application it is and which type of strings it supports.

It looks like the used bat to exe converter creates a 64-bit console application which is Unicode aware. So this application must convert correct the Unicode string to an ANSI string using the system locale of the user account on passing file and directory names and other arguments to the command finally running the embedded batch file. And it looks like this converter makes this Unicode to ANSI conversion task or the creation of the command line to run the batch file not 100% correct.

THX for your detailed answer ! Do you know a converter doing the conversion right in this case ?

batch file - (' findstr /b "URL=" "%~1" ') not working with ö,ä,ü in p...

batch-file for-loop findstr
Rectangle 27 4

2. Testing for assignment done in FOR loop

set variable="value with spaces"

This assigns "value with spaces" and everything else up to end of line like trailing spaces to variable.

The correct positioning of first double quote is:

set "variable=value with spaces"

This assigns just value with spaces to variable independent on trailing spaces or tabs on this line.

for /f "delims=" %%a in ('findstr /b "URL=" "%~1"') do set URL="%%a"
echo. %URL% | FIND /I "URL=">Nul || (set URL=""&goto chrome)

Much easier to read and faster on execution would be:

@echo off
set "URL="
for /F "delims=" %%a in ('%SystemRoot%\System32\findstr.exe /b "URL=" "%~1" 2^>nul') do set "URL=%%a"

if "%URL%"=="" goto Chrome

rem Remove URL= from string value.
set "URL=%URL:~4%"

echo URL found: %URL%
goto :EOF

:Chrome
echo No URL found.

Removing URL= case-insensitive is now much easier as the double quotes are not part of string value assigned to variable URL because of quoting value assignment to variable right.

In German countries the code page used on GUI for non Unicode strings is Windows-1252.

But in console windows by default OEM code page 850 is used in German countries.

It can be seen on comparing the two tables that the German umlauts have different byte values in those two code pages which explains what you see.

The code page used by default in console windows can be seen by opening a command prompt window and run there either command chcp without any parameter or command mode without any parameter. In both cases the used code page is output in console window.

Command chcp means change code page and can be therefore used to switch the code page for active command prompt.

What you have to do in the batch file depends on which encoding is used for file name string passed as parameter to the batch file.

Edit after questioner provided additional information about how batch file is called.

findstr is not needed for this task. Usage of findstr just makes the batch file slower and more complex than necessary.

Therefore I suggest a much easier batch solution for this task:

@echo off
for /F "usebackq tokens=1* delims==" %%a in ("%~1") do (
    if /I "%%a"=="URL" (
        set "URL=%%b"
        goto FoundURL
    )
)
echo No URL found.
goto :EOF

:FoundURL
echo URL found: %URL%

The *.url file is parsed now directly by command line interpreter with for instead of using findstr.

Run in a command prompt window for /? for help on this command.

A string in double quotes is parsed by default directly when using for with parameter /F. But for this task a file with full path specified in double quotes must be parsed. Therefore usebackq is used to change for behavior on string parsing to get file name with path in double quotes interpreted as name of a file to parse.

Next this batch file is only interested in the line:

URL=https://stackoverflow.com/

So delims== is used to split up each line into strings with using equal sign as delimiter.

Wanted is the string left to first equal sign and everything right of first equal sign which of course could contain also 1 or more equal signs. We get exactly that split behavior with tokens=1*. The string left to first equal sign is token 1 which is assigned to loop variable a while everything else after first equal sign is token 2 which is assigned to loop variable b.

With a case-insensitive comparison of string left to equal sign with string URL a check is made if line of interest is found in the file. In this case token 2 being the URL string is assigned to environment variable URL and the loop is exited with a jump to a label as there is no need to further parse the remaining lines of the file.

In case of for loop finishes normally, there is no line in *.url file starting with URL= in any case. Then the result is an appropriate information message before batch file is exited with goto :EOF (EOF - end of file - a nowadays always existing because predefined label).

Otherwise the found URL is output before also exiting this demo batch file.

This batch file called within a command prompt window with

D:\4all\reisen\istanbul\verkehr\fhren\Bosp_eminn_2h_14h30_12tl_SehirHatlari.url

or from Windows Explorer has no problem to open the file with the German umlauts and parse it.

Can it be that windows passes parameters differently depending on whether it calls .bat or .exe?

"%1" in a file association is a placeholder for an argument, usually the name of a file or directory.

There are now 3 possibilities for Windows to pass a directory or file name to an application:

ANSI strings use an array of type char in C/C++ coded applications for Windows while an array of type wchar_t is used for Unicode strings. Details for C/C++ programmers for Windows can be found

  • and lots of other web pages and documentations.

"%L" can be used instead of "%1" for a file association in HKEY_CLASSES_ROOT in Windows registry if Windows should pass a file or directory name always in long format and never in short format to an application. This is sometimes needed if an application is a hybrid like a C/C++ console application compiled with DJGPP which is a 16-bit application, but supports nevertheless long ANSI encoded file names because of special startup code.

But back to the question: Yes, of course, Windows passes file and directory names differently to a batch file or an executable depending on header of the executable, i.e. which type of application it is and which type of strings it supports.

It looks like the used bat to exe converter creates a 64-bit console application which is Unicode aware. So this application must convert correct the Unicode string to an ANSI string using the system locale of the user account on passing file and directory names and other arguments to the command finally running the embedded batch file. And it looks like this converter makes this Unicode to ANSI conversion task or the creation of the command line to run the batch file not 100% correct.

THX for your detailed answer ! Do you know a converter doing the conversion right in this case ?

batch file - (' findstr /b "URL=" "%~1" ') not working with ö,ä,ü in p...

batch-file for-loop findstr
Rectangle 27 66

They are both the same, and here's how you can find out, by looking at what the compiler does (even without optimisation set to high):

Look at what the compiler (gcc 4.0) does to your simple examples:

main(){ int var; while(int i < 100) { var = 4; } }
_main:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $24, %esp
    movl    $0, -16(%ebp)
    jmp L2
L3:
    movl    $4, -12(%ebp)
L2:
    cmpl    $99, -16(%ebp)
    jle L3
    leave
    ret
main() { while(int i < 100) { int var = 4; } }
_main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $24, %esp
        movl    $0, -16(%ebp)
        jmp     L2
L3:
        movl    $4, -12(%ebp)
L2:
        cmpl    $99, -16(%ebp)
        jle     L3
        leave
        ret

From these, you can see two things: firstly, the code is the same in both.

Secondly, the storage for var is allocated outside the loop:

subl    $24, %esp

And finally the only thing in the loop is the assignment and condition check:

L3:
        movl    $4, -12(%ebp)
L2:
        cmpl    $99, -16(%ebp)
        jle     L3

Which is about as efficient as you can be without removing the loop entirely.

"Which is about as efficient as you can be without removing the loop entirely" Not quite. Partially unrolling the loop (doing it say 4 times per pass) would speed it up dramatically. There are probably many other ways to optimize... although most modern compilers would probably realize that there's no point in looping at all. If 'i' was used later, it'd simply set 'i' = 100.

that's assuming the code changed to incremented 'i' at all... as is it's just a forever loop.

As was the Original Post!

I like answers that back the theory with proof! Nice to see ASM dump backing up the theory of being equal codes. +1

I actually produced the results by generating the machine code for each version. No need to run it.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 66

They are both the same, and here's how you can find out, by looking at what the compiler does (even without optimisation set to high):

Look at what the compiler (gcc 4.0) does to your simple examples:

main(){ int var; while(int i < 100) { var = 4; } }
_main:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $24, %esp
    movl    $0, -16(%ebp)
    jmp L2
L3:
    movl    $4, -12(%ebp)
L2:
    cmpl    $99, -16(%ebp)
    jle L3
    leave
    ret
main() { while(int i < 100) { int var = 4; } }
_main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $24, %esp
        movl    $0, -16(%ebp)
        jmp     L2
L3:
        movl    $4, -12(%ebp)
L2:
        cmpl    $99, -16(%ebp)
        jle     L3
        leave
        ret

From these, you can see two things: firstly, the code is the same in both.

Secondly, the storage for var is allocated outside the loop:

subl    $24, %esp

And finally the only thing in the loop is the assignment and condition check:

L3:
        movl    $4, -12(%ebp)
L2:
        cmpl    $99, -16(%ebp)
        jle     L3

Which is about as efficient as you can be without removing the loop entirely.

"Which is about as efficient as you can be without removing the loop entirely" Not quite. Partially unrolling the loop (doing it say 4 times per pass) would speed it up dramatically. There are probably many other ways to optimize... although most modern compilers would probably realize that there's no point in looping at all. If 'i' was used later, it'd simply set 'i' = 100.

that's assuming the code changed to incremented 'i' at all... as is it's just a forever loop.

As was the Original Post!

I like answers that back the theory with proof! Nice to see ASM dump backing up the theory of being equal codes. +1

I actually produced the results by generating the machine code for each version. No need to run it.

Is there any overhead to declaring a variable within a loop? (C++) - S...

c++ loops variable-declaration
Rectangle 27 89

Move the function outside the loop:

function dummy() {
    return this.name_;
}
// Or: var dummy = function() {return this.name;};
for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: dummy
   };
}

... Or just ignore the message by using the loopfunc option at the top of the file:

/*jshint loopfunc:true */
/* jshint loopfunc:true */

Ah I didn't think the "this" pointer would still work in that way. Isn't it pointing to the dummy function instead of the object at result[i]? In other words is name_ still correctly found?

@0x80 this points to the function's context, which is results[i] in this case. jsfiddle.net/W5vfw

Wonderful! Thanks for explaining this clearly. This was one of those things I never felt confident about in Javascript.

@RobW: May I know, what makes the difference by just calling a named function in the loop?

@AmolMKulkarni When the function expression is put inside the loop, it is constructed on each iteration. Moving the function expression/declaration outside the loop has some performance benefits: jsperf.com/closure-vs-name-function-in-a-loop/2

javascript - Don't make functions within a loop - Stack Overflow

javascript jslint
Rectangle 27 88

Move the function outside the loop:

function dummy() {
    return this.name_;
}
// Or: var dummy = function() {return this.name;};
for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: dummy
   };
}

... Or just ignore the message by using the loopfunc option at the top of the file:

/*jshint loopfunc:true */

Ah I didn't think the "this" pointer would still work in that way. Isn't it pointing to the dummy function instead of the object at result[i]? In other words is name_ still correctly found?

@0x80 this points to the function's context, which is results[i] in this case. jsfiddle.net/W5vfw

Wonderful! Thanks for explaining this clearly. This was one of those things I never felt confident about in Javascript.

@RobW: May I know, what makes the difference by just calling a named function in the loop?

@AmolMKulkarni When the function expression is put inside the loop, it is constructed on each iteration. Moving the function expression/declaration outside the loop has some performance benefits: jsperf.com/closure-vs-name-function-in-a-loop/2

javascript - Don't make functions within a loop - Stack Overflow

javascript jslint
Rectangle 27 88

Move the function outside the loop:

function dummy() {
    return this.name_;
}
// Or: var dummy = function() {return this.name;};
for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: dummy
   };
}

... Or just ignore the message by using the loopfunc option at the top of the file:

/*jshint loopfunc:true */

Ah I didn't think the "this" pointer would still work in that way. Isn't it pointing to the dummy function instead of the object at result[i]? In other words is name_ still correctly found?

@0x80 this points to the function's context, which is results[i] in this case. jsfiddle.net/W5vfw

Wonderful! Thanks for explaining this clearly. This was one of those things I never felt confident about in Javascript.

@RobW: May I know, what makes the difference by just calling a named function in the loop?

@AmolMKulkarni When the function expression is put inside the loop, it is constructed on each iteration. Moving the function expression/declaration outside the loop has some performance benefits: jsperf.com/closure-vs-name-function-in-a-loop/2

javascript - Don't make functions within a loop - Stack Overflow

javascript jslint