JavaScript For loop

Loops are used to execute code multiple times. It can be defined either by no. of iterations or until a condition evaluates to true.

JavaScript Loops

Loops are useful, if same code to be required to execute multiple times with different value each time. Loops are mostly used with arrays and objects.

var studentAGrade = getGrade(Student[0]);
var studentBGrade = getGrade(Student[1]);
var studentCGrade = getGrade(Student[2]);

In reality there are many more students and writing a separate line for each student is not ideal.

Solution to this problem is to use JavaScript loops

Using loops above code can be replaced with below

for(i=0; i<Student.length; i++) {
    studentGrads[i] = getGrade(Student[i]);
}

Different type of JavaScript Loops

Below types of loops are available in JavaScript

  • for : to loop for defined number of times
  • for/in : to loop for all properties of an object
  • while : to loop until a specified condition evaluates to true
  • do/while : to loop at least once irrespective of condition and than until a specified condition evaluates to true

For Loop

For loop is often used to iterate code predefined number of times.

Syntax

for ([initialization]; [condition]; [expression]) {
    // code to execute multiple times
}

initialization initialize variable before loop starts
condition defines condition for loop
expression is evaluated each time loop reach end of last statement of loop.

Example

<!DOCTYPE html>
<html>
<body>

Student grads 
<p id="text"></p>

<script>

var Student = [95,50,64,85,90];
var studentGrads = [];

for(var i=0; i<Student.length; i++) {
    studentGrads[i] = getGrade(Student[i]);
}

document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
	if(marks > 90) {
		return 'Grade A';
	} else if(marks > 80) {
		return 'Grade B';
	} else if(marks > 70) {
		return 'Grade C';
	} else if(marks > 60) {
		return 'Grade D';
	} else {
		return 'Fail';
	}
}

</script>

</body>
</html>

Download the code Run the code

Above for loop statement can be read as, initialize variable i=0 and repeat code within for loop until value of i is less than 10. After each iteration, value of i will be incremented by 1 using expression i++

Initialization

In normal way initialization is done within for statement. But it can be omitted if initialization is already done before for statement

Example

<!DOCTYPE html>
<html>
<body>

Student grads 
<p id="text"></p>

<script>

var Student = [95,50,64,85,90];
var studentGrads = [];
var i=0;
for(; i<Student.length; i++) {
    studentGrads[i] = getGrade(Student[i]);
}

document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
	if(marks > 90) {
		return 'Grade A';
	} else if(marks > 80) {
		return 'Grade B';
	} else if(marks > 70) {
		return 'Grade C';
	} else if(marks > 60) {
		return 'Grade D';
	} else {
		return 'Fail';
	}
}

</script>

</body>
</html>

Download the code Run the code

There can be more than one values in initialization part

<!DOCTYPE html>
<html>
<body>

Student grads 
<p id="text"></p>

<script>

var Student = [95,50,64,85,90];
var studentGrads = [];

for(i=0, len=Student.length; i<len; i++) {
    studentGrads[i] = getGrade(Student[i]);
}

document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
	if(marks > 90) {
		return 'Grade A';
	} else if(marks > 80) {
		return 'Grade B';
	} else if(marks > 70) {
		return 'Grade C';
	} else if(marks > 60) {
		return 'Grade D';
	} else {
		return 'Fail';
	}
}

</script>

</body>
</html>

Download the code Run the code

Condition

Condition is mostly used for comparison of initialized variable. Loop continues until condition evaluates to true. Condition is also optional. If condition is not provided, there must be a break statement inside loop.

Expression

Expression is often used to change the value of initialized variable. Even statement 3 is optional.

Expression can increment or decrements initialized variable value.

<!DOCTYPE html>
<html>
<body>

Student grads 
<p id="text"></p>

<script>

var Student = [95,50,64,85,90];
var studentGrads = [];

for(i=0; i<Student.length;) {
    studentGrads[i] = getGrade(Student[i]);
	i++;
}

document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
	if(marks > 90) {
		return 'Grade A';
	} else if(marks > 80) {
		return 'Grade B';
	} else if(marks > 70) {
		return 'Grade C';
	} else if(marks > 60) {
		return 'Grade D';
	} else {
		return 'Fail';
	}
}

</script>

</body>
</html>

Download the code Run the code

For..In loop

JavaScript for..in statement is used to iterates properties of JavaScript Object.

For each property of an Object a loop is execute once.

Syntax

for (property in objectName) {
    //iterates all properties of an object
    // each property is assigned to variable
}

where

property is a different property name of an Object
objectName An object which is iterated

A for…in loop only iterates over enumerable properties of an object.

Example

<!DOCTYPE html>
<html>
<body>

Properties of an item object are: 
<p id="text"></p>

<script>

var item = {type:"Clothes", category:"Women cloths", sub_cat:"Winter wear"}; 
var msg='';
for(prop in item) {
	msg += prop + ' : ' + item[prop]+'<br>';
}
document.getElementById('text').innerHTML = msg;
</script>

</body>
</html>

Download the code Run the code

In above example item object is iterates over all enumerated properties.

Added/Modified or Deleted properties

If a property is modified in one iteration than, in next iteration a property contains a modified value. A property that is deleted from the object cannot be iterated later. It is better not to add , modify or delete properties of an object while it is iterates.

Iterating over own properties

If it is required to iterate only own properties of an object and not its prototype properties use a hasOwnProperty()

The following example shows the use of hasOwnProperty(): the inherited properties are not displayed.

Example

<!DOCTYPE html>
<html>
<body>

Properties of an item object are: 
<p id="text"></p>

<script>

var texts = '';
var square = {sides:4, corner:4, angle:90};

function SquareColor() {
  this.color = "red";
}

SquareColor.prototype = square;

var obj = new SquareColor();
for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
    texts += prop + " : " + obj[prop];
  } 
}

document.getElementById('text').innerHTML = texts;
</script>

</body>
</html>

Download the code Run the code

<<< JavaScript Switch statementJavaScript while loop >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .