Jump to content

For...In Statement


Recommended Posts

var person={fname:"John",lname:"Doe",age:25};for (x in person){document.write(person[x] + " ");}

Here the variable x carries no values as it was not pre-declared, Then how it outputs the result like- John Doe 25Also give me one another example of For...In statement, so that the concept becomes more clear to me

Link to post
Share on other sites

if you don't put the 'var' word before a variable, the scope of that variable becomes global, instead of local.a variable can contain a value whether it's global or local.so if you added this to the end of your code:

alert(x);

you should see that it alerts "age", the last value that was assigned to the x variable.if you're running that code in global scope, putting the 'var' word before x will still make it global.but if you're not running the code in global scope, eg. inside a function, the 'var' word will make the variable local to the function.

Link to post
Share on other sites
Here the variable x carries no values as it was not pre-declared, Then how it outputs the result like- John Doe 25Also give me one another example of For...In statement, so that the concept becomes more clear to me
The for...in loop iterates over each property of an object. When the interpreter sees the for...in syntax it knows that it should loop through each property and assign the property name to the variable provided (in your example, x) and then executes the code you define in the loop for each property.Check here for more information. Edited by ShadowMage
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...