JavaScript Loop For In
The for...in
loop iterates over the enumerable properties of an object. It's often used to inspect object keys or iterate over array indices, though for...in
is not recommended for arrays in some cases due to indexing quirks.
Key Topics
Iterating Object Properties
for...in
loops over the keys of an object.
let person = { name: "John", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output
> name: John
> age: 30
Explanation: The loop iterates over "name" and "age" keys, printing their values.
Array Indices with for...in
While for...in
can be used on arrays, it's generally better to use a standard for loop or for...of
, since for...in
iterates over all enumerable properties, not just numeric indexes.
JavaScript Usage in DOM
Use for...in
to display object properties and values dynamically on a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>For In in DOM</title>
</head>
<body>
<h1>For In Demo</h1>
<button onclick="showProps()">Show Properties</button>
<div id="output"></div>
<script>
function showProps() {
let car = { brand: "Toyota", model: "Corolla", year: 2021 };
let result = "";
for (let prop in car) {
result += prop + ": " + car[prop] + "
";
}
document.getElementById("output").innerHTML = result;
}
</script>
</body>
</html>
Key Takeaways
- for...in: Iterates over object keys.
- Objects: Useful for examining property names and values.
- Arrays: Not ideal for arrays; consider using
for
orfor...of
. - DOM Integration: Display object property-value pairs in the browser.