Loops in JavaScript

A loop in JavaScript is a programming construct that allows you to execute a block of code repeatedly as long as a specified condition is true.
It's a fundamental tool for automating repetitive tasks and iterating over data structure like arrays or objects.

  • Key aspects of loops:
  • Iteration : Understanding how loops iterate over a set of instructions until a specific condition is met.
    Loop Control Statements : Knowing how to control the flow of loops using statements like break and continue.
    Loop termination : Identifying the conditions that determine when a loop should stop executing.
    Loop optimization : Learning techniques to optimize loop performance, such as minimizing unnecessary computations within the loop body.

  • Types of Loops :
  • 1. for loop
    2. while loop
    3. do-while loop
    4. for...in loop
    5. for...of loop

  • For loop :
  • A for loop in used to execute a block of code repeatedly for a specified number of times.
    Its syatax consists of three optional expressions enclosed in parentheses: initialization, condition, and increment/decrement.
    Anatomy of a for Loop :
    for(initialization; condition; increment/decrement)
    {
      //code block to be executed
    }

    Initialization : Declares and initializes the loop variable.
    Condition : Specifies when the loop should continue executing.
    Increment/Decrement : Modifies the loop variable after each iteration.

    Example :
    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> for(i=0; i<5; i++) { document.write(i); } </script> </body> </html>
    In this example :
    • i=0; initialize the loop variable i to 0.
    • i < 5; specifies the condition. The loop will continue as long as i is less than 5.
    • i++ is the increment expression, which increases the value of i by 1 after each iteration
    JavaScript code
    # Write a program to find the factorial of a number. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <!DOCTYPE html> <html> <script type="text/javascript"> var n=parseInt(prompt("Enter a Number : ")); var f=1; for(i=1;i<=n;i++) { f=f*i; } document.write("Factorial="+f); </script> </html> </body> </html>

    Output :
    Enter a Number : 5
    Factorial=120

    JavaScript code
    # Write a program to calculate and print the sum of odd numbers and sum of even numbers. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> n=10;s1=0;s2=0; for(i=1;i<=n;i++) { if(i%2==0) s1=s1+i; else s2=s2+i; } document.write("Sum of Even Numbers="+s1); document.write("Sum of Odd Numbers="+s2); </script> </body> </html>

    Output :
    Sum of Even Numbers=30
    Sum of Odd Numbers=25

    JavaScript code
    # Write a program to accept a number from the user and check whether it is prime or not. Prime number is a number that is greater than 1 and divided by 1 or itself. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var a,c=0; a=parseInt(prompt("Enter a Number : ")); for(i=1;i<=a;i++) { if(a%i==0) c++; } if(c==2) document.write("Prime"); else document.write("Not prime"); </script> </body> </html>

    Output :
    Enter a Number : 5
    Prime
    Enter a Number : 4
    Not prime

  • While Loop
  • A while loop repeatedly executes a block of code as long as a specified condition evaluates to true.
    Its syntax consists of the while keyword followed by a condition enclosed in parentheses, and the code block to be executed enclosed in curly braces.
    Anatomy of a While Loop :
    while (condition) {
    // code block to be executed
    }

    Condition: Specifies when the loop should continue executing.
    Example :

    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var i = 0; while (i < 5) { document.write(i); i++; } </script> </body> </html>
    In this example :
    • i = 0; initializes the loop variable i to 0.
    • i < 5; is the condition. The loop will continue as long as i is less than 5.
    • i++; increments the value of i by 1 after each iteration to prevent an infinite loop.
    JavaScript code
    # Write a program to accept a number and display the Sum of its digits. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var n=parseInt(prompt("Enter a number")); var g=0; while(n>0) { r=parseInt(n%10); g=g+r; n=parseInt(n/10); } document.write("Sum of digit="+g); </script> </body> </html>

    Output :
    Enter a number : 123
    Sum of digit=6

    JavaScript code
    # Write a program to accept a number from user and check whether its Palindrome or not. A palindrome number is a number that is same after reverse. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var a=parseInt(prompt("Enter a number :")); var s=0; t=a; while(a>0) { r=parseInt (a%10); s=s*10+r; a=parseInt (a/10); } if(s==t) document.write("Palindrome"); else document.write("not Palindrome"); </script> </body> </html>

    Output :
    Enter a number : 121
    Palindrome
    Enter a number : 124
    not Palindrome

  • Do while Loop
  • A do-while loop is similar to a while loop, but with one key difference: it always executes the code block at least once before checking the condition.
    Its syntax starts with the do keyword, followed by the code block enclosed in curly braces, and ends with the while keyword followed by the condition in parentheses.
    Anatomy of a do-while loop :
    do {
    // code block to be executed
    } while (condition);

    Condition : Checked after each iteration.
    Example :

    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var i = 0; do { document.write(i); i++; } while (i < 5); </script> </body> </html>
    In this example:
    • i = 0; initializes the loop variable i to 0.
    • The code block within the do and while loop will be executed at least once.
    • i < 5; is the condition. After executing the code block, the loop will continue as long as i is less than 5.

  • for...in loop :
  • The for...in loop is used to iterate over the enumerable properties of an object.
    Anatomy of for...in loop :
    for(variable in object){
    // code to be executed
    }

    Example :

    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> const Person = { name: "Rokeiya", class: 12 }; // loop through the keys of student object for (let key in Person) { // display the key-value pairs document.write(`${key} => ${Person[key]}`); }; </script> </body> </html>

    Output :
    name => Rokeiyaclass => 12

  • For..of loop :
  • The for...of loop in JavaScript is designed for iterating over iterable objects, such as arrays, strings, maps, sets, and more. It provides a simpler and more readable way to loop through elements, especially when compared to a traditional for loop or forEach method.

    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> const fruits = ['Apple', 'Banana', 'Cherry']; for (const fruit of fruits) { document.write(fruit+"<br>"); } </script> </body> </html>

    Output :
    Apple
    Banana
    Cherry

  • Benefits of Looping:
  • Readability: Python's loop constructs are designed for readability, making code easy to understand and maintain. The explicit nature of loops enhances code clarity, especially when dealing with repetitive tasks.
    Flexibility: Loops provide flexibility in handling different data structures and scenarios. Whether you're iterating over a collection of integers, strings, or complex objects, Python's loop constructs adapt effortlessly.
    Efficiency: Iteration with loops is often more efficient than manual iteration, as Python's built-in iteration mechanisms are optimized for performance. This efficiency is particularly evident when working with large datasets or complex data structures.

  • Key Points :
  • Loops can be used with break and continue statements to control the flow of iterations.
  • break exits the loop immediately.
  • continue skips the current iteration and moves to the next.
  • Choose the appropriate loop type (for or while) based on your needs.
  • Be mindful of infinite loops by ensuring the condition in while loops eventually becomes False.
  • Practice Exercises :
  • 1. Write a program that asks the user for a positive number and prints the sum of all numbers from 1 to that number (inclusive).
    2. Write a program to accept a number and check number is Perfect or not. A number is called perfect if it is equal to the sum of its factor other than the number itself. Example: 6= 1 + 2 + 3

  • conclusion :
  • Each type of loop has its use cases and benefits, and choosing the right one depends on the specific requirements of your task. Loops are fundamental to JavaScript programming and are widely used in various applications, from web development to backend server scripting.