-1

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

2
  • What is person[x]? For x="fname" we have person[x]="John". The result is "John" + "Doe" + "25" = "JohnDoe25". Think about it. :) Commented Jun 9, 2012 at 9:47
  • May help you play around with: jsconsole ` > var txt=""; > var person={fname:"John",lname:"Doe",age:25}; > for (x in person) { txt=txt + person[x]; } > x ` Commented Jun 9, 2012 at 9:53

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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 :)

2 Comments

10 seconds or 2 minutes ? ;-)
well, i was ready to reply it and then came an alert another answer posted :) so took some more time and posted leisurely :)

Your Answer

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