nath.bplb Posted September 1, 2011 Report Share Posted September 1, 2011 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 comment Share on other sites More sharing options...
JamesB Posted September 1, 2011 Report Share Posted September 1, 2011 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 comment Share on other sites More sharing options...
ShadowMage Posted September 1, 2011 Report Share Posted September 1, 2011 (edited) 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 meThe 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 September 1, 2011 by ShadowMage Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now