Blog

  • User Defined Iterators

    In JavaScript, an iterable is an object which has Symbol.iterator() method in the object prototype. Some examples of iterable are array, set, map, string, etc. The Symbol.iterator() method returns an object containing the next() method is called iterator. Here, the next() method returns the elements of iterable in each call.

    The next() Method

    The next() method of the iterator object returns an object containing two key-value pairs given below.

    • value − The value key contains the element as a value.
    • done − The done key contains the boolean value. It contains true if all iterations of iterable are finished. Otherwise, it contains false.

    Example

    In the example below, we have created the array and stored the array iterator in the ‘iter’ variable. After that, we use the next() method of the iterator object to get the next value.

    The output shows that the next() method returns the object containing ‘value’ and ‘done’ properties. The last iteration returns the object containing the ‘done’ property only.

    <html><head><title> JavaScript - Iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");const nums =[10,72,45];const iter = nums[Symbol.iterator]();
    
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"value":10,"done":false}
    {"value":72,"done":false}
    {"value":45,"done":false}
    {"done":true}
    

    User-defined Iterators

    In the above part, we have looked at how an iterator works in JavaScript. The Symbol.iterator() method returns the object containing the next() method, and whenever we execute the next() method, it returns an object.

    So, in the same way, we can implement the user-defined iterators.

    Example

    In the example below, we have created the custom iterator using the function. The function returns the object containing the next() method. The next() method returns the object containing the array element and the false boolean value from the nth index if n is less than the array length. If the n is greater than or equal to the array's length, it returns the object containing only the 'done' property with a 'true' boolean value.

    After that, we use the iter.next() syntax to get the next array element.

    <html><head><title> JavaScript - User defined iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functioncustomIterator(chars){// To track indexlet n =0;return{// next() methodnext(){if(n < chars.length){return{
    
                     value: chars[n++],
                     done:false}}return{
                  done:true}}}}const chars =['A','C','E'];const iter =customIterator(chars);
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"value":"A","done":false}
    {"value":"C","done":false}
    {"value":"E","done":false}
    {"done":true}
    {"done":true}
    

    The above code uses the function to define the iterator. So, you can't use the forof loop with the iterator. Let's learn to define the iterator using the object in the example below.

    Example

    In the example below, we add a function as a value of the 'Symbol.iterator' key. The function returns the next() method. The next() method returns the odd numbers. If the value of the odd number is 9, it finishes the iteration by returning the {done: true} object.

    Here, we created the iterator using the object. So, you can use the forof loop. The loop will automatically execute the next() method of the iterator and returns a value of the 'value' property of the object returned by the next() method.

    <html><head><title> JavaScript - User defined iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");// Empty object
    
       oddNum ={};// Add iterator 
       oddNum[Symbol.iterator]=function(){let p =-1;
          done =false;return{next(){
                p +=2;if(p ==9)return{ done:true}return{ value: p, done: done };}};}for(const odd of oddNum){
          output.innerHTML += odd +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    1
    3
    5
    7
    

    You should create user-defined iterators when they need customization in the traversal of iterable. For example, to traverse alternative array elements, to get even or odd numbers from an iterator, etc.

  • Switch Case

    The JavaScript switch case is a conditional statement is used to execute different blocks of code depending on the value of an expression. The expression is evaluated, and if it matches the value of one of the case labels, the code block associated with that case is executed. If none of the case labels match the value of the expression, the code block associated with the default label is executed.

    You can use multiple if…elseif statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.

    Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements.

    Flow Chart

    The following flow chart explains a switch-case statement works.

    Switch case

    Syntax

    The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

    switch(expression){case condition 1:statement(s)break;case condition 2:statement(s)break;...case condition n:statement(s)break;default:statement(s)}
    • break − The statement keyword indicates the end of a particular case. If the ‘break’ statement were omitted, the interpreter would continue executing each statement in each of the following cases.
    • default − The default keyword is used to define the default expression. When any case doesn’t match the expression of the switch-case statement, it executes the default code block.

    Examples

    Let’s understand the switch case statement in details with the help of some examples.

    Example

    In the example below, we have a grade variable and use it as an expression of the switch case statement. The switch case statement is used to execute the different code blocks according to the value of the grade variable.

    For the grade ‘A’, it prints the ‘Good job’ in the output and terminates the switch case statement as we use the break statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let grade ='A';
    
      output.innerHTML +="Entering switch block &lt;br /&gt;";switch(grade){case'A': output.innerHTML +="Good job &lt;br /&gt;";break;case'B': output.innerHTML +="Passed &lt;br /&gt;";break;case'C': output.innerHTML +="Failed &lt;br /&gt;";break;default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Good job
    Exiting switch block
    

    Break statements play a major role in switch-case statements. Try the following example that uses switch-case statement without any break statement.

    Example: Without break Statement

    When we don't use the 'break' statement with any case of the switch case statement, it continues executing the next case without terminating it.

    In the below code, we haven't used the break statement with the case 'A' and 'B'. So, for the grade 'A', it will execute the statement of cases A, B, and C, and then it will terminate the execution of the switch case statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let grade ='A';
    
      output.innerHTML +="Entering switch block&lt;br /&gt;";switch(grade){case'A': output.innerHTML +="Good job &lt;br /&gt;";case'B': output.innerHTML +="Passed &lt;br /&gt;";case'C': output.innerHTML +="Failed &lt;br /&gt;";default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Good job
    Passed
    Failed
    Unknown grade
    Exiting switch block
    

    Example: Common Code Blocks

    Sometimes, developers require to execute the common code block for the multiple values of the expression. It is very similar to the OR condition in the if-else statement.

    In the below code, we execute the same code block for cases A and B, and C and D. You may try to change the value of the grade variables and observe the output.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var grade ='C';
    
      output.innerHTML +="Entering switch block &lt;br /&gt;";switch(grade){case'A':case'B': output.innerHTML +="Passed &lt;br /&gt;";break;case'C':case'D': output.innerHTML +="Failed! &lt;br /&gt;";break;default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Failed!
    Exiting switch block
    

    Example: Strict Comparison

    The switch case statement compares the expression value with the case value using the strict equality operator.

    The 'num' variable contains the integer value in the code below. In the switch case statement, all cases are in the string. So, the code executes the default statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let num =10;switch(num){case'10': output.innerHTML +="10 Marks!";break;case'11': output.innerHTML +="11 Marks!";break;default: output.innerHTML +="Input is not a string!";}</script></body></html>

    Output

    Input is not a string!
    
  • Continue Statement

    The continue statement in JavaScript is used to skip the current iteration of a loop and continue with the next iteration. It is often used in conjunction with an if statement to check for a condition and skip the iteration if the condition is met.

    The JavaScript continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

    Syntax

    The syntax of continue statement in JavaScript is as follows −

    continue;ORcontinue label;

    We can use the continue statement inside the loops like for loop, while loop, dowhile loop, etc.

    We will learn to use the continue statement with the label statement in the upcoming chapter.

    Continue statement with for loop

    The example below uses the continue statement with the for loop. In the loop, when the value of the x is 3, it will execute the continue statement to skip the current iteration and move to the next iteration.

    In the output, you can see that the loop doesnt print 3.

    Example

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;5; x++){if(x ==3){continue;// skip rest of the loop body}
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1
    2
    4
    Exiting the loop!
    

    Continue statement with while loop

    We used the while loop with the continue statement in the example below. In each iteration of the while loop, we increment the x's value by 1. If the value of the x is equal to 2 or 3, it skips the current iteration and moves to the next iteration.

    In the output, you can see that the code doesnt print 2 or 3.

    Example

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var x =1;
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";while(x &lt;5){
         x = x +1;if(x ==2|| x ==3){continue;// skip rest of the loop body}
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    4
    5
    Exiting the loop!
    

    Continue statement with the nested loop

    You can use the continue statement with nested loops and skip the iteration of the parent loop or child loop.

    Example

    The parent loop traverses the 1 to 5 elements in the code below. In the parent loop, we used the continue statement to skip the iteration when the value of x is 2 or 3. Also, we have defined the nested loop. In the nested loop, we skip the loop iteration when the value of y is 3.

    In the output, you can observe the value of x and y. You wont see 2 or 3 values for x and 3 for y.

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;5; x++){if(x ==2|| x ==3){continue;// skip rest of the loop body}for(let y =1; y &lt;5; y++){if(y ==3){continue;}
            output.innerHTML += x +" - "+ y +"&lt;br /&gt;";}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1 - 1
    1 - 2
    1 - 4
    4 - 1
    4 - 2
    4 - 4
    Exiting the loop!
    
  • Break Statement

    The break statement in JavaScript terminates the loop or switch case statement. When you use the break statement with the loop, the control flow jumps out of the loop and continues to execute the other code.

    The break statement can also be used to jump a labeled statement when used within that labeled statement. It is a useful tool for controlling the flow of execution in your JavaScript code.

    Syntax

    The syntax of break statement in JavaScript is as follows −

    break;ORbreak[label];

    The label is optional with a break statement.Note In the next chapter, we will learn to use the break statement with the label inside the loop.

    Flow Chart

    The flow chart of a break statement would look as follows −

    Break Statement

    Example (break statement with for loop)

    In the example below, we used the for loop to make iterations. We added the conditional expression in the loop using the ‘if’ statement. When the value of ‘x’ is 5, it will ‘break’ the loop using the break statement.

    The below code prints only 1 to 4 values in the output.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;10; x++){if(x ==5){break;// breaks out of loop completely}
            output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1
    2
    3
    4
    Exiting the loop!
    

    Example (break statement with the while loop)

    The code below demonstrates the while loop with the 'break' statement. In the while loop, whenever the value of x is either 3 or 7, it will terminate the loop using the 'break' statement.

    In the code, we update the value after checking the condition. So, it will print 3 first and then terminate the loop in the next iteration.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var x =1;
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";while(x &lt;10){if(x ==3|| x ==7){break;// breaks out of loop completely}
         x = x +1;
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    2
    3
    Exiting the loop!
    

    Break statement with nested loops

    You can use the 'break' statement to jump out of any loop when you have nested loops. For example, if you use the 'break' statement with the parent loop, the code will also terminate all iterations of the nested loop. Using the 'break' statement with the nested loop will terminate only the nested loop.

    Example

    In the example below, x is a looping variable for the parent loop, and y is a looping variable for a child loop.

    In the nested loop, whenever y becomes 3, it will break the loop; in the outer loop, whenever x becomes 3, it will break the loop. You won't see x > 3 or y > 2 in the output.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;10; x++){for(let y =1; y &lt;10; y++){if(y ==3){break;// breaks inner loop}
            output.innerHTML += x +" "+ y +"&lt;br /&gt;";}if(x ==3){break;// break outer loop}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1 1
    1 2
    2 1
    2 2
    3 1
    3 2
    Exiting the loop!
    

    Break statement with switch case statement

    The switch case statement executes one of the code blocks from multiple based on the conditional expression. The 'break' statement terminates the switch case statement after matching one or more cases with the conditional expression's value.

    Example

    In the below code, we used the 'break' statement with each case. Here, the value of variable p works as a conditional expression for the switch case statement. It matches with 'case 10'. So, the code will execute that particular code block and terminate the switch case statement using the 'break' statement.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");var p =10;switch(p){case10:
    
            output.innerHTML ="p is 10";break;case20:
            output.innerHTML ="p is 20";break;case30:
            output.innerHTML ="p is 30";break;default:
            output.innerHTML ="p is not 10, 20 or 30";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    p is 10
    

  • Loop Control

    JavaScript Loop Control

    JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.

    To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. Also, JavaScript allows developers to use labels to name the loop.

    We have explained the keywords in the below table, which can be used to control the loop.

    KeywordExplanation
    breakThe ‘break’ keyword is used to come out of the loop.
    continueThe ‘continue’ keyword is used to skip the current iteration of the loop.
    labelThe ‘label’ is not a keyword, but you can use any identifier followed by a colon (:) to give a label to the loop. After that, you can use the label to target the particular loop with the break and continue keyword.

    In the upcoming chapters, we will learn in detail about the break, continue and label statements.

    The break Statement

    The JavaScript break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

    Flow Chart

    The flow chart of a break statement would look as follows −

    Break Statement

    Example

    The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches −

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");let x =1;
    
      coutput.innerHTML ="Entering the loop&lt;br&gt; ";while(x &lt;20){if(x ==5){break;// breaks out of loop completely}
         x = x +1;
         coutput.innerHTML +=  x +"&lt;br&gt;";}         
      coutput.innerHTML +="Exiting the loop!&lt;br&gt; ";&lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop
    2
    3
    4
    5
    Exiting the loop!
    Set the variable to different value and then try...
    

    The continue Statement

    The JavaScript continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

    Example

    This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 −

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");let x =1;
    
      coutput.innerHTML ="Entering the loop&lt;br&gt; ";while(x &lt;10){
         x = x +1;if(x ==5){continue;// skip rest of the loop body}
         coutput.innerHTML +=  x +"&lt;br&gt;";}         
      coutput.innerHTML +="Exiting the loop!&lt;br&gt; ";&lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop
    2
    3
    4
    6
    7
    8
    9
    10
    Exiting the loop!
    Set the variable to different value and then try...
    

    Using Labels to Control the Flow

    Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.

    Line breaks are not allowed between the 'continue' or 'break' statement and its label name. Also, there should not be any other statement in between a label name and associated loop.

    Try the following two examples for a better understanding of Labels.

    Example 1

    The following example shows how to implement Label with a break statement.

    In the example below, we have given the 'outerloop' and 'innerloop' labels to the loop.

    We used the 'break' statement in the nested loop with the label. In the output, you can see that it breaks the outer loop from the inner loop.

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");
    
      output.innerHTML ="Entering the loop!&lt;br /&gt; ";
      outerloop:// This is the label name         for(let i =0; i &lt;5; i++){
         output.innerHTML +="Outerloop: "+ i +"&lt;br /&gt;";
         innerloop:for(let j =0; j &lt;5; j++){if(j &gt;3)break;// Quit the innermost loopif(i ==2)break innerloop;// Do the same thingif(i ==4)break outerloop;// Quit the outer loop
            output.innerHTML +="Innerloop: "+ j +" &lt;br /&gt;";}}        
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop!
    Outerloop: 0
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 1
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 2
    Outerloop: 3
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 4
    Exiting the loop!
    

    Example 2

    In the below code, we use the continue statement with a label inside the nested loop to skip the current iteration of the outer loop. Whenever the value of q becomes 3, it skips the execution of the remaining code of the current iteration and starts a new iteration.

    <html><head><title> JavaScript - Label statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop!&lt;br /&gt; ";
      outerloop:// This is the label namefor(let p =0; p &lt;3; p++){
         output.innerHTML +="Outerloop: "+ p +"&lt;br /&gt;";for(let q =0; q &lt;5; q++){if(q ==3){continue outerloop;}
            output.innerHTML +="Innerloop: "+ q +"&lt;br /&gt;";}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop!
    Outerloop: 0
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Outerloop: 1
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Outerloop: 2
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Exiting the loop!
    
  • For of Loop

    JavaScript for…of Loop

    The for…of loop in JavaScript is used to traverse elements of the iterable object. In each iteration, it gives an element of the iterable object. Iterable objects include arrays, strings, maps, sets, and generators.

    The JavaScript for…of loop is a much more efficient way to iterate over iterables than using a for…in loop. The for…of loop iterates over the property value while the for…in loop is used to iterate through the keys (property name) of an object.

    Syntax

    The syntax of ‘for…of’ loop in JavaScript in as follows −

    for(ele of iterable){// loop body}

    Parameters

    • ele − It is a current element of the iterable.
    • of − It is a JavaScript operator.
    • iterable − It is iterable like an object, array, string, etc.

    Examples

    Example: For…of Loop with Arrays

    In the example below, the array contains various strings. After that, we used the for…of loop to traverse each array element. In the output, we can see that it prints each array element.

    <html><head><title> JavaScript -for...of loop </title></head><body><p id="output"></p><script>const output = document.getElementById("output");const arr =["JavaScript","Python","C","C++","HTML","CSS"];for(let ele of arr){
    
            output.innerHTML += ele +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    JavaScript
    Python
    C
    C++
    HTML
    CSS
    

    Example: For...of Loop with Strings

    In JavaScript, the string is also iterable as we can traverse through each character of the string. In the below code, for...of loop is used to traverse through each character of the string.

    <html><head><title> JavaScript -for...of loop </title></head><body><p id="output"></p><script>const output = document.getElementById("output");let str ="JavaScript";for(let char of str){
    
            output.innerHTML += char +", ";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    J, a, v, a, S, c, r, i, p, t,
    

    Example: For...of Loop with Set

    In JavaScript, the set contains a unique element. Here, we have passed the array containing numbers as a parameter of the Set() constructor to create a set. After that, we used the for...of loop to traverse the set.

    <html><head><title> JavaScript -for...of loop </title></head><body><p id="output"></p><script>const output = document.getElementById("output");const nums =newSet([10,20,30,30,30,40,50,60]);for(let num of nums){
    
         output.innerHTML += num +", ";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    10, 20, 30, 40, 50, 60,
    

    Example: For...of Loop with Map

    The map contains the key-value pair in JavaScript and is similar to the object. Here, we created a map and inserted 3 key-value pairs in the map. When we use the for...of loop to traverse the map elements in each iteration, we can get the key and value shown in the code below.

    <html><body><p id="output"></p><script>const output = document.getElementById("output");const map =newMap();
    
      map.set("one",1);
      map.set("second",2);
      map.set("third",3)for(let[k, v]of map){
         output.innerHTML += k +" -&gt; "+ v +"&lt;br/&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    one -> 1
    second -> 2
    third -> 3
    

    However, you can also use the for...in loop to traverse the iterable like an array, string, map, set, etc.f

  • For in Loop

    The for…in Loop

    The for…in loop in JavaScript is used to loop through an object’s properties. The JavaScript for…in loop is a variant of the for loop. The for loop can’t be used to traverse through the object properties. So, the for…in loop is introduced to traverse through all object properties.

    As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.

    The for…in loop in JavaScript can also be used to iterate through the elements of an array. However, it is not recommended to do this as this is less efficient than using a for…of loop.

    Syntax

    The syntax of for…in loop in JavaScript is as follows −

    for(variableName in object){
       statement or block to execute
    }

    Parameters

    • variableName − It is a property name (key) of the object.
    • in − It is an ‘in’ operator in JavaScript.
    • object − It is the object to traverse.

    In each iteration, one property from object is assigned to variableName and this loop continues till all the properties of the object are exhausted.

    Examples

    Try the following examples to implement ‘for-in’ loop.

    Example: Iterate through object properties

    In the example below, the car object contains various properties. We used the forin loop to traverse through each key of the object.

    In the output, we can see that it prints the key and its value. We use the ‘[]’ (member of) operator to access the value of the key from the object.

    <html><head><title> JavaScript -for...in loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let car ={
    
         brand:"OD",
         model:"Q7",
         color:"Black",}for(key in car){
         output.innerHTML += key +" -&gt; "+ car[key]+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    brand -> OD
    model -> Q7
    color -> Black
    

    Example: Iterating over a string

    In JavaScript, the string is an object. So, we can use the forin loop to traverse through each character of the string. The index of the character is the key, and the character is a value.

    The code prints the index and character in the output.

    <html><head><title> JavaScript -for...in loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let str ="Hello";for(key in str){
    
         output.innerHTML += key +" -&gt; "+ str[key]+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    0 -> H
    1 -> e
    2 -> l
    3 -> l
    4 -> o
    

    Exampl: Iterating over an array

    In JavaScript, the array is also an object. So, the forin loop can be used to traverse through array elements. Like a string, the index is a key, and the array element is a value for the key.

    The below code prints the array index and its value in the output.

    <html><head><title> JavaScript -for...in loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let array =["Hi","Hello",900,23,true,"JavaScript"];for(key in array){
    
         output.innerHTML += key +" -&gt; "+ array[key]+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    0 -> Hi
    1 -> Hello
    2 -> 900
    3 -> 23
    4 -> true
    5 -> JavaScript
    

    Example: Update value of each property of an object

    In the example below, we traverse each key of the object and update its value to null. In the output, the code prints the object keys with null values.

    So, the forin loop can also be used to update all or particular property values of the object.

    <html><head><title> JavaScript -for...in loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let car ={
    
            brand:"OD",
            model:"Q7",
            color:"Black",}for(key in car){
            car[key]=null;}
        output.innerHTML +="The updated object is - "+JSON.stringify(car);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The updated object is - {"brand":null,"model":null,"color":null}
    

    Example: Iterating the Browser's Navigator Object

    Try the following example to implement 'for-in' loop. It prints the web browsers Navigator object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");var aProperty;
    
    output.innerHTML ="Navigator Object Properties&lt;br&gt; ";for(aProperty in navigator){
      output.innerHTML += aProperty;
      output.innerHTML +="&lt;br&gt;";}
    output.innerHTML +="Exiting from the loop!";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Navigator Object Properties
    vendorSub
    productSub
    vendor
    maxTouchPoints
    userActivation
    doNotTrack
    geolocation
    connection
    plugins
    mimeTypes
    pdfViewerEnabled
    webkitTemporaryStorage
    webkitPersistentStorage
    hardwareConcurrency
    cookieEnabled
    appCodeName
    appName
    appVersion
    platform
    product
    userAgent
    language
    languages
    onLine
    webdriver
    getBattery
    getGamepads
    javaEnabled
    sendBeacon
    vibrate
    scheduling
    bluetooth
    clipboard
    credentials
    keyboard
    managed
    mediaDevices
    storage
    serviceWorker
    wakeLock
    deviceMemory
    ink
    hid
    locks
    mediaCapabilities
    mediaSession
    permissions
    presentation
    serial
    virtualKeyboard
    usb
    xr
    userAgentData
    canShare
    share
    clearAppBadge
    setAppBadge
    getInstalledRelatedApps
    getUserMedia
    requestMIDIAccess
    requestMediaKeySystemAccess
    webkitGetUserMedia
    registerProtocolHandler
    unregisterProtocolHandler
    Exiting from the loop!
  • For Loop

    The JavaScript for loop is used to execute a block of code repeteatedly, until a specified condition evaluates to false. It can be used for iteration if the number of iteration is fixed and known.

    The JavaScript loops are used to execute the particular block of code repeatedly. The ‘for’ loop is the most compact form of looping. It includes the following three important parts

    • Initialization − The loop initialization expression is where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
    • Condition − The condition expression which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed. Otherwise, the control will come out of the loop.
    • Iteration − The iteration expression is where you can increase or decrease your counter.

    You can put all the three parts in a single line separated by semicolons.

    Flow Chart

    The flow chart of a for loop in JavaScript would be as follows −

    For Loop

    Syntax

    The syntax of for loop is JavaScript is as follows −

    for(initialization; condition; iteration){Statement(s) to be executed if condition is true}

    Above all 3 statements are optional.

    Examples

    Try the following examples to learn how a for loop works in JavaScript.

    Example: Executing a code block repeatedly

    In the example below, we used the for loop to print the output’s updated value of the ‘count’ variable. In each iteration of the loop, we increment the value of ‘count’ by 1 and print in the output.

    <html><head><title> JavaScript -for loop </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");
    
        output.innerHTML ="Starting Loop &lt;br&gt;";let count;for(let count =0; count &lt;10; count++){
            output.innerHTML +="Current Count : "+ count +"&lt;br/&gt;";}
        output.innerHTML +="Loop stopped!";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Starting Loop
    Current Count : 0
    Current Count : 1
    Current Count : 2
    Current Count : 3
    Current Count : 4
    Current Count : 5
    Current Count : 6
    Current Count : 7
    Current Count : 8
    Current Count : 9
    Loop stopped!
    

    Example: Initialization is optional

    The below code demonstrates that the first statement is optional in the for loop. You can also initialize the variable outside the loop and use it with the loop.

    Whenever you need to use the looping variable, even after the execution of the loop is completed, you can initialize a variable in the parent scope of the loop, as we have done in the below code. We also print the value of p outside the loop.

    <html><head><title> Initialization is optional infor loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var p =0;for(; p <5; p++){
    
            output.innerHTML +="P -&gt; "+ p +"&lt;br/&gt;";}
        output.innerHTML +="Outside the loop! &lt;br&gt;";
        output.innerHTML +="P -&gt; "+ p +"&lt;br/&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    P -> 0
    P -> 1
    P -> 2
    P -> 3
    P -> 4
    Outside the loop!
    P -> 5
    

    Example: Conditional statement is optional

    The below code demonstrates that the conditional statement in the for loop is optional. However, if you don't write any condition, it will make infinite iterations. So, you can use the 'break' keyword with the for loop to stop the execution of the loop, as we have done in the below code.

    <html><head><title> Conditional statement is optional infor loop </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let arr =[10,3,76,23,890,123,54]var p =0;for(;; p++){if(p >= arr.length){break;}
    
            output.innerHTML +="arr["+ p +"] -&gt; "+ arr[p]+"&lt;br/&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    arr[0] -> 10
    arr[1] -> 3
    arr[2] -> 76
    arr[3] -> 23
    arr[4] -> 890
    arr[5] -> 123
    arr[6] -> 54
    

    Example: Iteration statement is optional

    In the for loop, the third statement is also optional and is used to increment the iterative variable. The alternative solution is that we can update the iterative variable inside the loop body.

    <html><head><title> Iteration statement is optional </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");let str ="Tutorialspoint";var p =0;for(;;){if(p >= str.length){break;}
    
            output.innerHTML +="str["+ p +"]  -&gt; "+ str[p]+"&lt;br/&gt;";
            p++;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    str[0] -> T
    str[1] -> u
    str[2] -> t
    str[3] -> o
    str[4] -> r
    str[5] -> i
    str[6] -> a
    str[7] -> l
    str[8] -> s
    str[9] -> p
    str[10] -> o
    str[11] -> i
    str[12] -> n
    str[13] -> t
    

  • While Loops

    while statement in JavaScript creates a loop that executes a block of code repeatedly, as long as the specified condition is true. The condition is evaluated before the execution of the block of code.

    While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.

    JavaScript supports all the necessary loops to ease the pressure of programming. In this chapter, we will discuss the while loop.

    There are 2 kinds of while loops in JavaScript, as given below.

    • Entry-controlled loops − The loop checks whether the looping condition is valid first and enters into the body of the loop to execute the loop statements.
    • Exit-controlled loops − The loop enters into the body and executes the loop statements without checking the condition. After completing the iteration, it checks the condition.

    JavaScript while Loop

    The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The while loop is an entry-controlled loop.

    The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.

    Flow Chart

    The flow chart of while loop looks as follows −

    While loop

    Syntax

    The syntax of while loop in JavaScript is as follows −

    while(expression){Statement(s) to be executed if expression is true}

    Example

    In the example below, we defined the ‘count’ variable and initialized it with 0. After that, we make iterations using the while loop until the value of the count is less than 10.

    <html><body><div id ='output'></div><script type="text/javascript">let output = document.getElementById("output");var count =0;
    
        output.innerHTML="Starting Loop &lt;br&gt;";while(count &lt;10){
            output.innerHTML+="Current Count : "+ count +"&lt;br&gt;";
            count++;}
        output.innerHTML+="Loop stopped!";&lt;/script&gt;&lt;p&gt; Set the variable to a different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Starting Loop
    Current Count : 0
    Current Count : 1
    Current Count : 2
    Current Count : 3
    Current Count : 4
    Current Count : 5
    Current Count : 6
    Current Count : 7
    Current Count : 8
    Current Count : 9
    Loop stopped!
    Set the variable to different value and then try... 
    

    JavaScript do...while Loop

    The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

    Flow Chart

    The flow chart of a do-while loop would be as follows −

    Do While Loop

    Syntax

    The syntax for do-while loop in JavaScript is as follows −

    do {
       Statement(s) to be executed;
    } while (expression);
    

    Don't miss the semicolon used at the end of the do...while loop.

    Example

    In the example below, we used the do...while loop and printed the results in the output until the value of the count variable is less than 5. In the output, we can observe that it always executes for once, even if the condition is false.

    <html><body><div id="output"></div><script type="text/javascript">let output = document.getElementById("output");var count =0;
    
        output.innerHTML +="Starting Loop"+"&lt;br /&gt;";do{
            output.innerHTML +="Current Count : "+ count +"&lt;br /&gt;";
            count++;}while(count &lt;5);
        output.innerHTML +="Loop stopped!";&lt;/script&gt;&lt;p&gt;Set the variable to a different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Starting Loop
    Current Count : 0 
    Current Count : 1 
    Current Count : 2 
    Current Count : 3 
    Current Count : 4
    Loop Stopped!
    Set the variable to different value and then try...
    

    JavaScript while vs. for Loops

    The JavaScript while loop is similar to the for loop with the first and third expressions omitted. A for loop is generally used when the number of iteration is fixed and known but we use the while loop whne the number of iterations is not known.

    Example

    Let's take an example of printing the first five natural numbers using for loop −

    <html><body><p> First five natural numbers:</p><div id ="demo"></div><script>const output = document.getElementById("demo");for(let i =1; i <=5; i++){
    
      output.innerHTML += i +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following output −

    First five natural numbers:
    1
    2
    3
    4
    5
    

    Example

    We can now modify the above for loop as follows −

    <html><body><p> First five natural numbers:</p><div id ="demo"></div><script>const output = document.getElementById("demo");let i =1;for(; i <=5;){
    
      output.innerHTML += i +"&lt;br&gt;";
      i++}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    First five natural numbers:
    
    1
    2
    3
    4
    5
    

    Example

    In the above example, we have omitted first and third expression in for loop statement. This is similar to the while loop statement. Look at the below example −

    <html><body><p> First five natural numbers:</p><div id ="demo"></div><script>const output = document.getElementById("demo");let i =1;while(i <=5){
    
      output.innerHTML += i +"&lt;br&gt;";
      i++}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    First five natural numbers:
    
    1
    2
    3
    4
    5
    

    You notice that the for loop without first expression (initialization) and third expression (iteration), is similar to the while loop.

  • Python Privacy Policy

    1. Introduction

    Welcome to Learn Python Programming This Privacy Policy explains how we collect, use, and protect your information when you use our application.

    2. Information We Collect

    We do not collect personally identifiable information (such as name, email, phone number) directly from users.

    However, our app uses third-party services (such as Unity Ads and Google Play Services) which may collect data automatically for analytics, personalization, and advertising purposes. This may include:

    • Device information
    • IP address
    • Usage statistics
    • Ad interactions

    3. How We Use Information

    The information collected is used to:

    • Provide and improve the app experience
    • Show relevant ads using Unity Ads
    • Monitor performance and fix issues
    • Ensure compliance with Play Store policies

    4. Third-Party Services

    Our app uses third-party services that may collect information to identify you. These include:

    • Unity Ads (for monetization and personalized ads)
    • Google Play Services (for app distribution and analytics)

    5. Data Security

    We take appropriate measures to protect your information. However, please note that no method of transmission over the internet or method of electronic storage is 100% secure.

    6. Children’s Privacy

    Our app is intended for a general audience and does not knowingly collect personal data from children under 13. If you believe we have collected such data, please contact us and we will take steps to delete it.

    7. Your Choices

    You may limit personalized advertising through your device settings. For example, you can reset your advertising ID or opt out of interest-based ads.

    8. Changes to This Policy

    We may update this Privacy Policy from time to time. Any changes will be posted within the app with an updated effective date.

    9. Contact Us

    If you have any questions or concerns about this Privacy Policy, you can contact us at:

    📧 Email: [email protected]