Javascript if two conditions are met, print a message. Conditional operators. Conditional if statement

JavaScript has a conditional construct that affects the execution flow of a program. If (in English if) something is, something is true, then do one thing, otherwise (in English else) - do another.

If statement

Let's take a look at how the if statement works, it is simple and does not require much explanation.

If (condition) (code to execute if condition is true)

It's simple: if the condition is true, then the code in the (...) block is executed.

Var digit \u003d 4; if (digit \u003d\u003d 4) (document.write ("digit is 4.");)

Some strange code can be done:

Var digit \u003d 4; if (true) (document.write ("The condition is true.");)

Else statement

An else statement can be used in conjunction with an if statement. It translates to "otherwise" and specifies an alternate code.

Var digit \u003d 4; if (digit

Note the different spelling of curly braces in this example for the if and else statements. It is not obligatory to write this way, both syntaxes are correct.

The else statement can be followed by a new if statement. This will test multiple conditions.

Var digit \u003d 4; if (digit

JavaScript does not have an elseif statement (in one word) like PHP does.

If you only need to execute one statement, then the block curly braces (...) are unnecessary. In our example, you don't need to write them:

Var digit \u003d 4; if (digit

Lies in JavaScript

The if (condition) statement evaluates and converts the parenthesized condition (expression) to the boolian type (true or false).

Let's reiterate that there is a lie in JavaScript.

  • Number 0 (zero).
  • Empty line "".
  • Boolean false :)
  • The value is null.
  • The value is undefined.
  • The NaN (Not a Number) value.

Everything else is true.

A couple of possible errors:

If ("false") document.write ("This is true.
"); if (false) document.write (" This is true.

");

Here you need to distinguish the string "false" (in quotes), from the value of the boolean type false.

If ("") document.write ("This is true.
"); else document.write (" This is false.
");

Here you need to distinguish the string "" (inside a space), from the empty string "". A space inside a string makes it not empty, but a containing character. For the interpreter, it doesn't matter a letter or a space - a symbol is a symbol.

Other conditionals in JavaScript

  • JavaScript switch construction.
  • Operator question mark

var a \u003d 10; var b \u003d (a\u003e 1)? 100: 200; alert (b);

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

Js task 3_4. Code completion: 3 local variables are declared using the var keyword. 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 \u200b\u200bis checked, in the case of a suitable value, one or another block of statements corresponding to the given case.

The block starting with the service word default can be omitted. Block statements will be executed if none of the listed values \u200b\u200bin 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 below will be displayed

Compare with the operator IF:

var a \u003d 2; switch (a) (case 0: // if (a \u003d\u003d\u003d 0) case 1: // if (a \u003d\u003d\u003d 0) alert ("Zero or one"); // then output ... break; case 2: // if (a \u003d\u003d\u003d 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; ...

With a \u003d 0 and a \u003d 1, the same statement is executed: alert ("Zero or one");

Example 4: Prompt the user to enter a color. Display the English translation of the 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 \u003d prompt ("What color?");

    var color \u003d 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 colorhas 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 coloris blue or variable colorhas 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 \u003d 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 \u003d 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 \u003d "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 \u003d "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 operator.
  3. Save this page in the results folder (it will be useful for further work).


Questions for self-control:

  1. When is it advisable to use the construction as a conditional operator 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 variants in an operator switch?

Cyclic operators of 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)

  • An assignment expression is used as the initial value of the iteration counter: for example, i \u003d 0 - the loop counter starts from zero:
  • for (var i \u003d 0; condition; counter increment) (//..block of statements ..)

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

  • The loop condition is the end value of the counter: for example, i10 stops the loop:
  • for (var i \u003d 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 \u003d 9; counter step must be 1 (i ++) since the difference between the members of the sequence is one:
  • for (var i \u003d 0; i<10; i++) { document.write(i+"
    "); }

    In the example, the values \u200b\u200bof 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 \u003d ...; ...; ...) (sum \u003d 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 loop iteration, but, at the same time, continues the loop execution from the next iteration.

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

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

Snippet of code:

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

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


✍ Solution:
  • The third line of the example contains a condition due to which the digit 4 will not be displayed: operator continuewill proceed to the next iteration of the loop without completing the current one.
  • In line No. 5, the loop is exited, but the number 8 will be displayed, since the output statement comes before the condition (on the 4th line). Having met break, the interpreter will exit the loop.
  • So 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 \u003d prompt ("Enter a number");

  • Using the parseInt function to convert a string to an integer, check if the value entered is a number:
  • number \u003d 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 \u003d 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 rule of "lies" arrange for checking the value of the variable x... If the value is not numeric, print a corresponding note and exit 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 loop parameters 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 \u003d 0 j \u003d 2 i \u003d 1 j \u003d 3 i \u003d 2 j \u003d 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 \u003d 0, j \u003d 2; i< 10 , j< 5 ; i++, j++ ) { }

    for (i \u003d 0, j \u003d 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 \u003d 0, j \u003d 2). The parameters themselves are listed semicolon separated(;).

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

    for (i \u003d 0, j \u003d 2; i<10, j<5; i++, j++) { document.write("
    i \u003d ", i," j \u003d ", 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\u003e <li\u003e <li\u003e <li\u003e </ ol\u003e

bulleted list tags:

var listType \u003d 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 you entered a different value, 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 \u003d prompt ("Enter the number of items");

          • To convert a string value to a numeric value, use the parseInt function:
          • for (var i \u003d 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 \u003d\u003d "1") document.write ("") else if (listType \u003d\u003d" 2 ") document.write ("" ) ;

            if (listType \u003d\u003d "1") document.write ("

        ") else if (listType \u003d\u003d" 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 \u003d "1" width \u003d "30%"\u003e <tr\u003e <td\u003e-</ td\u003e -</ td\u003e </ tr\u003e </ table\u003e

      --

      • 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 (attribute of the table cell bgcolor):
        <td bgcolor \u003d "red"\u003e-</ td\u003e

        -

      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 \u003d 1; while (a< 1000 ) { a*= 2 ; alert(a) ; }

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

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

      • Test the result in a browser.

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

      Example:

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

      var a \u003d 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 \u200b\u200bwill the following code snippet display?

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


      Js task 3_14. Write erection code x to the extent yusing a while loop. Query variable values \u200b\u200band output the result using alert ().

      Complete the code:

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

      var x \u003d ...; var y \u003d ...; counter \u003d 1; chislo \u003d x; while (...) (chislo \u003d x * ...; counter \u003d ...;) 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 \u003d prompt ("Enter a number"); var factorial \u003d 1; document.write ( "Number factorial:" + counter + "! \u003d"); do (if (counter \u003d\u003d 0) (factorial \u003d 1; break;) factorial \u003d factorial / counter; counter \u003d counter + 1;) while (counter\u003e 0); document.write (factorial);

      var counter \u003d prompt ("Enter a number"); var factorial \u003d 1; document.write ("Number factorial:" + counter + "! \u003d"); do (if (counter \u003d\u003d 0) (factorial \u003d 1; break;) factorial \u003d factorial / counter; counter \u003d counter + 1;) while (counter\u003e 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 operator's work 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 dialog box - e.message.

      • 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 the 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 task 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:

      The lesson covered the following javascript operators and constructions:

      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 "lot" 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.

      The source for this interactive example is stored in a GitHub repository. If you "d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

      Syntax

      if (condition) statement1 condition An expression that is considered to be either truthy or falsy. statement1 Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement (...)) to group those statements. To execute no statements, use an empty statement. statement2 Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements.

      Description

      Multiple if ... else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.

      If (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN

      To see how this works, this is how it would look if the nesting were properly indented:

      If (condition1) statement1 else if (condition2) statement2 else if (condition3) ...

      To execute multiple statements within a clause, use a block statement ((...)) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if statements:

      If (condition) (statements1) else (statements2)

      Do not confuse the primitive Boolean values \u200b\u200btrue and false with truthiness or falsiness of the Boolean object. Any value that is not false, undefined, , 0, -0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:

      Var b \u003d new Boolean (false); if (b) // this condition is truthy

      Examples

      Using if ... else

      if (cipher_char \u003d\u003d\u003d from_char) (result \u003d result + to_char; x ++;) else (result \u003d result + clear_char;)

      Using else if

      Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if:

      If (x\u003e 50) (/ * do the right thing * /) else if (x\u003e 5) (/ * do the right thing * /) else (/ * do the right thing * /)

      Assignment within the conditional expression

      It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:

      If (x \u003d y) (/ * do the right thing * /)

      If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

      If ((x \u003d y)) (/ * do the right thing * /)

      Specifications

      Specification Status Comment
      ECMAScript Latest Draft (ECMA-262)
      Draft
      ECMAScript 2015 (6th Edition, ECMA-262)
      The definition of "if statement" in that specification.
      Standard
      ECMAScript 5.1 (ECMA-262)
      The definition of "if statement" in that specification.
      Standard
      ECMAScript 3rd Edition (ECMA-262)
      The definition of "if statement" in that specification.
      Standard
      ECMAScript 1st Edition (ECMA-262)
      The definition of "if statement" in that specification.
      Standard Initial definition

      Browser compatibility

      The compatibility table on this page is generated from structured data. If you "d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

      Update compatibility data on GitHub

      DesktopMobileServer
      ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
      if ... elseChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

      In this example, we first declare four variables using the var keyword, and immediately assign numeric values \u200b\u200bto them. Next, using the operators of increment and decrement, we change the values \u200b\u200bof 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"
      • \u003e - L.O. more P.O.
      • \u003e \u003d - L.O. is greater than or equal to P.O.
      • < - Л.О. меньше П.О.
      • <= - Л.О. меньше или равен П.О.
      • \u003d\u003d - L.O. equal to P.O.
      • ! \u003d - L.O. is not equal to P.O.
      • | \u003d - L.O. equal to itself OR P.O.
      • & \u003d - L.O. equal to myself AND P.O.
      • ^ \u003d - EXCLUSIVE OR

      Now consider the following script:

      //***************************************** // logical operations // logik_if_else.js //***************************************** var a \u003d 10, b \u003d 100, WshShell, title, msg1, msg2, msg3, msg4, vbInformation \u003d 64; // Create an instance of the WScript.Shell class WshShell \u003d WScript.CreateObject ("WScript.Shell"); title \u003d "Working with IF ELSE JS Conditional Statement"; with (WshShell) (if (a\u003e \u003d 5 && a<= 100 ) //истина msg1 = "TRUE" ; else msg1 = "FALSE" ; Popup (msg1, 5 , title, vbInformation) ; if (a>\u003d 5 || b \u003d\u003d 100) // true msg2 \u003d "TRUE"; else msg2 \u003d "FALSE"; Popup (msg2, 5, title, vbInformation); // conditional statement js if else if (! a) // false msg3 \u003d "TRUE"; else msg3 \u003d "FALSE"; Popup (msg3, 5, title, vbInformation); if (a & \u003d 100) // false msg4 \u003d "TRUE"; else msg4 \u003d "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 \u003d - 2; b \u003d 6; c \u003d 20; // Searching for discriminant d \u003d Math .pow (b, 2) - 4 * a * c; if (d \u003d\u003d 0) (x \u003d b / (2 * a); msg \u003d "The equation has one solution, x is exactly" + x) else (if (d\u003e 0) (x1 \u003d (- b + Math .sqrt (d)) / (2 * a); x2 \u003d (- b- Math .sqrt (d)) / (2 * a) ; msg \u003d "The equation has two solutions \\ n x1 exactly" + x1 + " \\ n x2 exactly " + x2; // conditional statement if else js ) else msg \u003d "No solution"; ) WScript.Echo (msg);

      In everyday life, it is often necessary to make 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.

      In programming, this is also very common. 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 operator, and in the next article about the switch-case.

      If-else conditional statement syntax following:


      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 \u003d 35000; // Let's say we have 35,000 euros // The car we want to buy costs 50,000 euros. And the following condition occurs if (money\u003e 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 in this case to be true, you need to write a greater than or equal sign (\u003e \u003d) ...

      Comment! The logical operation equal is written with two equal signs (\u003d\u003d)... 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 operator.

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

      Comment! 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 \u003d 4, b \u003d 4, c \u003d 8, d \u003d 8; if ((a \u003d\u003d b) && (c \u003d\u003d d)) document.write ("a equals b AND c equals 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 \u003d 2; // Number of sockets in the house if (socket \u003d\u003d 1) document.write ("

      We can only connect one device

      "); else if (socket \u003d\u003d 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 fire. 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.

      Shorthand 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 \u200b\u200bwrite 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 \u003d 50, b \u003d 100, x; x \u003d (a\u003e 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 if-else conditional operator 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.