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.
JavaScript: Tips of the Day
How to insert an item into an array at a specific index (JavaScript)?
What you want is the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
Ref: https://bit.ly/2BXbp04
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework