3

I'm having trouble understanding the way this for in loop works.

function createSimpleNode(name, options, text) {
         var node = document.createElement(name); 

        for (var o in options) { 
                 node.setAttribute(o, options[o]);
        }

        if (text) { 
                node.innerHTML = text;
        }

        return node; 
}
2
  • 1
    For In - iterates over a collection just, it will pull the first type off the list and let use it in the following code block. Using o in options[o] will never set, as it is not an Index in the collection. Maybe look at JavaScript Loops Commented Jan 3, 2015 at 7:20
  • updated my answer for example of object and array Commented Jan 3, 2015 at 7:38

2 Answers 2

5

The For in loop gives a way to iterate over an object or array with each value and key.

It can be applied over an object or Array.

For an Object

For an object it gives each key in the object as the ITER variable. Using this variable you can get the corresponding value from object.

var options = {a:1,b:2};

for (var key in options) { 
    console.log(o,options[key]);
}

Will Iterate over the options object and print each key and it's value.

a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2    

For an Array

For an array it gives each index in the array as the ITER variable. Using this variable you can get the corresponding element from array.

var options = ["a","b"];

for (var index in options) { 
    console.log(index,options[index]);
}

Will Iterate over the options array and print each index and element on given index. Output will be:-

0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b    
Sign up to request clarification or add additional context in comments.

Comments

1

This is a for..in loop. it iterates over the properties of an object (options, in this case), and allows you access the said property in each iteration using the [] operator.

In your example, you iterate over options properties, and set them all as attributes of node.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.