Categories
JavaScript Tutorials

Loop statements

To understand conditional statements, we imagined the JavaScript interpreter following a branching path through your source code. The looping statements are those that bend that path back upon itself to repeat portions of your code. JavaScript has four looping statements: while, do/while, for, and for/in. The subsections below explain each in turn. One common use for loops is to iterate over the elements of an array.

while

Just as the if statement is JavaScript’s basic conditional, the while statement is JavaScript’s basic loop.

Syntax:

while (expression)
statement

To execute a while statement, the interpreter first evaluates expression. If the value of the expression is falsy, then the interpreter skips over the statement that serves as the loop body and moves on to the next statement in the program. If, on the other hand, the expression is truthy, the interpreter executes the statement and repeats, jumping back to the top of the loop and evaluating expression again. Another way to say this is that the interpreter executes statement repeatedly while the expression is truthy. Note that you can create an infinite loop with the syntax while(true). In almost every loop, one or more variables change with each iteration of the loop. Since the variables change, the actions performed by executing statement may differ each time through the loop. Furthermore, if the changing variable or variables are involved in expression, the value of the expression may be different each time through the loop. This is important; otherwise, an expression that starts off truthy would never change, and the loop would never end! 

Here is an example of a while loop that prints the numbers from 0 to 9:

var count = 0;
while (count < 10) {
console.log(count);
count++;
}

As you can see, the variable count starts off at 0 and is incremented each time the body of the loop runs. Once the loop has executed 10 times, the expression becomes false (i.e., the variable count is no longer less than 10), the while statement finishes, and the interpreter can move on to the next statement in the program. Many loops have a counter variable like count. The variable names i, j, and k are commonly used as loop counters, though you should use more descriptive names if it makes your code easier to understand.

for

The for statement provides a looping construct that is often more convenient than the while statement. The for statement simplifies loops that follow a common pattern. Most loops have a counter variable of some kind. This variable is initialized before the loop starts and is tested before each iteration of the loop. Finally, the counter variable is incremented or otherwise updated at the end of the loop body, just before the variable is tested again. In this kind of loop, the initialization, the test, and the update are the three crucial manipulations of a loop variable. The for statement encodes each of these three manipulations as an expression and makes those expressions an explicit part of the loop syntax:

for(initialize ; test ; increment)
statement

initialize, test, and increment are three expressions (separated by semicolons) that are responsible for initializing, testing, and incrementing the loop variable. Putting them all in the first line of the loop makes it easy to understand what a for loop is doing and prevents mistakes such as forgetting to initialize or increment the loop variable. The simplest way to explain how a for loop works is to show the equivalent while loop:

Initialize;
while(test) {
statement
increment;
}

In other words, the initialize expression is evaluated once, before the loop begins. To be useful, this expression must have side effects (usually an assignment). JavaScript also allows initialize to be a var variable declaration statement so that you can declare and initialize a loop counter at the same time. The test expression is evaluated before each iteration and controls whether the body of the loop is executed. If test evaluates to a truthy value, the statement that is the body of the loop is executed. Finally, the increment expression is evaluated. Again, this must be an expression with side effects in order to be useful. Generally, either it is an assignment expression, or it uses the ++ or — operators.

We can print the numbers from 0 to 9 with a for loop like the following. Contrast it with the equivalent while loop shown in the previous section:

for(var count = 0; count < 10; count++) {
  console.log(count);
}

Loops can become a lot more complex than this simple example, of course, and sometimes multiple variables change with each iteration of the loop. This situation is the only place that the comma operator is commonly used in JavaScript; it provides a way to combine multiple initialization and increment expressions into a single expression suitable for use in a for loop:

var i,j;
for(i = 0, j = 10 ; i < 10 ; i++, j--) {
  sum += i * j;
}

In all our loop examples so far, the loop variable has been numeric. This is quite common but is not necessary. 

The following code uses a for loop to traverse a linked list data structure and return the last object in the list (i.e., the first object that does not have a next property): 

function tail(o) { // Return the tail of linked list o
  for(; o.next; o = o.next) /* empty */ ; // Traverse while o.next is truthy return o;
}

Note that the code above has no initializer expression. Any of the three expressions may be omitted from a for loop, but the two semicolons are required. If you omit the test expression, the loop repeats forever, and for(;;) is another way of writing an infinite loop, like while(true).

Examples

Print “Hello World” 3 times.

Whenever we want to do something repeatedly, we need to use loops. This example can be implemented using while or for loops. First, let’s do it using while loop.

We need a variable to count the number of times it is printed. So, we take a variable:

var count = 0;

This count will be incremented every time the text “Hello World” is printed. So, the loop should stop when the counter reaches 3. Therefore, the condition for the while loop would be count<=3. The while loop would be as follows:

var count = 0;
while(count<3) {
  console.log('Hello World');
  count++;
}

The same thing can be achieved by using for loop. The for loop takes 3 expressions: initializer, condition and updation.

Here, we can start the counter from 0. So, the initializer statement would be var count = 0. We need to print the text 3 times. So, the condition would be count<3. We need to increase the count after printing every time. So, the updation statement would be count++. The for loop would be as follows:

for(var count = 0; count < 3; count++) {
  console.log('Hello World');
}
Print 1 to 10.

Here, we need to start printing from 1 and stop at 10. So, initialization statement would be var x = 1. The condition would be x<=10. And the updation statement would be x++. The for loop would be as follows:

for(var x=1;x<=10;x++) {
  console.log(x);
}
Print 10 to 1.

This example is similar to the previous one but in reverse order. We need to start from 10 and stop at 1. Also we need to decrement the value every time the number is printed. So, the for loop would be as follows:

for(var x=10;x>=1;x--) {
  console.log(x);
}
Print all the even numbers between 1 and 10 in ascending order.

To implement this, we have to check for even numbers between 1 and 10. For this, we need to have a if statement inside the for loop. The if statement will check each number whether it is an even number or not. It will print the number only if it is an even number.

for(var x=1;x<=10;x++) {
  if(x%2===0){
    console.log(x);
  }
}
Print all the even numbers between 1 and 10 in descending order.

For this, we will do the same as the previous example but in reverse order.

for(var x=10;x>=1;x--) {
  if(x%2===0){
    console.log(x);
  }
}
Print all the odd numbers between 1 and 10 in ascending order.

For this, we need to check for odd numbers, which means we have to check which numbers don’t give 0 as remainder when divided by two.

for(var x=1;x<=10;x++) {
  if(x%2!==0){
    console.log(x);
  }
}
Print all the odd numbers between 1 and 10 in descending order.

For this, we will do the same as the previous example but in reverse order.

for(var x=10;x>=1;x--) {
  if(x%2!==0){
    console.log(x);
  }
}
Count the number of even numbers between 1 and 10.

We need to have a variable to keep count of the even numbers between 1 and 10. So, inside the for loop, when we check for even number, we need to increment the count if it is an even number. The code will be as follows:

var count = 0;
for(var i=1;i<=10;i++) {
  if(i%2===0) {
    count++;
  }
}
console.log('The number of even numbers between 1 and 10 is ' + count);
Count the number of odd numbers between 1 and 10.

For this, it is same as the previous example but we need to check for odd numbers as follows:

var count = 0;
for(var i=1;i<=10;i++) {
  if(i%2!==0) {
    count++;
  }
}
console.log('The number of odd numbers between 1 and 10 is ' + count);
Print all the multiples of 3 between 1 and 20 in ascending order.

For this example, we have to check each number between 1 and 20 whether it is a multiple of 3. We need to print the number only if it is a multiple of 3.

for(var x=1;x<=20;x++) {
  if(x%3===0){
    console.log(x);
  }
}
Print all the multiples of 3 between 1 and 20 in descending order.

This example is same as the previous one but in reverse order.

for(var x=20;x>=1;x++) {
  if(x%3===0){
    console.log(x);
  }
}
Count all the multiples of 4 between 1 and 20.

Here, we need to have a variable to keep count of the number of multiples of 4 between 1 and 20. It will increase every time a multiple of 4 is detected.

var count = 0;
for(var i=1;i<=20;i++) {
  if(i%4===0) {
    count++;
  }
}
console.log('The number of multiples of 4 between 1 and 20 is ' + count);
Print all the factors of 12.

To find the factors of a number n, we need to divide the number n by all numbers between 1 and n. Whenever the division by a number gives 0 as remainder, that number is known as the factor of the number n. So, we need to loop from 1 to n and check which numbers give remainder as 0 on dividing n. Accordingly, we need to print those numbers(which are the factors).

for(var i=1;i<=12;i++) {
  if(12%i===0) {
    console.log(i);
  }
}
Count the number of factors of 12.

This example is similar to the previous example but instead of printing the factor, we need to increment a count variable so that we can know how many factors are there.

Using while loop:

var a = 1;
var n = 12;
var count = 0;
while(a<=n){				
  if(n%a===0){
    count++;
  }
  a++;
}			
console.log(count);

Using for loop:

var count = 0;
for(var i=1;i<=12;i++) {
  if(12%i===0) {
    count++;
  }
}
console.log('The number of factors of 12 is ' + count);
Check whether a number is prime or not.

Prime numbers are those numbers which have only two factors i.e. 1 and the number itself. That means we need to check how many factors a given number has. If it has only two factors, it is a prime number. Otherwise, it is not. Let us take a number as input through prompt.

var x = +prompt('Enter a number');

The unary plus operator converts the input string into a number as explained earlier. Now, we need to check the number of factors as we did in the earlier example. If the count is 2, then it is a prime number, otherwise not.

var count = 0;
for(var i=1;i<=x;i++) {
  if(x%i===0) {
    count++;
  }
}
if(count===2) {
  console.log('It is a prime number');
}
else {
  console.log('It is not a prime number');
}
Print all the prime numbers between 1 and 50.

For this, we need to check each number between 1 and 50 whether it is a prime number or not. We need to print the number only if it is a prime number. So, we need two for loops: one for iterating from 1 to 50, another one to check whether it is a prime number or not.

for(var i=1;i<=50;i++) {
  var count = 0;
  for(var j=1;j<=i;j++) {
    if(i%j===0) {
      count++;
    }
  }
  if(count===2) {
    console.log(i);
  }
}
Print only the prime factors of 120.

For this example, we need to find the factors first. Then we need to check each factor whether it is a prime number or not.

var n = 120;
for(var i=1;i<=n;i++){
  if(n%i===0){
    var count = 0;
    for(var j=1;j<=i;j++){
      if(i%j===0) {
        count++;
      }
    }
    if(count===2){
      console.log(i);
    }
  }
}
Print the factorial of a given number.

To find the factorial of a number n, we need to find the product of all numbers from 1 to n. So, we need to loop through all numbers from 1 to the given number and find the product as follows:

var n = +prompt('Enter a number');
var fact = 1;
for(var i=1;i<=n;i++){
  fact = fact*i;
}
console.log(fact);

Print the reverse of a given number.

var n = 96321;
var s = 0;
var r;


while(n!=0){
	r = n%10;
	s = s*10+r;
	n = parseInt(n/10);
}		
console.log(s);