user466534
user466534

Reputation:

for in loop in javascript

i am trying to understand following fragment of javascript code

<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script type="text/javascript">
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
{
txt=txt + person[x];
}

document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>

i am a little confused with this line

for (x in person)
    {
    txt=txt + person[x];
    }

as i guessed it is a associative array,with key--> value relationship and as a final result should not it print like this?

fname:"John",lname:"Doe",age:25

? thanks very much

Upvotes: 0

Views: 317

Answers (3)

avk
avk

Reputation: 1004

As said, javascript has no concept of associative arrays and it is better to do some reading about js than the normal run and test approach because there are some behaviors which is not logically correct untill we learn to think the way js does.

for for..in loops check this https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in and do read the hasOwnProperty part . This confuses a lot of people.

I suggest you read http://eloquentjavascript.net/ and whenever have any issues keep checking on MDN. the documentation is really good there.

Upvotes: 3

Rishabh
Rishabh

Reputation: 1195

Firstly person is not an array it an object

secondly for(x in person) here x is the key hence person[x] will give the value.

now in line txt = txt + person[x] you are just concatenating strings (values and not keys), so txt will just contain all the values

Got beaten by the previous answer by abt 10 seconds :)

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382656

First, there is no concept of associate arrays in JavaScript, the person is an object and an object is iterated using the for-in loop.

The line:

txt = txt + person[x];

simply reads each property of the person objects and concatenates the value in the txt variable giving the result:

JohnDoe25

FYI, always use for-in loop for objects and normal for loop for arrays.

Upvotes: 3

Related Questions