Javascript - For Statement

About

Syntax

for in (array)

var colors = [ "blue", "green" ];
  • The index
console.log("index value are:");
for (index in colors) {
    console.log("  "+index);
}
  • Using this index, when can access the value
console.log("\ncolors[index] values are:");
for (index in colors) {
    console.log("  "+colors[index]);
}
console.log("\nwith an entries loop, you get value and index directly:");
for (const [index, value] of colors.entries()) {
  console.log("  "+index+", "+value);
}

for in (property in object)

Reference/Statements/for...in.

Not for an array

The loop iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

var person = {name: "Nicolas", length: 180};

function ColoredPerson() {
    // Rode piet !
    this.color = "red";
}
ColoredPerson.prototype = person;

var coloredPerson = new ColoredPerson();

var propSource;
for (var prop in coloredPerson) {
    if (coloredPerson.hasOwnProperty(prop)) {
        propSource = "object";
    } else {
        propSource = "prototype";
    }
    console.log("The property " + prop + " (value:" + coloredPerson[prop] + ") is a property from the " + propSource + ".");
}

for ( initialization; test; update )

for (initialization; test; update) {
    //Code to run each time through the loop
}

Let op ! Thanks to variable hoisting and function-level scope, you may create variable name clash because the code below

for (var i = 0; i < 5; i++) {
    console.log(i);
}

is equivalent to:

var i;
for (i = 0; i < 5; i++) {
    console.log(i);
}

Example:

/* To show a variable name clash with the variable in the for loop */
var i = 2;
console.log("The first value of the variable i is "+i+".");

for (var i = 0; i < 4; i++) {
  console.log(i);
}

console.log("!!!! The final value of the variable i is "+i+", not 3 and also not 2. !!!!");

Powered by ComboStrap