Blog

  • 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]

  • if else Statement

    The JavaScript if…else statement executes a block of code when the specified condition is true. When the condition is false the else block will be executed. The if-else statements can be used to control the flow of execution of a program based on different conditions.

    While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform the right actions.

    JavaScript supports conditional statements used to perform different actions based on different conditions. Here we will explain the if…else statement.

    Flow Chart of if-else

    The following flow chart shows how the if-else statement works.

    Decision Making

    JavaScript supports the following forms of if…else statement −

    • if statement
    • if…else statement
    • if…else if… statement.

    JavaScript if statement

    The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

    Syntax

    The syntax for a basic if statement is as follows −

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

    Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.

    Example

    Try the following example to understand how the if statement works.

    <html><body><div id ='output'></div><script type ="text/javascript">let result;let age =20;if( age >18){
    
         result ="Qualifies for driving";}
    document.getElementById("output").innerHTML = result;</script><p> Set the variable to a different value and then try...</p></body></html>

    Output

    Qualifies for driving
    Set the variable to different value and then try...
    

    JavaScript if…else statement

    The ‘if…else’ statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

    Syntax

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

    Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the if block, are executed. If the expression is false, then the given statement(s) in the else block are executed.

    Example

    Try the following code to learn how to implement an if-else statement in JavaScript.

    <html><body><div id ='output'></div><script type ="text/javascript">let result;let age =15;if( age >18){
    
         result ="Qualifies for driving";}else{
         result ="Does not qualify for driving";}
      document.getElementById("output").innerHTML = result;&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

    Does not qualify for driving
    Set the variable to different value and then try...
    

    JavaScript if...else if... statement

    The if...else if... statement (also called as if...else ladder)is an advanced form of ifelse that allows JavaScript to make a correct decision out of several conditions.

    Syntax

    The syntax of an if-else-if statement is as follows −

    if(expression 1){Statement(s) to be executed if expression 1 is true}elseif(expression 2){Statement(s) to be executed if expression 2 is true}elseif(expression 3){Statement(s) to be executed if expression 3 is true}else{Statement(s) to be executed if no expression is true}

    There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.

    Example

    Try the following code to learn how to implement an if-else-if statement in JavaScript.

    <html><body><div id ="demo"></div><script type="text/javascript">const output = document.getElementById("demo")let book ="maths";if(book =="history"){
    
         output.innerHTML="&lt;b&gt;History Book&lt;/b&gt;";}elseif(book =="maths"){
         output.innerHTML="&lt;b&gt;Maths Book&lt;/b&gt;";}elseif(book =="economics"){
         output.innerHTML="&lt;b&gt;Economics Book&lt;/b&gt;";}else{
         output.innerHTML="&lt;b&gt;Unknown Book&lt;/b&gt;";}&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

    Maths Book
    Set the variable to different value and then try...

  • Operator Precedence

    In JavaScript, operator precedence ensures the priority of the operators to be executed when a single expression contains multiple operators. So, whatever expressions have higher priority, the compiler executes it first over other operators and then executes the operators with the lower precedence.

    Whenever you write any JavaScript expression with only 1 or 2 operators, you can easily understand the output of the expression. But when the expression contains multiple operators, you should know the concept of operator precedence to evaluate the expression correctly.

    The best example of operator precedence is that in traditional mathematics, the multiplication operator has higher precedence over the addition or subtraction operator. So, if any mathematical expression contains the multiplication and addition of both operators, you need to perform the multiplication first.

    Associativity

    The term associativity refers to the direction compiler should follow while evaluating the expression. In many situations, operators have the same precedence. In such cases, ambiguity occurs that which operation the compiler should perform first. So, the compiler takes the help of associativity. It can be from left to right or right to left.

    For example, we need to execute the below expression.

    let res =50/5*2;
    • Considering the above expression as (50/5) * 2 gives 20 as an output.
    • Evaluating the expression like 50/ (5*2) gives the 5 as a resultant value.

    To resolve the above ambiguity, the compiler uses the associativity rule. The associativity for the division and multiplication operator is from left to right. So, it evaluates the expression as (50 / 5) * 2.

    The assignment operator has right-to-left associativity. Consider the below assignment expression.

    P= q =90;

    In the above expression, 90 is assigned to the q, and the value of the q variable is assigned to the p.

    In short, the JavaScript compiler evaluates the expression based on the operator precedence, and when multiple operators have the same precedence, it uses the associativity rule.

    Operator Precedence Table

    The below table contains the operator, its description, associativity direction, and a short example.

    Operator PrecedenceOperatorDescriptionAssociativityExample
    1()GroupingL -> R(expression)
    2.Member of objectL -> RObject_name.property
    2()Function callL -> RDemo()
    2newTo create objectsR -> LNew test()
    2[]Member of objectL -> RObject[“property”]
    3Postfix decrementp–;
    3++Postfix incrementp++
    4Prefix decrementR -> L–p;
    4++Prefix incrementR -> L++p;
    4typeofTo get the variable typeR -> Ltypeof a;
    4!Logical notR -> L!a;
    4~Bitwise notR -> L~p
    4Unary minusR -> L-p
    4+Unary plusR -> L+p
    4deleteTo delete object propertyR -> LDelete arr[0]
    4voidEvaluates voidR -> LVoid(1)
    5**Exponentiation operatorR -> Lp ** q
    6*MultiplicationL -> Rp * q
    6/DivisionL -> Rp / q
    6%moduloL -> Rp % q
    7+Addition or plus operatorL -> Rp + q
    7Subtraction operatorL -> Rp – q
    8<<Left shiftL -> Rp << 2
    8>>Signed right shiftL -> Rp >> 2
    8>>>Unsigned right shiftL -> Rp >>> 2
    9inProperty in objectL -> Rx in y
    9instanceofInstance of objectL -> Rp instanceof Object
    9<Less thanL -> Rp < q
    9<=Less than or equal toL -> Rp <= q
    9>Greater thanL -> Rp > q
    9>=Greater than or equal toL -> Rp >= q
    10==EqualityL -> Rp == q
    10!=InequalityL -> Rp != q
    10===Strict equalityL -> Rp === q
    10!==Strict inequalityL -> Rp !== q
    11&Bitwise ANDL -> Rp & q
    12^Bitwise XORL -> Rp ^ q
    13|Bitwise ORL -> Rp | q
    14&&Logical ANDL -> Rp && q
    15||Logical ORL -> Rp || q
    16??Nullish CoalescingR -> Lp ?? q
    17=AssignmentR -> Lp = q
    17:Colon assignmentR -> Lp : q
    17+=Addition assignmentR -> Lp += q
    17-=Subtraction assignmentR -> Lp -= q
    17*=Multiplication assignmentR -> Lp *= q
    17/=Division assignmentR -> Lp /= q
    17%=Modulo assignmentR -> Lp %= q
    17**=Exponentiation assignmentR -> Lp **= q
    17<<=Left shift assignementR -> Lp <<= q
    17>>=Right shift assignmentR -> Lp >>= q
    17>>>=Unsigned right shift assignmentR -> Lp >>>= q
    17&=Bitwise AND assignmentR -> Lp &= q
    17^=Bitwise XOR assignmentR -> Lp ^= q
    17|=Bitwise OR assignmentR -> Lp |= q
    17&&=Logical AND assignmentR -> Lp &&= q
    17||=Logical OR assignementR -> Lp ||= q
    17=>Arrow operator(a, b )=> { // function code}
    17Spread operator[ arr]
    18yieldPause / ResumeR -> Lyield p;
    19,Comma operatorL -> R(10, 20, 30)

    Examples

    Let’s understand the operator precedence via simple examples.

    Example

    In the example below, the first expression contains the division, modulo, and multiplication operators with the same precedence. So, the compiler will use the associativity rule, which is left to right for multiplication, division, and modulo operator.

    So, it divides the 30 by 15, takes modulo of (30/15) with 3, and multiples the ((30/15)%3) with 2.

    In the second expression, the exponentiation operator has right-to-left associativity. So, it evaluates the expression same as (2 *8 (3 ** 2)).

    <html><body><div id ="output"></div><script>const first =30/15%3*2;const second =2**3**2;
    
         document.getElementById("output").innerHTML ="The value of first expression is : "+ first +"&lt;br&gt;"+"The value of second expression is : "+ second;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    It will produce the following result −

    The value of first expression is : 4
    The value of second expression is : 512
    

    Example

    This code demonstrates that you can use the grouping operator () to change the operator precedence. In the below code, we have taken the same expressions which we have taken in the above code, but we change the operator precedence.

    In the first expression, first, we take modulo and multiply the resultant value with 2. So, we get 0 and divide 30 by 0, returning infinity.

    In the second expression, the first expression evaluates the (2 ** 3) and (8 ** 2), which is equal to 64.

    <html><body><div id ="output"></div><script>const first =30/((15%3)*2);const second =(2**3)**2;
    
         document.getElementById("output").innerHTML ="The value of first expression is : "+ first +"&lt;br&gt;"+"The value of second expression is : "+ second;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of first expression is : Infinity
    The value of second expression is : 64
    

    The grouping operator can change operator precedence for any operator as it has the highest operator precedence.

  • Exponentiation Operator

    Exponentiation Operator

    The exponentiation operator in JavaScript is represented as **. The exponentiation operator takes two operands and returns the power of the first operand raised to the second.

    The exponentiation operator can also accept the variables of the BigInt data type as operands. Also, it follows the property of associativity, which means a**b**c and a**(b**c) expressions give the same result.

    The exponentiation operator evaluates the expression from right to left.

    Syntax

    We should follow the syntax below to use the exponentiation operator.

    let pow = x ** y;

    Return value

    It returns the result of raising the first operand (x) to the power of the second operand (y).

    Examples

    Let’s understand the exponentiation operator in details with the help of some examples.

    Example

    The example below defines the p and q variables containing the 2 and 3 values. After that, we used the exponentiation operator to get the PQ. In the output, you can observe the value of the ‘pow’ variable, which is 23, equal to 8.

    <html><body><div id ="output"></div><script>let p =2;let q =3;let pow = p ** q;
    
      document.getElementById("output").innerHTML ="The value of p ** q: "+ pow;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    The value of p ** q: 8
    

    Example: Associativity of Exponentiation Operator

    This example demonstrates that the exponentiation operator follows the associativity property and evaluates the expression from right to left.

    Both expressions print the 6561 in the output, equal to the 38, where 8 equals the 23.

    <html><body><div id="output"></div><script>let p =3;let q =2;let r =3;let pow1 = p ** q ** r;let pow2 = p **(q ** r);
    
    
      document.getElementById("output").innerHTML ="pow1 = "+ pow1 +"&lt;br&gt;"+"pow2 = "+ pow2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    pow1 = 6561
    pow2 = 6561
    

    Example: Exponentiation operator with BigInt variables

    The below example demonstrates that the exponentiation operator can also be used with the bigint numbers. It returns the bigint value in the output.

    <html><body><div id ="output"></div><script>let p =10000000000000000000000000000n;let q =2n;let pow = p ** q;
    
      document.getElementById("output").innerHTML ="pow = "+ pow;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    pow = 100000000000000000000000000000000000000000000000000000000
    

    Example: Exponentiation operator with non-numeric values

    When you use the non-numeric value as an operand of the exponentiation operator, it converts the value to numeric and returns the result. If the operand can't be converted to the numeric value, it returns NaN in the output.

    Here, it converts the '[]' to 0 and gives the correct result. The numeric value for the string '2a' is NaN, so it prints the NaN in the output. If the array contains a single numeric element, it parses the element. Otherwise, it evaluates NaN if the array contains multiple elements.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");let pow =2**[];// Number([]) = 0
    
      output .innerHTML ="10 ** [] = "+ pow +"&lt;br&gt;";
      pow =[]**2;// Number([]) = 0
      output.innerHTML +="[] ** 2 = "+ pow +"&lt;br&gt;";
      pow =2**[2];// Number([2]) = 2    
      output.innerHTML +="10 ** [2] = "+ pow +"&lt;br&gt;";
      pow ="2"**2;// Number("2") = 2
      output.innerHTML +="2 ** 2 = "+ pow +"&lt;br&gt;";
      pow ="2a"**2;// Number("2a") = NaN
      output.innerHTML +="2a ** 2 = "+ pow +"&lt;br&gt;";
      pow =[2,3]**2;// Number([2, 3]) = NaN
      output.innerHTML +="[2, 3] ** 2 = "+ pow +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10 ** [] = 1
    [] ** 2 = 0
    10 ** [2] = 4
    2 ** 2 = 4
    2a ** 2 = NaN
    [2, 3] ** 2 = NaN
    

    The exponentiation operator is an alternative to the pow() method of the Math() object.

  • Spread Operator

    What is a Spread Operator?

    The JavaScript spread operator () allows us to spread out elements of an iterable such as an array. The spread operator is represented with three dots (). This is operator is introduced in ES6. The main use cases of the spread operator are to copy array elements, concatenate arrays or objects with rest parameters, etc.

    Let’s take an example to expand the elements of an array

    let x =["Tutorials","Point"];
    console.log(x);// [ 'Tutorials', 'Point' ]
    console.log(...x);// Tutorials Point

    Spread Operator to Concatenate Arrays

    The JavaScript spread operator can be used to concatenate the arrays.

    Example

    In the below example, we have defined two different arrays. After that, we used the spread operator to concatenate these arrays.

    <html><body><div id ="output"></div><script>const nums1 =[10,20,30];const nums2 =[40,50,60];const res =[...nums1,...nums2];
    
      document.getElementById("output").innerHTML = res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30,40,50,60
    

    You can also change the concatenation order of the array.

    Spread Operator to Clone an Array

    In JavaScript, when we assign one array (object) to another array, it assigns the reference rather than cloning the array. So, whenever you update the original array, it also updates the cloned array. The assignement operator creates a deep copy of the array.

    Example: Without Using Spread Operator

    In this example, we defined an array named nums1. We defiend another array named nums2 and assigned the array nums1 to array nums2. Here, you can see that when you change nums1, it also updates the nums2.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const nums1 =[10,20,30];const nums2 = nums1;
    
      document.getElementById("result1").innerHTML = nums2;
      nums1.push(40);
      document.getElementById("result2").innerHTML = nums2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30
    10,20,30,40
    

    Example: Using Spread Operator to Clone Arrays

    Using the spread operator to clone the array creates an actual copy of the array, and the cloned array doesn't change when you make changes to the original array. Here, you can see that nums3 doesn't get updated even if you change the nums1.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const nums1 =[10,20,30];const nums3 =[...nums1];
    
      document.getElementById("result1").innerHTML = nums3;
      nums1.push(50);
      document.getElementById("result2").innerHTML = nums1 +"&lt;br&gt;";
      document.getElementById("result2").innerHTML += nums3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30
    10,20,30,50
    10,20,30
    

    Spread Operator to Concatenate Objects

    You can use the spread operator to copy object properties into another object. Here, consider the 'car' object as a parent object containing similar properties to all cars. After that, created the 'BMW' object, representing the particular car, and concatenated all properties of the 'car' object with the 'BMW' object's property.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const car ={
    
         gears:6,
         color:"Black"}
      document.getElementById("result1").innerHTML =JSON.stringify(car);constBMW={
         model:"X5",
         year:2019,...car,}
      document.getElementById("result2").innerHTML =JSON.stringify(BMW);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    {"gears":6,"color":"Black"}
    {"model":"X5","year":2019,"gears":6,"color":"Black"}
    

    Function Rest Parameters

    When you need to pass an unknown number of arguments to the function, you can use the spread operator with the function parameters, called the rest parameter.

    Here, you can see that we have passed multiple numbers as a function argument and collected all arguments in the nums[] array using the spread operator except the first argument.

    <html><body><div id ="result"></div><script>functionsum(a, ...nums){let sum = a;for(let i =0; i < nums.length; i++){
    
            sum += nums[i];}
         document.getElementById("result").innerHTML = sum;}sum(3,6,9,8,6,5,3,3,2,1);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    46
    

    You can also use the spread operator to expand the string into the array of characters, clone the string, or concatenate the string. Also, set, map, etc., are iterable objects in JavaScript. So, you can use the spread operator with them.

  • Yield Operator

    JavaScript Yield Operator

    The yield operator in JavaScript is used to pause and resume the generator function asynchronously. In JavaScript, generator functions are the special functions that you can pause or resume while executing. The generator functions are defined with the ‘function*’ syntax. The yield keyword can only be used within the generator function that contains it.

    The yield operator pauses the execution of generator function and returns its operand (expression) to the generator’s caller.

    Syntax

    The syntax of the yield operator in JavaScript is as follows −

    yield expression;

    Paramter

    • expression − The value to yield from the generator function via the iterator protocol. ‘undefined’ is yielded, if expression is omitted.

    Return value

    It returns the optional value passed to the generator’s next() method to resume its execution.

    Yield Operator in Genrator Function

    To understand the yield operator, let’s understand fist the working of the generator function.

    When a generator function is called, it returns a generator object. When the next() method this generator object is called it resumes the execution of the generator function. When a yield expression is encountered, it pauses the execution and returns the expression after yield keyword to the object’s caller (the next() method).

    The next() method of the generator object returns an iterator object with two properties value and done. The value is the actual value of the expression and the done is a boolean value. The done property is true if the execution of the generator function is completely executed, else it if false.

    Below is a complete example code of generator function with yield keyword (operator).

    function*test(){// function codeyield expression;}const genObj =test();
    genObj.next();

    In the above syntax, ‘function*’ is used to create a generator function named test, and the yield keyword is used to return ‘expression’ from the function.

    The generator function test is called and assigned the returned generator object to the variable genObj. The next() method resumes the execution of the function and returns iterator object when encounters yield expression.

    Let’s execute the below JavaScript code snippet

    function*test(){
    
    console.log("I'm before yield expression");yield20;}const genObj =test();
    console.log(genObj.next());

    Notice when we call next() method, it display the message in the console first and then display the iterator object.

    I'm before yield expression
    { value:20, done:false}

    Example: Returning a value

    In the example below, we have defined the test() generator function. We used the yield operator 3 times in the function to return a number, an array, and a string, respectively.

    After that, we used the next() method four times to resume the execution of the function. Whenever the control flow finds the yield operator, it will stop execution and return the value.

    In the output, you can observe that it returns the object containing the operand of the yield operator and boolean value.

    function*test(){yield20;yield[1,2,3];yield"Hello World";}let res =test();
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());

    Output

    { value: 20, done: false }
    { value: [ 1, 2, 3 ], done: false }
    { value: 'Hello World', done: false }
    { value: undefined, done: true }
    

    Example: Returning undefined

    When we omit the expression following the yield keyword, it will return undefined.

    function*test(){yield;}let res =test();
    console.log(res.next());
    console.log(res.next());

    Output

    { value: undefined, done: false }
    { value: undefined, done: true }
    

    Example: Passing a value to the next() method

    We can also pass a value to the next() method. In the below example, we have passed 30 to the second next() method. It evaluates yield to 30. The variable result is assigned the value of yield which is evaluated as 30.

    function*test(){let result =yield20;
    
    console.log("default value paased to next() method "+ result);}let res =test();
    console.log(res.next()); console.log(res.next(30));

    Output

    { value: 20, done: false }
    default value paased to next() method 30
    { value: undefined, done: true }
    

    Example

    In the below code, we used the loop, and in each operation, we stop the execution of the function using the yield operator. Afterward, we use the next() method to start the execution of the generator function.

    // Generator functionfunction*test(){for(let p =0; p <6; p +=2){yield p;}}let res =test();
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());

    Output

    { value: 0, done: false }
    { value: 2, done: false }
    { value: 4, done: false }
    { value: undefined, done: true }
    

    In real-time development, programmers use the ‘yield’ operator for asynchronous operations, lazy evaluations, task scheduling, iterating through large datasets, creating custom iterators, etc.