Intro To JavaScript Loop

With the help of a loop, We can execute our code as many times as we want.

There are four methods for looping in Javascript which are the following:

  1. for
  2. for/in
  3. while
  4. do/while

for Loop

Example-

<!DOCTYPE html>
<html>
<head>
	<title>Javascript Loop</title>
</head>
<body>

<center>
<button onclick="demo()">Click</button>
</center>

<script>

function demo()
{
	var languages = ["HTML","CSS","Javascript","Jquery","Bootstrap"];

	for(i=0;i<languages.length;i++)
	{
		document.write(languages[i]+"<br>");
	}
}

</script>
</body>
</html>

for/in loop

Example-

<!DOCTYPE html>
<html>
<head>
	<title>Javascript Loop</title>
</head>
<body>

<center>
<button onclick="demo()">Click</button>
<div id="div1"></div>
</center>

<script>

function demo()
{
	var languages = {name:"Ram",fathers_name:"Rhim",age:21};

	for(details in languages)
	{
		document.write(languages[details]+"<br>");
	}
}

</script>
</body>
</html>

while loop

Example-

<!DOCTYPE html>
<html>
<head>
	<title>Javascript Loop</title>
</head>
<body>

<center>
<button onclick="demo()">Click</button>
<div id="div1"></div>
</center>

<script>

function demo()
{

	var languages = ["HTML","CSS","Javascript","Jquery","Bootstrap"];
	var i = 0;
	while(i < languages.length)
	{
		document.write(languages[i]+"<br>");
		i++
	}
}

</script>
</body>
</html>

do/while loop

Example-

<!DOCTYPE html>
<html>
<head>
	<title>Javascript Loop</title>
</head>
<body>

<center>
<button onclick="demo()">Click</button>
<div id="div1"></div>
</center>

<script>

function demo()
{

	var languages = ["HTML","CSS","Javascript","Jquery","Bootstrap"];
	var i = 0;
	do{
		document.write(languages[i]+"<br>");
		i++;
	}
	while(i < languages.length);
	
}

</script>
</body>
</html>

Leave a Comment