JavaScript: for in Statement


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.


for (variable in object)


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 ({..}).


In the following web document for in statement iterates a specified variable over all the properties of an object.


<!DOCTYPE html>
<html lang="en">
<meta charset=utf-8>
<title>JavaScript for in statement :  Example-1</title>
<link rel="stylesheet" type="text/css" href="example.css">
<h1>JavaScript : for in statement </h1>
<p id="result">Output will be displayed here.</p>
<script src="for-in-statement-example1.js"></script>

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];
var newParagraph = document.createElement("p");
var newText = document.createTextNode(demo());

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 do I redirect to another webpage?

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace.

// similar behavior as an HTTP redirect

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ref: https://bit.ly/37JdWH8