JavaScript for-in Loop
JS for-in loop is used to iterate over the properties of an object. The for-in loop iterates only over those keys of an object which have their enumerable property set to “true”.
Syntax
for(let variable_name in object_name) {
// Statement
}
Example: This example shows the use of for-in loop.
let myObj = { x: 1, y: 2, z: 3 };
for (let key in myObj) {
console.log(key, myObj[key]);
}
Output
x 1 y 2 z 3
JavaScript Loops
JavaScript loops are essential for efficiently handling repetitive tasks. They execute a block of code repeatedly as long as a specified condition remains true. These loops are powerful tools for automating tasks and streamlining your code.
For example, suppose we want to print “Hello World” 5 times. This can be done using JS Loop easily. In Loop, the statement needs to be written only once and the loop will be executed 5 times as shown below:
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
}
Output
Hello World! Hello World! Hello World! Hello World! Hello World!
Table of Content
- for Loop
- while Loop
- do-while Loop
- for-in Loop
- for-of Loop
- Labeled Statement
- Break Statement
- Continue Statement
- Infinite Loop (Loop Error)