Skip to content
Related Articles

Related Articles

Explain the differences between for(..in) and for(..of) statement in JavaScript.
  • Last Updated : 31 Jan, 2020

Often in a JavaScript script, we iterate over some objects of few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops. JavaScript supports different kinds of loops:

  • for loop
  • for (..in) loop
  • for (..of) loop
  • while loop
  • do-while loop

In this article, we will be learning about the difference between for (..in) and for (..of) Loops.

for (..in) loop: The JavaScript for (..in) statement loops through the enumerable properties of an object. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype.

  • Syntax
    for (variable in object)
      statement
  • Example




    <!DOCTYPE html>
    <html>
      
    <body>
        <p id="demo"></p>
        <script>
            var person = {
                firstName: "GeeksforGeeks",
                lastName: "<br>A Computer Science Portal for Geeks ",
                rank: 43
            };
            var userId = "";
            var i;
            for (i in person) {
                userId += person[i];
            }
            document.getElementById("demo").innerHTML = userId;
        </script>
    </body>
      
    </html>
  • Output: As you can see the for (..in) loop iterate over only the properties or the values of the dictionary object.
    GeeksforGeeks
    A Computer Science Portal for Geeks 43

    for (..of) loop: This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object.

    • Syntax
      for (variable of iterable) {
        statement
      }
      
    • Example




      <!DOCTYPE html>
      <html>
          <body>
              <p id ="demo"></p>
              <script>
              var text = [
                  "GeeksforGeeks",
                  " A Computer Science Portal for Geeks ", 
                  "43"
                  ];
              var userId = "";
              var i;
              for (i of text) {
              userId+=i;
              }
              document.getElementById("demo").innerHTML = userId;
              </script>
          </body>
      </html>                    
    • Output: As you can see the for (..of) loop iterate over only the content of the Array object.
      GeeksforGeeks A Computer Science Portal for Geeks 43



    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :