Javascript conditional operator. Conditional statements in Javascript - IF-ELSE construct - Conditions in Javascript - Basics. Other conditionals in JavaScript

Control instructions are instructions that control the execution of program code. Typically, the executable code in a control instruction is called 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 in which they appear in the 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 execution 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 \u003d "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 \u003d 2; if (num \u003d\u003d 1) (alert ("num value:" + num);) else if (num \u003d\u003d 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 consider a syntactically equivalent form showing the nesting of if statements:

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

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 \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);

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.

      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

      Conditional Operators

      Conditional statements let you skip or execute other statements depending on the value of the specified expression. These operators are the decision points in the program and are sometimes also called branching operators.

      If you imagine that the program is a road, and the JavaScript interpreter is a traveler walking along it, then conditional statements can be thought of as intersections, where the program code forks into two or more roads, and at such intersections the interpreter must choose which road to take. ...

      If / else statement

      The if statement is a basic control statement that allows the JavaScript interpreter to make decisions, or more precisely, execute statements based on conditions. The if statement has two forms. First:

      if (expression) statement

      In this form, the expression is evaluated first. If the result is true, then the statement is executed. If the expression returns false, then the statement is not executed. For example:

      If (username \u003d\u003d null) // If username is null or undefined username \u003d "Alex"; // define it

      Note that the parentheses around the conditional expression are a required part of the if statement syntax.

      The second form of the if statement introduces the else clause, which is executed when the expression returns false. Its syntax is:

      if (expression) statement1 else statement2

      This form executes statement1 if the expression returns true, and statement2 if the expression returns false. For example:

      If (n \u003d\u003d 1) console.log ("Received 1 new message."); else console.log ("Received" + n + "new messages.");

      Else if statement

      The if / else operator evaluates the value of the expression and executes one or another piece of program code, depending on the result. But what if you need to execute one of many fragments? A possible way to do this is to use an else if statement. It is not formally a stand-alone JavaScript operator; this is just a common programming style that uses a repeating if / else statement:

      If (n \u003d\u003d 1) (// Execute block 1) else if (n \u003d\u003d 2) (// Execute block 2) else if (n \u003d\u003d 3) (// Execute block 3) else (// If neither one of the previous else statements was not executed, execute block 4)

      There is nothing special about this snippet. It is simply a sequence of if statements, where each if statement is part of the else statement of the previous statement.

      Switch statement

      The if statement creates branching in the program flow, and multi-position branching can be implemented with multiple else if statements. However, this is not always the best solution, especially if all branches depend on the value of the same expression. In this case, it is wasteful to re-evaluate the value of the same expression in multiple if statements.

      The switch statement is designed for just such situations. The switch keyword is followed by an expression in parentheses and a block of code in curly braces:

      switch (expression) (statements)

      However, the complete syntax of a switch statement is more complex than shown here. Various places in the block are marked with the keyword casefollowed by an expression and a colon character.

      When a switch statement is executed, it evaluates the value of the expression and then looks for a case label that matches that value (matching is determined with the identity operator \u003d\u003d\u003d). If a label is found, the code block is executed starting at the first statement following the case label. If no case label with matching value is found, execution starts from the first statement following the special label default:... If there is no default: label, the entire switch block is skipped.

      The operation of the switch statement is difficult to explain in words, the explanation looks much clearer with an example. The following switch statement is equivalent to the repeated if / else statements shown in the previous example:

      Switch (n) (case 1: // Execute if n \u003d\u003d\u003d 1 // Execute block 1 break; // Stop here case 2: // Execute if n \u003d\u003d\u003d 2 // Execute block 2 break; / / Stop here case 3: // Executed if n \u003d\u003d\u003d 3 // Execute block 3 break; // Stop here default: // If everything else doesn't work ... // Execute block 4 break; // Stop here )

      Pay attention to the keyword break at the end of each case block. The break statement transfers control to the end of the switch statement and continues execution of the statements that follow. The case statements in a switch statement only specify the starting point of the code being executed, but do not specify any ending points.

      If there are no break statements, the switch statement will start executing the block of code with the case label corresponding to the value of the expression and continue executing the statements until it reaches the end of the block. In rare cases, this is useful for writing code that jumps from one case label to the next, but 99% of the time, you should carefully end each case block with a break statement. (When using switch inside a function, you can use a return statement instead of break. Both of these statements terminate the switch statement and prevent jumping to the next case label.)

      Below is a more practical example of using a switch statement, it converts a value to a string in a way that depends on the type of the value:

      Function convert (x) (switch (typeof x) (// Convert a number to a hexadecimal integer case "number": return x.toString (16); // Return a quoted string case "string": return "" "+ x + "" "; // Any other type is converted in the usual way default: return x.toString ();)) console.log (convert (1067)); // Result "42b"

      Note that in the previous two examples, the case keywords were followed by numbers or string literals. This is how the switch statement is most often used in practice, but the ECMAScript standard allows you to specify arbitrary expressions after the case.

      The switch statement first evaluates the expression after the switch keyword and then the case expressions in the order in which they appear until a matching value is found. The fact of a match is determined using the \u003d\u003d\u003d identity operator, not using the \u003d\u003d equality operator, so the expressions must match without any type conversion.

      Because not all case expressions are evaluated each time a switch statement is executed, you should avoid using case expressions that have side effects, such as function calls and assignments. It is safest to limit your case expressions to constant expressions.

      As explained earlier, if none of the case expressions match the switch expression, the switch statement starts executing the statement labeled default :. If there is no default: label, the body of the switch statement is skipped entirely. Note that in the previous examples, the default: label appears at the end of the body of the switch statement after all case labels. This is a logical and usual place for it, but in fact it can be located anywhere within a switch statement.