Js short notation if. JavaScript if-else functions and conditions

Control instructions are instructions that allow you to control the execution of program code. Typically, the executable code in a control instruction is referred to as the body of that instruction.

Control instructions can be nested or used inside other control instructions.

Conditional statements

By default, the JavaScript interpreter executes instructions one after the other in the order they appear in source code... In cases where the execution or non-execution of some instructions must depend on the fulfillment or non-fulfillment of a certain condition, conditional statements are used.

If statement

The if statement has two forms. The syntax for the first form is:

The expression in parentheses is called condition of fulfillment if statements or conditional briefly. The value of the expression is evaluated first. The resulting value, if necessary, is implicitly converted to a boolean type. If the expression evaluates to true, then the statement is executed. If the expression returns false, then the statement is not executed:

If (true) alert ("Completed!"); if (false) alert ("Will not be executed!");

The if syntax allows you to execute only one statement, but if you need to execute more than one statement, you need to use a compound statement:

If (true) (var str = "Hello!"; Alert (str);)

The syntax for the second form is:

If (expression) statement; else statement;

The else keyword allows you to add a statement to be executed if the condition is false:

If (false) alert ("Will not be executed"); else alert ("Execute");

As already mentioned, control instructions can be nested, which allows you to create the following constructs:

Var num = 2; if (num == 1) (alert ("num value:" + num);) else if (num == 2) (alert ("num value:" + num);) else (alert ("I don’t know such a number ! ");)

There is nothing special about this code. It is simply a sequence of statements, where each if statement is part of the else of the previous if statement. At first glance, this form of notation may not seem entirely clear, so let's consider a syntactically equivalent form showing the nesting of if statements:

Var num = 2; if (num == 1) (alert ("num value:" + num);) else (if (num == 2) (alert ("num value:" + num);) else (alert ("I don’t know this numbers! ");))

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

More than 2 million domain names in service.

Promotion, mail for domain, business solutions.

More than 700 thousand customers around the world have already made their choice.

Bootstrap framework: fast responsive layout

A step-by-step video tutorial on the basics of responsive layout in the Bootstrap framework.

Learn to typeset easily, quickly and efficiently using a powerful and practical tool.

Layout to order and get paid.

* Hover your mouse to pause scrolling.

Back forward

JavaScript if-else functions and conditions

Often, when using JavaScript, it becomes necessary to perform different actions when different conditions are met.

For example, you wrote a script that checks which browser a visitor is using when visiting your site. If this Internet Explorer, a page specially designed for IE should be loaded, if it is any other browser - another version of this page should be loaded.

The general syntax for the if-else construct is as follows:

If (condition) (action) else (action2);

As an example, consider the following code:

If (browser == "MSIE") (alert ("You are using IE")) else (alert ("You are not using IE"));

Note that all lowercase letters are used. If you write "IF", an error will occur.

Also note that the comparison uses a double equal sign (==).

If we write browser = "MSIE" then we just assign the value MSIE variable named browser.

When we write browser == "MSIE", then JavaScript "understands" that we want to compare, not assign a value.

More complex conditions if can be created simply by adding them, for example, to the part else already existing construction if-else:

If (condition) (action1) else (if (other condition) (action2) else (action3););

For example:

If (browser == "MSIE") (alert ("You are using IE")) else (if (browser == "Netscape") (alert ("You are using Firefox")) else (alert ("You are using an unidentified browser: ) ")); );

Logical operators AND, OR and NOT

For even more flexible use of the structure if-else so-called logical operators can be used.

And written as && and is used in cases where you need to check for the truth of more than one condition.

For example: If there are eggs in the fridge and bacon in the fridge, then we can eat eggs and bacon.

The syntax is as follows:

If (condition1 && condition2) (action) if (hour == 12 && minute == 0) (alert ("Noon!"));

Or written as || and is used when we want to check for the truth of at least one of two or more conditions. (You can get || by holding down the shift key and the \ key)

For example: If there is milk in the refrigerator, or if there is water in the refrigerator, then we have something to drink.

The syntax is as follows:

If (condition1 || condition2) (action) if (hour == 11 || hour == 10) (alert ("Noon has not come yet!"));

Not written as ! and is used for denial.

For example: If there are no eggs in the refrigerator or no bacon, then we cannot eat either eggs or bacon.

The syntax is:

If (! (Condition)) (action) if (! (Hour == 11)) (alert ("It is not 11 o'clock"));

Functions in JavaScript

Instead of just adding Javascript to the page so that the browser will execute the code when it comes to it, you can make the script execute only when an event occurs.

For example, you have created JavaScript whose job it is to change background color page when clicking on a specific button. In this case, you need to "tell" the browser that this script should not be executed simply because a queue has reached it.

To prevent the browser from executing the script when it loads, you need to write the script as a function.

In this case, the JavaScript code will not be executed until we "ask" it in a special way.

Take a look at this example of a script written as a function:



Click on the button to see what the script does:

If the line alert ("Welcome!"); was not written inside a function, then it would be executed whenever the browser reached this line. But since we wrote it inside the function, this line is not executed until we press the button.

A function call (i.e. access to it) occurs in this line:

As you can see, we have placed a button on the form and added an event onClick = "myfunction ()" for the button.

In future lessons, we will look at other types of events that trigger functions.

The general syntax for functions is as follows:

Function functionname (variable1, variable2, ..., variableN) (// Here goes the body of the function, the actions that it performs)

Braces: { and } indicate the beginning and end of a function.

A typical mistake when creating functions is carelessness and ignoring the importance of case. Word function should be exactly function... Option Function or FUNCTION will throw an error.

Also, using capital letters plays a role in specifying variable names. If you have a function named myfunction (), then an attempt to refer to her as to Myfunction (), MYFUNCTION () or MyFunction () will throw an error.

Did you like the material and want to thank you?
Just share with your friends and colleagues!


See also:

var a = 10; var b = (a> 1)? 100: 200; alert (b);

If the condition a> 1 is true, then the variable b assign value 100 , otherwise the variable b is assigned the value 200 .

Js task 3_4. Complement code: declared 3 local variables using keyword var. It is necessary to assign the value of the following ternary operator to the variable max: if a is greater than b, then we return a, otherwise we return b.
Snippet of code:

if (a * b< 6) { result = "Мало"; } else { result = "Много"; }


Questions for self-control:

  1. What is the syntax for the ternary operator?
  2. How many arguments does the ternary operator have?

Switch operator in javaScript - switch

The javascript switch statement is used to test a variable for multiple values:

Syntax:

switch (variable or expression) (case option1: //.. statement block .. break case option2: //.. statement block .. break default: //.. statement block ..)

The value of a variable or expression is checked: in each case one of the values ​​is checked, in the case of a suitable value, one or another block of statements corresponding to this case.

The block starting with the service word default can be omitted. Block statements will be executed if none of the listed values ​​in all case does not fit.

Important: The break statement is required after each considered value of the variable (after each case); if you do not use it, then all the operators located below will be displayed

Compare with the operator IF:

var a = 2; switch (a) (case 0: // if (a === 0) case 1: // if (a === 0) alert ("Zero or one"); // then output ... break; case 2: // if (a === 2) alert ("Two"); // then display ... break; default: // else alert ("Many"); // otherwise display ...)

How do I group multiple options?

To execute the same operators, it is possible to group several case... As in the example above:

Case 0: case 1: alert ("Zero or one"); break; ...

For a = 0 and a = 1, the same statement is executed: alert ("Zero or one");

Example 4: Prompt the user to enter a color. Output translation to English entered color. For color "blue" and "blue" return the same value.


✍ Solution:
  • Create a web page with html skeleton and tag script.
  • Initialize a variable color
  • var color = prompt ("What color?");

    var color = prompt ("What color?");

  • Check the value of a variable using the construct switсh, outputting for each value - the corresponding translation:
  • switch (color) (case "red": alert ("red"); break; case "green": alert ("green"); break; // ...

    If the variable color has the value "red", then display the translation in the modal window - "red" and exit the construction (break;). If the variable color has the value "green", then display the translation in the modal window - "green" and exit the construction (break;).

  • For flowers "blue" and "blue" do the grouping:
  • // ... case "blue": case "blue": alert ("blue"); break; // ...

    If the variable color is blue or variable color has the value "blue", then display the translation in the modal window - "blue" and exit the construction (break;).

  • Organize the output for those colors that are not provided by the program:
  • // ... default: alert ( "we have no information on this color")) // end switch

    // ... default: alert ("y we have no information on this color")) // end switch

  • Test the script in a browser.

Js task 3_6. Find and fix errors in the following code snippet:

14 15 16 17 var number = prompt ( "Enter the number 1 or 2:"); switch (number) (case "1" (document.write ("One");); break; case "2" (document.write ("Two");); break; default (document.write ( "You entered a value other than 1 and 2") ; } ; }

var number = prompt ("Enter the number 1 or 2:"); switch (number) (case "1" (document.write ("One");); break; case "2" (document.write ("Two");); break; default (document.write ("You entered a value other than 1 and 2 "););)


Js task 3_7. What will be displayed on the screen when the following code is executed ?:

1 2 3 4 5 6 7 8 9 10 11 12 13 var value = "2"; switch (value) (case "1": case "2": case "3": document.write ("Hello"); break; case "4": case "5": document.write ("World"); default: document.write ("Error");)

var value = "2"; switch (value) (case "1": case "2": case "3": document.write ("Hello"); break; case "4": case "5": document.write ("World"); default: document.write ("Error");)


Js task 3_8. The user will be prompted for a number - the number of crows on the branch. Depending on the entered number (no more than 10), display the message: - Sitting on a branch 1 crow- Sits on a branch 4 crows- Sits on a branch 10 crows

  1. Depending on the entered number, the ending of the word changes "Crow".
  2. To check, use the Switch javascript statement.
  3. Save this page in the results folder (it will be useful for further work).


Questions for self-control:

  1. In which case is it advisable as conditional operator use construction switch?
  2. What is the default block in the statement for? switch?
  3. Is it mandatory to use the break statement in the construction switch?
  4. How grouping is performed for multiple value options in an operator switch?

Cyclic operators of the javaScript language - For

Syntax:

for (initial value of the counter; condition; increment of the counter) (//..block of statements ..)

Important: A loop in javascript for is used when it is known in advance how many times cyclic actions should be repeated (how many iterations the loop has)

  • As initial value the iteration counter, an assignment expression is used: for example, i = 0 - the loop counter starts at zero:
  • for (var i = 0; condition; counter increment) (//..block of statements ..)

  • The increment of the counter indicates the step with which the counter should increase: for example, it indicates that each iteration of the loop will be accompanied by its increment by 1 :
  • for (var i = 0; condition; i ++) (//..block of statements ..)

  • The loop condition is the final value of the counter: for example, i10, stops the loop:
  • for (var i = 0; i<10; i++) { //..блок операторов.. }

Let's look at an example of using a for loop in javascript:

Example 5: Print a sequence of numbers 0 1 2 3 ... 9 , each digit on a new line. 0 1 2 ... 8 9


✍ Solution:
  • To display a sequence of numbers, we will use the counter of the for loop, which should change its value from 0 before 9 according to the sequence.
  • Hence, for the initial value of the cycle counter set the value to 0 ; as cycle conditions set the final value - ii = 9; counter step must equal 1 (i ++) since the difference between the members of the sequence is one:
  • for (var i = 0; i<10; i++) { document.write(i+"
    "); }

    In the example, the values ​​of the loop counter are displayed on the screen, since the increment of the counter i ++, respectively, will appear on the screen 0 1 2 3 ... 9 , with each digit on a new line (tag
    ).

  • Test the script in a browser.

Js task 3_9. 1 before 15 .

  1. Use a loop counter as a sequence of numbers for.
  2. For an adder variable, use the variable identifier sum.

Snippet of code:

For (var i = ...; ...; ...) (sum = sum + ...;) ...

Loop exit statements break and continue in javaScript. Operator Exit

The break statement interrupts the execution of the entire loop body, i.e. breaks out of the loop in javaScript.

While the continue statement interrupts the execution of the current iteration of the loop, but, at the same time, continues the execution of the loop from the next iteration.

Let's consider the operation of the break and continue statements using an example:

Example: Deconstruct the algorithm of the code snippet. What will be displayed?

Snippet of code:

1 2 3 4 5 6 for (var i = 0; i< 10 ; i++ ) { if (i== 4 ) continue ; document.write (i+ "
"); if (i == 8) break;)

for (var i = 0; i<10;i++) { if (i==4) continue; document.write(i+"
"); if (i == 8) break;)


✍ Solution:
  • The third line of the example contains a condition due to which the digit 4 will not be displayed: operator continue will go to the next iteration of the loop without completing the current one.
  • In line 5, the loop is exited, but at the same time the number 8 will be displayed, since the output statement comes before the condition (in the 4th line). Having met break, the interpreter will terminate the cycle.
  • That. the screen will show: 0 1 2 3 5 6 7 8 - each digit on a new line.

Js task 3_10. Output the sum of all integers from 1 before 15 , excluding from the total number 5 and 7 .

Exit statement

The javasctipt language provides an exit operator from the program code - the exit operator.
Most often, the operator is used to eliminate user input error.


Let's consider an example:

Example 6: Prompt the user to enter a number. If not a number is entered, then display the message "You need a number!" and stop the program.


✍ Solution:
  • Initialize a variable number the value entered by the user into the modal:
  • var number = prompt ("Enter a number");

  • Using the parseInt function to convert a string to an integer, check if the value entered is a number:
  • number = parseInt (number); // will return NaN - not a number

    If not a number is entered, the function will return the value NaN (from English. not a number- not a number).

  • Check the value of the variable number using the isNaN function:
  • x = isNaN (number); // will return true if the value is not numeric

    IsNaN function returns value true in case the variable is not a number

  • By the rule of "lies" arrange for checking the value of the variable x... If the value is not numeric, print a corresponding note and terminate the program:
  • if (x) (alert ("A number is required!"); exit; // exit the program)

  • To continue the program (if the entered value was a number), display the following window with an input prompt:
  • alert ("Enter the second number"); // if you enter a non-number, the statement will not be executed

  • Test the script in a browser.

Questions for self-control:

  1. List three parameters of the loop for and explain their purpose.
  2. What operators are meant to exit the loop and to interrupt it? Give examples of their use.
  3. What the operator is for exit?

Is it possible to have multiple counters in one FOR?

An interesting work with the for loop is possible by using simultaneously two counters in a cycle.
Let's consider an example:

Example 7: Using the script, print the following variable-value pairs in three lines: i = 0 j = 2 i = 1 j = 3 i = 2 j = 4


✍ Solution:
  • In the for loop, organize two counters: counter i to output the sequence 0 1 2 , counter j for outputting the sequence 2 3 4 :
  • 1 2 3 for (i = 0, j = 2; i< 10 , j< 5 ; i++, j++ ) { }

    for (i = 0, j = 2; i<10, j<5; i++, j++) { }

    Each of the three parameters of the for loop now has two values, which are listed comma separated(for example, the first parameter with two values: i = 0, j = 2). The parameters themselves are listed semicolon separated(;).

  • For output on each line, use the tag
    :
  • 1 2 3 4 for (i = 0, j = 2; i< 10 , j< 5 ; i++, j++ ) { document.write ("
    i = ", i," j = ", j);)

    for (i = 0, j = 2; i<10, j<5; i++, j++) { document.write("
    i = ", i," j = ", j);)

On-the-fly page generation: how is it?

Before doing the next task, consider an example. dynamically building html page using javascript.

Example 8:

  • It is necessary to dynamically generate bulleted and numbered lists on the web page depending on the data entered by the user: prompt the user to enter list view(numbered (number 1) or labeled (number 2)), and then number of list items.
  • Depending on the answer, display the tags of either a bulleted or numbered list with the required number of items.
  • If a non-existent list type is entered, then display the message "Please enter the correct type!" and exit the program ().

Let's remember the tags:
numbered list tags:

<ol> <li> <li> <li> </ ol>

bulleted list tags:

var listType = prompt ("Enter" 1 "for a bulleted list," 2 "for a numbered list");

  • Check the entered value: for a numbered list (number 1) output the tag
      , for marked (number 2) - tag
        ... If a different value is entered, print a note and end the program:

            ") else (alert (" Enter the correct type "); exit;)

          • Initialize a variable kolvo the value entered by the user into the modal:
          • var kolvo = prompt ("Enter the number of items");

          • To convert a string value to a numeric value, use the parseInt function:
          • for (var i = 1; i<=kolvo; i++) document.write("");

          • Since the lists are closed with the corresponding tags, depending on the type of the list, print the closing tags:
          • if (listType == "1") document.write ("") else if (listType ==" 2 ") document.write ("" ) ;

            if (listType == "1") document.write ("

        ") else if (listType ==" 2 ") document.write ("
      ");

    1. Test the script in a browser.
    2. Js task 3_11.
      Write a script that displays tags input(controls) of different types, depending on the entered digit:

      1 - text field,
      2 - button,
      3 - radio(switch).

      The number of tags displayed should also be requested.

      Let's remember the tags:

      For 1 - text field: For 2 - button: For 3 - radio:

      Output example:

      Js task 3_12. Draw a 9x9 checkerboard using javascript for loops. "Draw" the board should be html tags for the table:

      Let's remember the tags:

      <table border = "1" width = "30%"> <tr> <td>-</ td> -</ td> </ tr> </ table>

      --

      • To draw 9 lines, you need to organize an external for loop with a counter i.
      • To draw 9 cells in each line, you need to organize an inner (nested) for loop with a counter j.
      • Use the document.write method to render cell and line tags.

      Result:

      Additionally:

      1. Print the multiplication table into the table cells using the loop counters (i and j).
      2. Display the first row and the first column with a red background (table cell attribute bgcolor):
        <td bgcolor = "red">-</ td>

        -

      Result:


      Questions for self-control:

      1. Explain what does dynamic page building mean?
      2. What is the most commonly used language construct for dynamic page building?

      Cyclic statements of the javaScript language - While

      The syntax for the while statement is:

      while (condition) (//..block of statements ..);

      Example: Display powers of two up to 1000 (2, 4, 8 ... 512). Use alert () method


      ✍ Solution:
      • Listing of the script:
      • 1 2 3 4 5 var a = 1; while (a< 1000 ) { a*= 2 ; alert(a) ; }

        var a = 1; while (a< 1000){ a*=2; alert(a); }

        a * = 2 → the operation of compound assignment is used: the product combined with the assignment, i.e. same as a = a * 2

      • Test the result in a browser.

      How do the break and continue statements work in a while loop?

      Example:

      var a = 1; while (a< 1000 ) { a*= 2 ; if (a== 64 ) continue ; if (a== 256 ) break ; alert(a) ; }

      var a = 1; while (a< 1000){ a*=2; if (a==64) continue; if (a==256) break; alert(a); }

      Powers of two will be output to 128 inclusive, and the value 64 will be skipped. Those. in the dialog boxes we will see: 2 4 8 16 32 128

      Js task 3_13. What values ​​will the following code snippet display?

      var counter = 5; while (counter< 10) { counter++; document.write("Counter " + counter); break; document.write("Эта строка не выполнится."); }


      Js task 3_14. Write erection code NS to the degree y using a while loop. Query variable values ​​and output the result using alert ().

      Complete the code:

      1 2 3 4 5 6 7 8 9 var x = ...; var y = ...; counter = 1; chislo = x; while (...) (chislo = x * ...; counter = ...;) alert (chislo);

      var x = ...; var y = ...; counter = 1; chislo = x; while (...) (chislo = x * ...; counter = ...;) alert (chislo);

      A Correct the error in the program designed to find the factorial of a number:

      1 2 3 4 5 6 7 8 9 10 11 12 13 var counter = prompt ("Enter a number"); var factorial = 1; document.write ( "Number factorial:"+ counter + "! ="); do (if (counter == 0) (factorial = 1; break;) factorial = factorial / counter; counter = counter + 1;) while (counter> 0); document.write (factorial);

      var counter = prompt ("Enter a number"); var factorial = 1; document.write ("Number factorial:" + counter + "! ="); do (if (counter == 0) (factorial = 1; break;) factorial = factorial / counter; counter = counter + 1;) while (counter> 0); document.write (factorial);


      Js task 3_16. Modify the program for user input:

      Prompt for a username until the user actually enters a name (i.e. the field is actually filled in and the cancel key is not pressed). When the name is entered, then output "Hello name!"... document.

      How to find errors in javascript?

      In some cases, the code on the page does not work for some reason. Where to look for the error? In such cases, you can use the try..catch statement.

      The try..catch statement tries to execute a piece of code, and if there is an error in the code, it is possible to display an error on the screen.
      The error is stored in the e.message object.

      Let's consider the work of an operator using an example:

      Example: write a statement with an error in the program. Check for an error in the suspected erroneous code: if there is an error in the code, display a message "error handling: error name"... After checking the erroneous operator, regardless of whether there is an error in the code, issue the message "finishing actions"


      ✍ Solution:
      • As a message with an error, we will use the prompt () method, written with an error - promt ()... Enclose the error message in a try block:
      • alert ("before"); try (promt ("enter a number"); // operator with an error)

        Try from English. - "try", thus, we put a try statement in front of a code fragment that may contain an error (in our case, there really is an error).

      • The error message should be placed in a catch block:
      • 6 7 8 9 catch (e) (alert ( "error handling:"+ e.message); )

        catch (e) (alert ("error handling:" + e.message);)

        If there really is an error, then the catch statement stores this error in the e object. Later it can be displayed in the e.message dialog box.

      • Place the final message, which should be displayed regardless of whether there is an error in the code, in a finally block:
      • finally (alert ("finishing actions");) alert ("after");

        If there is an error, then the interpreter, after displaying it in our example, will go on to execute the catch block, and then finally (from English "completion", "finally"), which will always be executed, regardless of whether there was an error or not. Even if there was an error in the catch block.

      Important: The finally block is optional in the construction.


      Js assignment 3_17. Follow the example above with the following modifications:

    3. Remove the finally block and watch the code run.
    4. Replace the erroneous operator with an error-free one and see what the result will be.
    5. Summary:

      In the lesson, the following javascript language operators and constructions were considered:

      Javascript conditional statements:

    6. If statement
    7. Conditional assignment (ternary operator)
    8. Switch statement
    9. Loop operators:

    10. For loop
    11. While loop
    12. The do ... while loop
    13. For ... in loop
    14. Final task Js 3_18.
      Create a game for two:

      1. The program asks the first player to enter a number from 1 before 100 (the second player does not see the entered number). Then the second player is asked to guess the entered number. The message is displayed in response "few" or "many" depending on the answer entered. If the player guesses correctly, congratulations are displayed. If he guesses wrong, the game continues (until the number is actually guessed).
      2. Calculate the number of attempts and return the result when the number is guessed.


      Questions for self-control:

      1. When is it advisable to use a For In loop? What is an example of its use.
      2. What is the purpose of the try..catch statement?
      3. Explain the purpose of each try..catch statement block.

      In everyday life, it is often necessary to take some kind of decision, depending on some condition. For example, if the weather is warm on the weekend, then we will go to the sea, otherwise, if it is cloudy, we will sit at home.

      This is also very common in programming. For this there are two conditional statements, these are if-else and switch-case... In this article I will tell you about the if-else statement, and in the next article about the switch-case.

      If-else conditional statement syntax next:


      If the condition is true, then the code from the if block is executed, otherwise, if the condition is false, then the code from the else block is executed.

      For a better understanding, let's take such a simple example, we have a certain amount of money and we want to buy a car, and here such a condition immediately arises, if we have enough money, then we can buy this car, otherwise we cannot.

      Var money = 35000; // Let's say we have 35,000 euros // The car we want to buy costs 50,000 euros. And such a condition occurs if (money> 50000) (document.write ("We can buy a car");) else (document.write ("Not enough money to buy a car");)

      We save the document, open it in a browser and see that the following message is displayed on the page "Not enough money to buy a car". If we had more than 50,000 euros, then the code from the if block would be executed. If we had exactly 50,000 euros, then we would also not be able to buy a car, because 50,000 is not more than 50,000. In order for the condition to be true in this case, you need to write a greater than or equal sign (> =) ...

      Comment! The logical operation equal is written with two equal signs (==)... There is also a logical operation less than or equal to (

      using curly braces

      If there is only one operator, then curly braces are optional, if there is more than one operator in the block, then curly braces are required.

      The example above will work fine without curly braces, since both blocks contain only one statement.

      Any logical operations can be written inside the if. whether they are simple or complex. You can also use the AND (&&) and OR (||) operators.

      Comment! The presence of the else block is optional.

      For example, if a is equal to b, and c is equal to d, then we display the corresponding message, otherwise if there is no else block, then we simply move on to the next line.

      Var a = 4, b = 4, c = 8, d = 8; if ((a == b) && (c == d)) document.write ("a is equal to b AND c is equal to d"); document.write ("Next line of code");

      Statement if - else if - else

      After the if block, one or more else if blocks can follow, and at the end there is an else block. This is useful when you need to use more than one condition.


      For a better understanding, let's take an example from everyday life. For example, we have a certain number of outlets. If we have only one outlet in the room, then we can connect only one device, if there are two sockets, then we can connect two devices, and if there are more, then we can connect all devices from home to the electrical network.

      Now let's move on to programming.

      Var socket = 2; // Number of sockets in the house if (socket == 1) document.write ("

      We can only connect one device

      "); else if (socket == 2) (document.write ("

      We can only connect two devices

      "); document.write ("

      For example TV and laptop

      ");) else (document.write ("

      We can connect all devices from home to the electrical network

      "); }

      Depending on the value of the socket variable, this or that block of code will be triggered. As you probably already understood, if socket is equal to 1, then the first block of code will work. If socket is 2, then the second block of code will fire, and if socket has any other value (even a negative number), then the third block of code will fire.

      Abbreviated notation if else

      The abbreviated notation can be used in the case when, depending on a certain condition, a variable can receive one or another value.


      For example, if the value of the variable a is greater than the value of the variable b, then in the variable x we ​​write the following message, "The variable a is greater than the variable b", otherwise we write that "The variable a is less than the variable b".

      Var a = 50, b = 100, x; x = (a> b)? "

      Variable a more variable b

      " : "

      Variable a smaller variable b

      "; // Print the resulting result document.write (x);

      That's all I wanted to tell you about in this article. The conditional operator if-else is used more than in every script, so it is very important to know and understand it. In the next article I will tell you about one more conditional switch-case statement.

      In this example, we first declare four variables using the var keyword, and immediately assign them numeric values. Next, using the operators of increment and decrement, we change the values ​​of the numbers. Information is displayed using the function Echo(see article ""). In order not to write the name of the object once again, I used the construction with ().

      Logical operators

      Logical operators are used when checking the condition, so as not to repeat, I will make an abbreviation: the left operand is L.O., and the right operand is P.O.

      • && - Logical "AND"
      • || - "OR"
      • ! - "NOT"
      • > - L.O. more P.O.
      • > = - L.O. is greater than or equal to P.O.
      • < - Л.О. меньше П.О.
      • <= - Л.О. меньше или равен П.О.
      • == - L.O. equal to P.O.
      • ! = - L.O. not equal to P.O.
      • | = - L.O. equal to itself OR P.O.
      • & = - L.O. equal to myself AND P.O.
      • ^ = - EXCLUSIVE OR

      Now, consider the following script:

      //***************************************** // logical operations// logik_if_else.js //***************************************** var a = 10, b = 100, WshShell, title, msg1, msg2, msg3, msg4, vbInformation = 64; // Create an instance of the WScript.Shell class WshShell = WScript.CreateObject ("WScript.Shell"); title = "Working with the IF ELSE JS conditional statement"; with (WshShell) (if (a> = 5 && a<= 100 ) //истина msg1 = "TRUE" ; else msg1 = "FALSE" ; Popup (msg1, 5 , title, vbInformation) ; if (a>= 5 || b == 100) // true msg2 = "TRUE"; else msg2 = "FALSE"; Popup (msg2, 5, title, vbInformation); // conditional statement js if else if (! a) // false msg3 = "TRUE"; else msg3 = "FALSE"; Popup (msg3, 5, title, vbInformation); if (a & = 100) // false msg4 = "TRUE"; else msg4 = "FALSE"; Popup (msg4, 5, title, vbInformation); )

      As in the previous script, here I used the construction with to shorten the program code. However, to display information, we used the function Popup(see article ""). As a result, the dialog boxes will close automatically after a few seconds. Please note that in this example we did not use curly braces. in the js if conditional statement, they are relevant only when you need to execute more than one line of code, but several.

      Finally, let's look at a practical example like solving a quadratic equation:

      // Solving a quadratic equation// uravnenije_if_else.js // *********************************************************** var a, b, c, d, x, x1, x2; // Declare variables a = - 2; b = 6; c = 20; // Searching for discriminant d = Math .pow (b, 2) - 4 * a * c; if (d == 0) (x = b / (2 * a); msg = "The equation has one solution, x is exactly"+ x) else (if (d> 0) (x1 = (- b + Math .sqrt (d)) / (2 * a); x2 = (- b- Math .sqrt (d)) / (2 * a) ; msg = "The equation has two solutions \ n x1 exactly"+ x1 + " \ n x2 exactly "+ x2; // conditional statement if else js) else msg = "No solution"; ) WScript.Echo (msg);