Search code examples
javascriptfor-in-loop

Confused with a result of a for...in statement JS output


I was just testing out the Java Script for...in ( just a newbie :P :D ).

I tried the following code:

var arr=[];
arr['n1']='name1';
arr['n2']='name2';
arr['n3']='name3';
arr['n4']='name4';

var i,j;

for(i in arr)
{
    for(j in i)
        document.writeln(j+"-");
}

and the output was:

0- 1- 0- 1- 0- 1- 0- 1-

I was wondering why am I getting an output like this.

The for...in loop if tried to output the 'i' instead of 'j' I'm getting the index names.

When I checked the typeof 'j' I got it as String.

Please help me understand the output.


Solution

  • Javascript doesn't have an associative arrays.
    You can't fill a regular array in such way: arr['n1']='name1';.

    If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.

    var arr=[];
    arr['n1']='name1';
    arr['n2']='name2';
    arr['n3']='name3';
    arr['n4']='name4';
    var x = arr.length;         // arr.length will return 0
    var y = arr[0];             // arr[0] will return undefined
    

    As for the for-in loop - this loop has a very special purpose: it enumerates the named properties of any object.

    for(i in arr)
    {
        for(j in i)
            document.writeln(j+"-");
    }
    

    The 'parent' loop will iterate the named properties, such as n1, n2 etc. The nested loop expects the second operand to be an object: i should be an object in this expression (j in i). But the actual value is a string (n1 ,n2, n2). Therefore, Javascript will create Primitive Wrapper Object for every string on each iteration behind the scenes:

    ...
    for(j in i) // actually would be (for j in new Object('n1'))
       // console.log(new Object('n1'));
       // String {0: "n", 1: "1", length: 2, [[PrimitiveValue]]: "n1"}
       document.writeln(j+"-");
    ...
    

    As you can see, a primitive wrapper object has two "numbered" properties for each string. That's way it gives to you the output:

    0- 1- 0- 1- 0- 1- 0- 1-