Jump to content

For...In Statement


nath.bplb

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 comment
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 comment
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.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...