JavaScript. The for-in loop. nested loops. Eternal loop.

The for-in loop. Nested loops. Eternal loop.

This topic is a continuation of the topic:


Search other resources:

1. The for-in loop. Movement through objects

The for-in loop is used when it is necessary to iterate over a set of objects, which can be an array, a list, etc. The general form of using a for-in loop is as follows

for (var item in obj) {
  // Loop body
  // ...


  • item is a variable constituting the obj object. Such a component can be, for example, a property of an object. The item element receives a value in turn from the entire set of components of the obj object.

The for-in loop can be used to iterate over the elements of an array. In this case, the variable item gets the value of the array indexes. To directly access an array element, you need to use an index like


where Array – the name of array.


1.1. Example. Display all elements of the standard console object
// Loop for-in

// Display all elements of the console object
for (var t in console) {
  document.write(t + "<br>");




1.2. Display all elements of a user object

If you have developed your own (custom) object, then using the for-in loop, you can display all the elements of this object.

The example declares a Line class that describes a line on the coordinate plane. The following elements are declared in the class:

  • x1, y1, x2, y2 – coordinates of line points;
  • ShowLine() – a function that displays the current value of the line coordinates (the current state of the line);
  • Length() is a function that returns the length of the line.

Program text in JavaScript

// Loop for-in

// Task. Display all elements of an object of class Line.

// 1. Declaring the Line class
function Line(x1, y1, x2, y2) {
  this.x1 = x1
  this.y1 = y1
  this.x2 = x2
  this.y2 = y2

  // Function that prints the internal state of an object
  this.ShowLine = function() {
    document.write("x1 = " + this.x1 + ", y1 = " + this.y1 + "<br>");
    document.write("x2 = " + this.x2 + ", y2 = " + this.y2 + "<br>");

  // A function that returns the length of a line
  this.Length = function() {
    var len = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
    return len

// 2. Create object ln1
var ln1 = new Line(2.5, 3.8, 1.4, -0.3);

// 3. Demonstrate the methods of the ln1 object
document.write("ln1.Length = " + ln1.Length() + "<br>")

// 4. Display elements of ln1 object
document.write("<br>Object ln1:<br>")
for (var t in ln1)
  document.write(t + "<br>")


x1 = 2.5, y1 = 3.8
x2 = 1.4, y2 = -0.3
ln1.Length = 4.244997055358225

Object ln1:



1.3. Retrieve all elements of an array
// Loop for-in
// Task. Retrieve all elements of an array
// 1. Array of strings
var AS = [ "One", "Two", "Three" ];

// Loop for-in
for (var t in AS)

// 2. Array of numbers
var AI = [ 2.5, 3.8, 1.4, -0.8, 2 ]

document.write("Array AI: ")
for (var t in AI)
  document.write(AI[t]+" ")


Array AI: 2.5 3.8 1.4 -0.8 2


2. Nested loops

Loops can be nested. This means that one loop can contain another loop in its body. The nested loop can be any loop: for, while, do-while, for-in. In turn, any nested loop in its body can also contain a loop statement. Thus, the cyclic process is abstracted into several levels of nesting. The number of nestings of any of the loop operators is not limited and is determined by the algorithm for solving the problem.

2.1. Example. Nested loops for, while. The output of the multiplication table

Task. Print a 9 multiplication table for the numbers 1 to 5.


Below is a solution where the top loop is a for loop and the inner loop is a while loop.

// Nested loops

// Outer loop for
for (var i=1; i<=5; i++) {
  // Inner loop while
  var j = 1

  while (j<=9) {
    document.write(i + " * " + j + " = " + i*j + "<br>");


2.2. Example. Nested loops while, do-while. Defining properties of sets of numbers


Find all numbers between 1 and 300 that have exactly five divisors. To solve use:

  • while loop as an outer loop;
  • do-while loop as inner loop.


// Nested loops.
// Find all numbers from 1 to 300 that have exactly 5 divisors.

// Declare additional variables
var num = 1
var n, t

// Outer loop - numbers from 1 to 300
while (num <= 300) {

  n = 0 // number of divisors for num

  t = 1 // counter variable, needed to calculate the number of divisors
  do {
    // If t is a divisor of num, then increase the number of divisors
    if (num%t==0) n++;
  } while (t <= num)

  // At the exit from the do-while loop in the variable n - the number of divisors of the number num
  if (n==5)

  num++ // Get the next number




2.3. Finding the number of occurrences of a given word in a text

Task. The text is set. Determine how many times the given fragment occurs in the text.


In solving the problem, an outer do-while loop and an inner for loop were used.

// Nested loops
// Search for a given word in the text
// 1. Input text
var text = prompt("Input string:")

// 2. Enter the search word
var word = prompt("Input word:")

// 3. Declare additional variables
var count = 0; // Number of words in the text
var i, j
var f_find // a flag that indicates the match of a word in the text

i = 0
while (i<text.length) { // character-by-character text traversal

  // Accept that there is a match
  f_find = true

  for (j = 0; f_find && (j<word.length); j++) {
    // if a mismatch is found, exit the loop
    if (text[i+j]!=word[j]) f_find = false

  // Checking how the loop will end
  if (f_find) // if there are no mismatches
  count++ // then increase counter


// Display the result
alert("Number of occurences = " + count)


3. Eternal loop. Examples

If loops are programmed incorrectly, it may happen that the end condition of the loop process will never occur. In this case, the loop will be performed indefinitely. Such a loop is called an eternal loop.
For while, for, do-while loops, an eternal loop will mean that the value of the conditional expression that determines the execution of the next iteration will always be true.

Some of the most common cases where an eternal loop occurs can be the following:

  • incorrect increment of the counter, defined in the condition of the end of the loop process;
  • no increment of the counter specified in the loop termination condition;
  • erroneous determination of the result that determines the completion of the cyclic process;
  • other cases.


// Eternal loop

// 1. Loop while
var i=0;

while (i<5){
  // there is no increment of the counter i in the loop
  document.write("i = " + i + "<br>")

// 2. Loop for
for (var j=0; j<5; j--) {
  // counter j changes in the wrong direction
  document.write("j = " + j + "<br>")

// 3. Loop do-while
do {
} while (true) // stupid, but it's also an eternal loop


Related topics