Javascript - For Statement

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

Advertising

3 - Syntax

3.1 - 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. !!!!");

See also: Javascript - Array

3.2 - for propertyName 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 + ".");
}

Advertising
web/javascript/es/for.txt · Last modified: 2019/02/16 17:40 by gerardnico