Last Updated:

Conditional operators - JavaScript

 

Any programming language would be useless if it did not provide some means of branching during the execution of the program. JavaScript provides an if-else conditional statement that allows you to execute different program strings depending on the condition.

A general view of the if-else statement is shown below:

if(condition)
   line 1
[else
   line 2]

The part of the operator highlighted in square brackets is optional.

When this statement is executed, the condition specified in parentheses after the if keyword is evaluated. If the condition score returns to a Boolean value of true, line 1 is executed. If false is obtained, then line 2 is executed (when it is present).

The if-else statement can be nested. Note that if you want to arrange more than one statement on line 1 or line 2, you should highlight them with curly braces:

if(nYourAge < 18)
{
  bAccessDenied = true;
  szNextPage = "bye18.html";
}
else if(nYourAge > 99)
{
  bAccessDenied = true;
  szNextPage = "bye99.html";
}
else
{
  bAccessDenied = false;
  szNextPage = "welcome.html";
}

Here, the condition is first evaluated (nYourAge < 18). If the contents of the nYourAge variable are less than 18, the bAccessDenied variable is set to true, and the szNextPage variable is set to the text string "bye18.html".

Otherwise, the contents of nYourAge are compared to the number 99. If the nYourAge variable has a value greater than 99, the bAccessDenied variable is set to true, and the szNextPage variable is set to the text string "bye99.html".

Finally, if neither of the two conditions is met, that is, the value of the nYourAge variable is between 18 and 99, false is written to the bAccessDenied variable, and the szNextPage variable is the text string "welcome.html".

There is also a special type of conditional operator called the ?:. This operator is generally written as follows:

expression ? line 1 : line 2

When calculating the ?: operator, the Boolean expression on the left side is evaluated first. If it is true, line 1 is executed, and if false, line 2 is executed.

The following is an example of using the conditional operator ?: to assign the value of the bAccessDenied variable based on the contents of the nYourAge variable:

bAccessDenied = 
  (nYourAge < 18 || nYourAge > 99) ? true : false;

If the value of the nYourAge variable is between 18 and 99, the bAccessDenied variable is set to true, and if it does not fall within this interval, false. Traditionally, solving this problem using the else-if operator would take up more space: The above examples specify a composite condition: According to the precedence table, the operator || is calculated after the < and > operators. If you do not want to deal with the precedence table, you can use parentheses to indicate the order of calculation:

if(nYourAge < 18 || nYourAge > 99)
  bAccessDenied = true;
else
  bAccessDenied = false;
(nYourAge < 18 || nYourAge > 99)
((nYourAge < 18) || (nYourAge > 99))


Self-service tasks

  1. Write a script that asks for two numbers and displays the largest number in the browser window.
  2. Write a script that asks for the month number and displays the name of the time of year.
  3. Write a script that displays a dialog box with OK and Cancel buttons (confirm function) and displays a message in the browser window about which of the buttons was pressed (use the if(confirm("Message")) construct ... )

 

Loop operators

The JavaScript language has several statements designed to organize loops.


For operator

A general view of the for operator is presented below:

for([initialization;] 
[condition;]
[iteration])

{ . . . loop body lines . . . }

In the initialization area, you typically assign initial values to loop variables. It is acceptable to declare new variables using the var keyword. The second area specifies the condition to exit the loop. This condition is evaluated each time the cycle progresses. If the scoring results in a Boolean value of true, the loop body strings are executed. The iteration scope is used to change the values of cycle variables, for example, to increment the loop counter.


For-in operator

The for-in statement is used to view all the properties of an object and is written as follows:

for(variable in object)
{
   . . .
   loop body lines
   . . .
}


while operator

To organize iterative loops with a precondition, the while operator is used:

while(condition)
{
   . . .
   loop body lines
   . . .
}

If the condition evaluation results in true, then the iteration is performed if false the loop is interrupted.


Break statement

You can use the break statement to interrupt the execution of a loop created by the for or while statements anywhere. For example:

var i = 0;
while(true)
{
  . . .
  i++;
  if(i > 10)
    break;
  . . .
}
 

Continue statement

Executing the continue statement inside a for or while loop causes the iteration to be interrupted and then resumed. This statement does not interrupt the loop. The following is an example of using the continue operator:

var i = 0;
while(i < 100)
{
  i++;
  if(i < 10)
    continue;
  . . .
}

Here, the loop body fragment marked with an ellipsis will execute only after the value of the variable i becomes 10. When this value reaches 100, the cycle will be completed.

 

Examples of using loop operators

The following are three examples of using the for and while loop operators. In all of these examples, the script displays ten lines of "Hello, world!" in the document window. The source code for the first scenario is shown in Listing 1.10.

Code Listing 1.10.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var szHelloMsg = "Hello, world!";

    function printNString(szString, n)
    {
      var i;
      for(i = 0; i < n; i++)
      {
        document.write(szString + "<BR>");
      }
    }

    function printHello()
    {
      printNString(szHelloMsg, 10);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <P>Message:<BR> 
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>  
  </BODY>
</HTML>

Here, immediately after loading the document, the printHello function is called. In the body of this function, in turn, the printNString function is called, to which two parameters are passed: Through the first parameter of this function, the text string szHelloMsg is passed, and through the second - the number of repetitions of this line during output. The output of the string is performed by the printNString function in a loop: Here, the value of the loop variable i varies from zero to n, where n is the number of repetitions. When the value of the loop variable reaches the value of n, the loop will be completed.

printNString(szHelloMsg, 10);
for(i = 0; i < n; i++)
{
  document.write(szString.bold() + "<BR>");
}

Listing 1.11 shows a script that solves the same problem using a different method, using the while operator.

Code Listing 1.11.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var szHelloMsg = "Hello, world!";

    function printNString(szString, n)
    {
      var i;
      i = 0;
      while(i < n)
      {
        document.write(szString + "<BR>");
        i++;
      }
    }

    function printHello()
    {
      printNString(szHelloMsg, 10);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <P>Message:<BR> 
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>
  </BODY>
</HTML>

Here i is also used as a loop variable: How does this loop work? After the write method outputs the string, the value of the loop variable is incremented by one. Then, before starting the next iteration, it is checked whether the cycle variable has reached the value of n. If it has, the loop completes its work.

i = 0;
while(i < n)
{
  document.write(szString.bold() + "<BR>");
  i++;
}

Using the while and break statements together is demonstrated in the scenario shown in Listing 1.12.

Code Listing 1.12.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var szHelloMsg = "Hello, world!";

    function printNString(szString, n)
    {
      var i;
      i = 0;
      while(true)
      {
        document.write(szString + "<BR>");
        i++;
        if(i > n)
          break;
      }
    }

    function printHello()
    {
      printNString(szHelloMsg, 10);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <P>Message:<BR> 
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>
  </BODY>
</HTML>

As in the previous case, i is used as a loop variable, but in the while statement, the loop completion condition is set to true: A break statement is used to interrupt the loop. This operator is called if the value of the cycle variable i exceeds the value of n.

i = 0;
while(true)
{
  document.write(szString.bold() + "<BR>");
  i++;
  if(i > n)
    break;
}


Self-service tasks

  1. Write a script that asks for the number of students in the student group and, according to this number, their names and surnames. Last names and first names must be displayed in a browser window.
  2. Write a script that prompts for last names and first names until the user clicks cancel in the input window. Last names and first names must be displayed in a browser window.
  3. Write a script that displays a multiplication table in the browser window