The For In Loop
The JavaScript for in statement loops through the properties of an Object:
for (key in object) {
// code block to be executed
}
Example
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
let text = "";
for (let x in person) {
text += person[x];
}
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 JavaScriptfor instatement can also loop over the properties of an Array: for (variable in array) {
code
}Example
const numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
txt += numbers[x];
}let txt = "";
No comments:
Post a Comment