JavaScript Loops: for...in vs for - javascript

I faced a strange behaviour in Javascript. I get
"Object doesn't support this property or method"
exception for the removeAttribute function in the following code:
var buttons = controlDiv.getElementsByTagName("button");
for ( var button in buttons )
button.removeAttribute('disabled');
When I change the code with the following, the problem disappears:
var buttons = controlDiv.getElementsByTagName("button");
for ( var i = 0; i < buttons.length; i++ )
buttons[i].removeAttribute('disabled');
What is the value of button inside the for...in?

Don't use for..in for Array iteration.
It's important to understand that Javascript Array's square bracket syntax ([]) for accessing indicies is actually inherited from the Object...
obj.prop === obj['prop'] // true
The for..in structure does not work like a more traditional for..each/in that would be found in other languages (php, python, etc...).
Javascript's for..in is designed to iterate over the properties of an object. Producing the key of each property. Using this key combined with the Object's bracket syntax, you can easily access the values you are after.
var obj = {
foo: "bar",
fizz: "buzz",
moo: "muck"
};
for ( var prop in obj ) {
console.log(prop); // foo / fizz / moo
console.log(obj[prop]); // bar / buzz / muck
}
And because the Array is simply an Object with sequential numeric property names (indexes) the for..in works in a similar way, producing the numeric indicies just as it produces the property names above.
An important characteristic of the for..in structure is that it continues to search for enumerable properties up the prototype chain. It will also iterate inherited enumerable properties. It is up to you to verify that the current property exists directly on the local object and not the prototype it is attached to with hasOwnProperty()...
for ( var prop in obj ) {
if ( obj.hasOwnProperty(prop) ) {
// prop is actually obj's property (not inherited)
}
}
(More on Prototypal Inheritance)
The problem with using the for..in structure on the Array type is that there is no garauntee as to what order the properties are produced... and generally speaking that is a farily important feature in processing an array.
Another problem is that it usually slower than a standard for implementation.
Bottom Line
Using a for...in to iterate arrays is like using the butt of a screw driver to drive a nail... why wouldn't you just use a hammer (for)?

for...in is to be used when you want to loop over the properties of an object. But it works the same as a normal for loop: The loop variable contains the current "index", meaning the property of the object and not the value.
To iterate over arrays, you should use a normal for loop. buttons is not an array but a NodeList (an array like structure).
If iterate over buttons with for...in with:
for(var i in a) {
console.log(i)
}
You will see that it output something like:
1
2
...
length
item
because length and item are two properties of an object of type NodeList. So if you'd naively use for..in, you would try to access buttons['length'].removeAttribute() which will throw an error as buttons['length'] is a function and not a DOM element.
So the correct way is to use a normal for loop. But there is another issue:
NodeLists are live, meaning whenever you access e.g. length, the list is updated (the elements are searched again). Therefore you should avoid unnecessary calls to length.
Example:
for(var i = 0, l = buttons.length; i < l, i++)

for(var key in obj) { } iterates over all elements in the object, including those of its prototypes.
So if you are using it and cannot know nothing extended Object.prototype you should always test obj.hasOwnProperty(key) and skip the key if this check returns false.
for(start; continuation; loop) is a C-style loop: start is executed before the loop, continuation is tested and the loop only continues while it's true, loop is executed after every loop.

While for..in should not generally be used for Arrays, however prior to ES5 there was a case for using it with sparse arrays.
As noted in other answers, the primary issues with for..in and Arrays are:
The properties are not necessarily returned in order (i.e. not 0, 1, 2 etc.)
All enumerable properties are returned, including the non–index properties and those on the [[Prototype]] chain. This leads to lower performance as a hasOwnProperty test is probably required to avoid inherited properties.
One reason to use for..in prior to ES5 was to improve performance with sparse arrays, provided order doesn't matter. For example, in the following:
var a = [0];
a[1000] = 1;
Iterating over a using for..in will be much faster than using a for loop, as it will only visit two properties whereas a for loop will try 1001.
However, this case is made redundant by ES5's forEach, which only visits members that exist, so:
a.forEach();
will also only iterate over two properties, in order.

Related

IE8 for...in enumerator

So I am using this in IE8:
var hi=["hi", "lo", "foo", "bar"];
for(i in hi){console.log(i)};
//WTF is that indexOf i value?
LOG: 0
LOG: 1
LOG: 2
LOG: 3
LOG: indexOf
undefined
In chrome and others, I'll just get 0-3, no mysterious "indexOf" thing. Why and what's the fix?
Don't use for...in for arrays. It's best to use the traditional for loop in that case.
The reason is because for...in looks at the array as an object, and therefore properties like indexOf or length may be included in the loop. The normal for loop only deals with numeric keys, so this problem is avoided.
On a side note, unwanted properties could show up when iterating over plain objects as well (as others have noted, properties you add to the object's prototype will show up). You can get around this by writing your for...in loops this way:
var obj = { ... };
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var item = obj[prop];
...
}
}
To be clear though: you still shouldn't use this method on arrays.
You're using the wrong type of loop for an array - for ... in ... will also include any enumerable properties of the object, which in your case includes the .indexOf() method.
Use this instead:
var i, n = hi.length;
for (i = 0; i < n; ++i) {
console.log(i, hi[i]);
}
Chrome and other up to date browsers implement ECMAScript 5, and correctly mark all built-in methods as non-enumerable properties.
This is happening because a script you are including on your page is adding the indexOf method to Array.prototype. This means all arrays inherit an indexOf method, which is good, since it means you can use that method even in IE8.
But, since there is no way to mark a property as non-enumerable in IE8, you will end up seeing it every time you enumerate over all the properties of the array, which is what you do in a for-in loop. You probably wanted a for loop instead.

what is for....in statement in javascript

anyone can explain how to use for...in statement in javascript. I had read the w3school article but i think it is not so clear.Below is the code, please explain this:
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[10] = "Saab";
mycars[20] = "Volvo";
mycars[30] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
A for in loop will iterate through every property in an object.
In your example, the x variable will cycle through every property in the mycars object.
If you add mycars.expensive = "Porsche";, it will find that too.
Note that, as stated by MDC, for in loops should not be used to loop through ordinary arrays:
Although it may be tempting to use
this as a way to iterate over an Array,
this is a bad idea. The
for...in statement
iterates over user-defined properties
in addition to the array elements, so
if you modify the array's non-integer
or non-positive properties (e.g. by
adding a "foo" property
to it or even by adding a method or
property to
Array.prototype), the
for...in statement will
return the name of your user-defined
properties in addition to the numeric
indexes. Also, because order of
iteration is arbitrary, iterating over
an array may not visit elements in
numeric order. Thus it is better to
use a traditional for loop with a numeric index when
iterating over arrays. Similar
arguments might be used against even
using for...in at all (at least
without propertyIsEnumerable()
or hasOwnProperty()
checks), since it will also iterate
over Object.prototype (which, though
usually discouraged, can, as in the
case of Array.prototype, be usefully
extended by the user where are no
namespacing concerns caused by
inclusion of other libraries which
might not perform the above checks on
such iterations and where they are
aware of the effect such extension
will have on their own use of
iterators such as for...in).
First you create an object with 3 items (and not an Array)
var mycars = new Object();
mycars[10] = "Saab";
mycars[20] = "Volvo";
mycars[30] = "BMW";
where 10, 20 and 30 are the object properties.
then you want to navigate through the object, visit all properties and display each value associated to a property.
This is where the [ for (variable in object) expression ] javascript construction intervenes:
The variable will be set to the first property of the object, then to the 2nd, then to the last. Try
for (v in mycars) alert(v);
to see how it works, and this as well
for (v in mycars) alert("Property: "+v+", value: "+mycars[v]);
The for ... in construction iterates over every element within the object on the right side of in. In your case, the block below the for statement is executed once for every car in mycars.
for in is a way of burying bugs for later generations to discover. As has been copiously pointed out, if applied to an Array, it will loop through all the elements of the array, and the length of the array, and whatever other data happens to be attached to the array. Applying it to an ordinary object is better, but you still should still filter the indices through hasOwnProperty.
Better to use a framework-provided function like jQuery's $.each

What is the difference between 'for...in' and 'for each...in' in javascript? [duplicate]

This question already has answers here:
What is the difference between for..in and for each..in in javascript?
(4 answers)
Closed 8 years ago.
I know in C# you use foreach like this: foreach string str in array1 {console.writeline(str);}
Is "for each ... in" used like that in JavaScript too?
Afaik only Firefox supportes for each...in. It is not part of any standard and most tools like JSLint will throw errors if they encountered it.
The difference is that for...in loops over the keys of an object whereas for each...in loops over the values.
So the recommended way is to not use for each and do
for (var key in obj) {
console.log(obj[key]);
}
instead.
Update: I cannot say how it relates to C#. But regarding arrays: Never use for...in to traverse arrays (yellow box here):
Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.
Use a normal for loop instead:
for(var i = 0, l = arr.length; i<l; i++)
or more fancy:
for(var i = arr.length; i--;)
There is no for each in in standard JavaScript. It may exist in specific implementations, if they want to extend the language.
for..in in JavaScript only relates to arrays by association, because it relates to objects, and arrays are objects. for..in does not loop through array entries, as for each does in C#. Nor does it loop through array indexes although people tend to think it does. (It loops through property names; array indexes are property names, but an array object can have other properties as well.) It's more like for each with the keys of a dictionary. I've discussed this fairly thoroughly in this article.
"for each ... in" returns the values rather than the keys... See here:
http://www.dustindiaz.com/for-each-in/
The in operator is used to enumerate the properties (the names, not the values) of a javascript object - and in javascript, all non-primitives are objects (inherit from Object).
You use it like this
var obj = {
a: "aaa",
b: "bbb"
};
for (var key in obj) {
if (obj.hasOwnProperty(key)){
console.log("obj has a property " + key + ", with a value of " + obj[key]);
}
}
Since in also enumerates properties inherited through the prototype chain, we must use hasOwnProperty to check if these are indeed the objects own properties, and not just inherited ones.
Note that the in operator should never be used to enumerate the items stored in arrays - for this you should use a regular for/while loop using the index.

Exclude variables from object

So basically I understand you can loop through an array in either of these ways.
var testarray = new Array(1,2,3,4);
for(i in testarray)console.log(testarray[i]);
//outputs 1,2,3,4
for(var i=0;i<testarray.length;i++) console.log(testarray[i]);
//outputs 1,2,3,4
My question how can I duplicate/emulate that array. With support for both of the for loop methods? Because when I do the same thing but I create my own function it includes length in the 1st for loop.
function emulatearray(){
for(var i = 0;i<arguements.length;i++)this[i]=arguments[i];
this.length = i;
}
var testarray = new emulatearray(1,2,3,4);
for(i in testarray)console.log(testarray[i]);
//outputs 1,2,3,4,null
for(var i=0;i<testarray.length;i++) console.log(testarray[i]);
//outputs 1,2,3,4
The for...in statement shouldn't be used to iterate over an array.
Quoting the Mozilla Dev Center:
for...in Statement
Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.
Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.
This is exactly the reason why you shouldn't use the for (i in array) ... construct. The JavaScript array's length property is internally declared as non-enumerable, so it doesn't appear when you iterate through the object, but any properties that you define are always enumerated.
The upcoming ECMAScript 5 has a way to define your own properties as non-enumerable, but most browsers don't support it as yet.

Weird problem with JSMock

Can someone explain what's going on here, and how to fix it? I'm using JSMock, and executing the following code in spec.js:
for (var t in []) {
alert(t)
}
... causes my browser to alert "eachIndexForJsMock" (when it shouldn't execute the alert command at all). This is messing up my for each loops. How do I fix it?
The problem is that JSMock augments the Array.prototype object.
The for-in statement is meant to be used to enumerate object properties, for arrays and array-like1 objects, it is always recommended to use an iterative loop, e.g.:
for (var i = 0; i < arr.length; i++) {
//...
}
You should avoid for-in on array-like objects because:
The order of iteration is not guaranteed, the indexes may not be visited in the numeric order.
Inherited properties are also enumerated.
See also:
Iteration VS Enumeration
[ 1 ] By array-like I mean any object that contains sequentially numbered properties and a length property.

Categories