JavaScript For In
The For In Loop
The JavaScript code for in
helps go through the properties of an object.
Syntax
for (key in object) {
}
Example Explained
- The for in loop iterates over a person object
- Each iteration returns a key (x)
- The key is used to access the value of the key
- The value of the key is person[x]
For In Over Arrays
The JavaScript for in
statement can be used to iterate through the properties of an Array.
Syntax
for (variable in array) {
code
}
Avoid using a loop called for in with Arrays when the sequence of the index matters.
The order in which items appear in an array depends on how it's set up, and you might not be able to find items in the array in the order you think they should be.
Using a for loop, a for of loop, or Array.forEach() is best when the order matters.
Array.forEach()
The forEach()
method runs a callback function for every element in an array.
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
The given code utilizes the value parameter exclusively. It can be rephrased as follows:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement goes through all the properties of an object.</p>
<p id="demo"></p>
<script>
const person = {
fname: "John",
lname: "Doe",
age: 25
};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement checks every feature of an object one by one.</p>
<p id="demo"></p>
<script>
const person = {
fname: "John",
lname: "Doe",
age: 25
};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt += value + " <br> ";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt += value + " <br> ";
}
</script>
</body>
</html>