JavaScript For…in Loop

The for…in loop is used to iterate all the properties of an object in their actual order. The synax of the loop is such that a variable is initialised in the loop followed by the object’s name which is to be iterated.

var object = ....
for (variable in object) {
	statement1;
	statement2;
}
var obj = {a: 'Monday', b: 'Tuesday', c: 'Wednesday', d: 'Thursday'};
for (var prop in obj) {
  console.log('obj.' + prop +'= '+obj[prop]);
}

Loop Controls

We already know how to come out of the for loop using the break keyword. What if we only need to come out of single or multiple iteration condition. Thus, not breaking the loop.

To get the desired output continue keyword is used

How will you print number from 1 to 100 excluding 34,57,81 and 95?

for(var i=1;i<=100;i++){
	if(i===34 || i==57 || i==81)
		continue;
	else
		console.log(i);
}

Break the Loop

To break the loop we can use break keywork inside the loop by putting some condition.

var a = 0;
for(;;){
a++;
console.log(a);
if(a===10) 
	break;
}
Translate »