JavaScript: for in Statement
Description
The for...in statement iterates (the act of repeating a process) a specified variable over all the properties of an object and execute one or more statements for each property of the object.
Syntax
for (variable in object) { statements }
Parameters
Variable:
Variable to iterate over every property of the object and the variable is accessible outside the loop, after completing the loop.
statements : The statement to be executed for each property of an object. For multiple statements within the loop use a block statement ({..}).
Example:
In the following web document for in statement iterates a specified variable over all the properties of an object.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript for in statement : Example-1</title>
<link rel="stylesheet" type="text/css" href="example.css">
</head>
<body>
<h1>JavaScript : for in statement </h1>
<p id="result">Output will be displayed here.</p>
<script src="for-in-statement-example1.js"></script>
</body>
</html>
JS Code
function demo()
{
var key, str1 = "";
// Initialize object.
var student = {
name : "David Rayy",
classname : "V",
rollno : 12
};
// Iterate the properties.
for(key in student)
{
str1 = str1+ student[key];
}
return(str1);
}
var newParagraph = document.createElement("p");
var newText = document.createTextNode(demo());
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);
View the example in the browser
Practice the example online
See the Pen for-in-1 by w3resource (@w3resource) on CodePen.
Previous: JavaScript: continue statement
Next: JavaScript: try...catch statement
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript/statements/for-in.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics