nath.bplb 0 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 Quote Link to post Share on other sites
JamesB 50 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. Quote Link to post Share on other sites
ShadowMage 94 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 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.