<span>
for ([initialization]; [condition]; [final-expression]) statement
</span>
<span>
for (variable in object) {... }
A for...in loop only iterates over enumerable properties
</span>
JavaScript
console.groupCollapsed("Using for");
for (var i = 0; i < 9; i++) {
console.log(i);
// more statements
}
console.log("Optional for 1");
//1
var i = 0;
for (; i < 9; i++) {
console.log(i);
// more statements
}
console.log("Optional for 2");
//2
for (var i = 0;; i++) {
console.log(i);
if (i > 3) break;
// more statements
}
console.log("Optional for 3");
//3
var i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
console.groupEnd();
console.groupCollapsed("Using for...in");
//for..in should not be used to iterate over an Array where index order is important.
//Iterates over all objects enumerable properties and return string
console.log("for...in : 1");
var obj = {a:1, b:2, c:3};
for (var prop in obj) {
console.log("o." + prop + " = " + obj[prop]);
}
//illustrates the use of hasOwnProperty(): the inherited properties are not displayed.
console.log("for...in with hasOWnProeprty : 2");
var triangle = {a:1, b:2, c:3};
function ColoredTriangle() {
this.color = "red";
}
ColoredTriangle.prototype = triangle;
var obj = new ColoredTriangle();
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) {
console.log("o." + prop + " = " + obj[prop]);
}
}
console.groupEnd();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.