JavaScript for in Loop

JavaScript for in loop execute block of code for each element of an array (or each property of an object).

JavaScript has two distinct syntax for the for in statement,

  1. for (var variable in objectExpression) { statements }
  2. for (LeftHandSideExpression in objectExpression) { statements }

1. for (var variable in objectExpression) { statements }

Syntax

for (var variable in objectExpression) { 
    statements 
}

Arguments

  1. variable: Required, A unique variable name (property of an object or element index if an array) is assigned evaluated value for every iteration.
  2. objectExpression: Optional, An object or an array, that are iterate and return a result of evaluating the Expression.
  3. statements: Optional, Specified number of statements to be executed in every iteration.

Example (Array)

<script>
    var arr = ['a','b','c'];
    for (var key in arr) {
        document.writeln(key +" : "+ arr[key]);
    }
</script>

Run it...   »

Example Result

Example (Object)

<script>
    var obj = {'a': 'AAA','b': 'BBB','c' : 'CCC'};
    for (var key in obj) {
        document.writeln(key +" : "+ obj[key]);
    }
</script>

Run it...   »

Example Result

2. for (LeftHandSideExpression in objectExpression) { statements }

Syntax

for (LeftHandSideExpression in objectExpression) { 
    statements 
}

Arguments

  1. LeftHandSideExpression: Any variable name (object property or array indexes) as a reference for assignment.
  2. objectExpression: Optional, An object or an array, that are iterate and return a result of evaluating the Expression.
  3. statements: Optional, Specified number of statements to be executed in every iteration.

Example (Array): for..in loop treats array is not aligned with other programming languages.

<script>
    var arr = ['a','b','c'];
    var i = 0, arr_key = [];

    for (arr_key[i++] in arr);

    console.log(arr_key);       // returns ["0", "1", "2"]
</script>

Run it...   »

Example Result

["0", "1", "2"]

Example (Object)

<script>
    var arr = {'a': 'AAA','b': 'BBB','c' : 'CCC'};
    for (var key in arr) {
        document.writeln(key +" : "+ arr[key]);
    }
</script>

Run it...   »

Example Result

a : AAA b : BBB c : CCC