JavaScript - While Loops




JavaScript - While Loops

JavaScript while loops can executes a statement or series of statements until a specified condition is false, JavaScript while loops are a way of repeating the same block of code over and over.

To control the times a while loop repeats, we start with a variable set to a number. We call this variable a counter variable.

var counter = 1;

Then, we use a comparison in the condition to compare the counter variable to a number. In this case, counter < 4.

var counter = 1;

while (counter < 4) {
 
}

Inside the code block, we make the condition return false and stop the loop by incrementing the counter variable. Try it with counter++.

var counter = 1;

while (counter < 4) {
 console.log(counter);
 counter++;
}

Loops can execute a block of code as long as a specified condition is true. the while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition) {
  // code block to be executed
}

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
var text = "";
var i = 0;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output

JavaScript While Loop

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

What is an JavaScript While Loops ?

The while loop executes a block of code as long as the defined condition is true. You can also use a do while JavaScript loop. It will execute the code once even if the condition is false. You should remember to set the variable to be increased in order to avoid an infinite loop.

The JavaScript While Loop is used to repeat a block of statements for a given number of times until the given condition is False. The While loop in JavaScript starts with the condition, if the condition is True, statements inside the while loop will execute. If it is false, it won’t run at least once. It means, JavaScript while loop may execute zero or more time.

Syntax

When you're writing a while loop JavaScript syntax rules should always be in your mind. It is essential you write it correctly, otherwise you might not be able to achieve the results you want. Take a look at the standard while loop JavaScript syntax -

while (condition) {
code that will be executed
}

In the example below, you can see (i < 10) is set as the condition. This means that the code in the loop will run over and over again, as long as the variable i is less than 10.

while (i < 10) {      
  example += "Loop counter: " + i;      
  i++;
}

A basic while loop tests for the ending condition immediately. If the ending condition is met, then the loop never executes. This type of loop is useful when you may or may not need to perform processing on some type of variable data. For example, a while loop of this sort works perfectly with a function that accepts zero or more optional arguments. The fact that there may not be any arguments to process means that the while loop will never execute. The following example shows such a scenario.

function OptionalArgument(param)
{
 // Display the default output.
 document.getElementById("Result").innerHTML =
   "Nothing Passed!";
  // Create a string to hold the arguments.
  var Result = new String();
  // Process each of the arguments in turn.
  while (param.length > 0)
  {
   // Remove the current argument.
   var Argument = param.shift();
   // Verify that the argument is of the right type.
   if (typeof(Argument) == 'string')
   {
     // Add to the argument string.
     Result += Argument + "
"; } } // Display the results onscreen. document.getElementById("Result").innerHTML = Result; }

In this example, OptionalArgument() receives an array as input. When someone sends something other than an array, the function acts as if the user didn’t send anything at all. The array can contain any number of elements — the function doesn’t care how many or how few. the while loop checks the length of param. When param contains even a single element, the loop begins processing the data. The call to shift() removes the first element from the array, making the array shorter by one element. When this Argument is of type string, it’s added to Result.

The sacred boolean. What is a boolean and why is it called boolean? I feel like computer science is a breeding ground for nomenclature. Booleans are binary values in computer science (“true” and “false”). In Javascript they are primitive data types (unalterable data types) and are used constantly even if you don’t see them explicitly. Example: Let’s write a function that determines if functions argument is an integer, string, or a boolean.

function valueType(param){
    if(typeof(param) === "number"){
        return "It's an Integer!"
    } else if(typeof(param) === "boolean"){
        return "It's a Boolean!"
    } else if(typeof(param) === "string"){
        return "It's a String!"
    } 
}
valueType(5)
valueType("not a boolean")
valueType(true)

If “if” and “else if” statements are functioning on boolean logic, even though it’s not explicit. It’s a basic, easy to understand, and super powerful aspect of programming. If you copy and paste the content of the “if” statement into inspect, you’ll see the logic.

typeof(true) === "boolean"
=> true
typeof("this is a string") === "boolean"
=> false

This is the same logic “while” loops use. It can be a super readable, logical and clean way to iterate a collection.

How it work

The while loop - condition test occurs before statement in the loop are executed.if the condition returns true, then the body of the loop is executed.After execution of the body, the condition is once again evaluated and if it is true, the body is executed once again.This process of repeated execution of the body continues until the condition finally becomes false and the control is transferred out of the loop".

Example - The loop in this example will continues to run as long as the variable i is less than 10:

Example

<html>
<head>
	<script type="text/javascript">
		document.write("<b>Using while loops </b><br />");
		var i = 0, j = 1, k;
		document.write("Fibonacci series less than 40<br />");
		while(i<40)
		{
			document.write(i + "<br />");
			k = i+j;
			i = j;
			j = k;
		}
	</script>
</head>
<body>
</body>
</html>

Output

Using while loops
Fibonacci series less than 40
0
1
1
2
3
5
8
13
21
34