JavaScript
    About Lesson

    for-in Loop is a control flow statement that iterates over the enumerable properties of an object, in an arbitrary order. It’s primarily used when you want to work with the properties of an object or elements of an array, but you don’t know how many there are.

     

    Syntax of a for-in Loop

    The syntax of a for-in Loop in JavaScript is as follows:

    for (variable in object) {
       // code to be executed
    }

     

    • Variable: This is a different property name that’s assigned in each iteration.
    • Object: This is the object whose enumerable properties are iterated.

     

    Example of a for-in Loop

    Here’s a simple example of a for-in Loop that prints the properties of an object:

    let student = {
       name: "John Doe",
       age: 20,
       course: "Computer Science"
    };
    
    for (let property in student) {
       console.log(`${property}: ${student[property]}`);
    }

     

    In this example, the for-in Loop iterates over the properties of the student object and prints each property and its value.

     

    The for-in Loop is a unique tool in JavaScript, allowing you to easily iterate over the properties of an object or elements of an array. It’s a fundamental concept that’s widely used in programming, so understanding how it works will greatly enhance your JavaScript coding skills.