the Internet Windows Android

Functions and conditions if-else in JavaScript. Conditional Operators in JavaScript - Design IF-ELSE - Conditions in JavaScript - Basics IF ELSE JS Examples

Conditional operators

Conditional operators allow you to skip or perform other operators depending on the value of the specified expression. These operators are decision-making points in the program, and sometimes they are also called operators of "branching".

If you submit that the program is the road, and the javascript interpreter is a traveler, going through it, then conditional operators can be represented as an intersection, where the program code branches two or more roads, and at such intersections the interpreter must choose which road to move on .

IF / ELSE operator

The IF statement is a basic controller that allows the JavaScript interpreter to make solutions or, more precisely, perform the operators depending on the conditions. The IF operator has two forms. First:

if (expression) operator

In this form, the expression is first calculated. If the result is true, the operator is executed. If the expression returns a false value, the operator is not executed. For example:

If (username \u003d\u003d null) // If the username variable is NULL or undefined username \u003d "alex"; // Determine It

Please note that brackets around the conditional expression are mandatory part of the IF operator syntax.

The second form of the IF operator enters the ELSE design, which is performed in cases where the expression returns a false value. Its syntax:

if (expression) operator1 ELSE operator2

This form performs the operator1 if the expression returns the true value, and the operator2, if the expression returns a false value. For example:

If (n \u003d\u003d 1) Console.log ("1 new message received."); Else Console.log ("Received" + N + "new messages.");

Operator ELSE if.

The IF / ELSE statement calculates the expression value and performs one or another fragment of the 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 apply the ELSE IF statement. Formally, it is not an independent JavaScript operator; This is only a common programming style, which consists in applying the recurring IF / ELSE operator:

If (n \u003d\u003d 1) (// Perform block 1) ELSE if (n \u003d\u003d 2) (// Run block 2) ELSE if (n \u003d\u003d 3) (// Run block 3) ELSE (// if neither One of the previous ELSE statements was not executed, execute block 4)

In this fragment there is nothing special. This is just a sequence of IF operators, where each IF statement is part of the ELSE design of the previous operator.

SWITCH operator

The IF statement creates a branch in the program execution stream, and the multiposition branch can be implemented by several ELSE IF operators. 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 waste re-calculate the value of the same expression in several IF operators.

The SWITCH operator is designed for such situations. The Switch keyword should be expressed in brackets and block of code in curly brackets:

switch (expression) (instructions)

However, the full syntax of the SWITCH operator is more complicated than shown here. Different places in the block are labeled in a key word case.Behind which the expression and colon symbol should be.

When the SWITCH statement is performed, it calculates the value of the expression, and then searches for the Case label corresponding to this value (the correspondence is determined using the identity operator \u003d\u003d\u003d). If the label is found, the code block is running, starting from the first instruction following the case of the CASE. If the CASE label with the corresponding value is not found, execution begins with the first instruction following the special mark default:. If the default label: missing, the SWITCH statement unit is fully skipped.

The work of the SWITCH operator is difficult to explain in words, it looks much clearer the explanation on the example. The following SWITCH statement is equivalent to repeating IF / ELSE operators shown in the previous example:

Switch (n) (Case 1: // runs if n \u003d\u003d\u003d 1 // Run the block 1 break; // here stop Case 2: // Perform if N \u003d\u003d\u003d 2 // Run Block 2 Break; / / Here Start Case 3: // Performed if N \u003d\u003d\u003d 3 // Run Block 3 Break; // Stop Default: // If everything else does not fit ... // Run Block 4 Break; // )

Pay attention to the keyword break At the end of each CASE block. The BREAK operator leads to the transfer of control to the end of the SWITCH operator and continue the execution of the operators following. Case designs in the SWITCH statement set only the starting point of the program code performed, but do not specify any endpoints.

In the absence of BREAK operators, the SWITCH operator will start executing the code block with the CASE label corresponding to the expression value, and will continue to perform the operators until it reaches the end of the block. In rare cases, this is useful for writing a program code that goes from one CASE mark to the next one, but in 99% of cases it should be carefully completed each block of the CASE operator Break. (When using Switch inside the function instead of Break, you can use the RETURN statement. Both of these operators are used to complete the operation of the Switch operator and prevent transition to the next Case Tag.)

The following is a more practical example of using the SWITCH statement, it converts the value to a string in a method dependent on the type of value:

Function Convert (X) (Switch (TypeOF x) (// Convert a number to a hexadecimal integer CASE "Number": Return X.Tostring (16); // Return a string enclosed in Case "String": Return "" "+ x + "" "; // Any other type is converted by the usual way to Default: Return X.Tostring ();)) Console.log (Convert (1067)); // Result "42b"

Please note that in the two previous examples, the numbers or string literals followed the keywords. That is how the SWITCH statement is most often used in practice, but the ECMAScript standard allows you to specify arbitrary expressions after CASE.

The Switch operator first calculates the expression after the Switch keyword, and then CASE expressions in the order in which they are specified until the coincidence value is found. The fact of the coincidence is determined using the identity operator \u003d\u003d\u003d, and not using the equality operator \u003d\u003d, therefore, the expressions must match without any conversion of types.

Since each other execution of the SWITCH operator is calculated not all CASE expressions, the use of CASE expressions that have side effects, such as feature calls and assignments, should be avoided. Sostly all is limited in the expressions of CASE constant expressions.

As previously explained, if none of the CASE expressions do not correspond to the expression switch, the SWITCH operator starts executing the operator with the DEFAULT: Tag. If the default label: missing, the SWITCH operator's body is completely skipped. Please note that in previous examples, the default label: specified at the end of the SWITCH operator's body after all CASE marks. This is a logical and usual place for it, but in fact it can be located anywhere inside the SWITCH operator.

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 Trouthy or Falsy. Statement1 Statement That Is Executed IF Condition Is Truthy. CAN BE Any Statement, Including Further Nested If States. To Execute Multiple Statements, Use a Block Statement ((...)) to group thosee 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 States and Further Nested If States.

Description.

MultiPle If ... Else States 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 States. In General, IT IS A Good Practice to Always Use Block States, Especially in Code Involving Nested If States:

If (Condition) ELSE (States2)

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, NULL, 0, -0, NAN, OR THE EMPTY STRING (""), AND ANY OBUTY, 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 Trouthy

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) (/ * doo the right * /) ELSE if (x\u003e 5) (/ * doo the right of it * /) else (/ * do the right it * /)

ASSIGNMENT WITHIN THE CONDITIONAL EXPRESSION

IT 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) (/ * doo the right of it * /)

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)) (/ * doo the right of it * /)

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

Desktop.MobileServer
Chrome.Edge.Firefox.Internet Explorer.Opera.Safari.Android WebView.Chrome for AndroidFirefox for AndroidOpera for AndroidSafari On ios.Samsung 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

var a \u003d 10; VAR B \u003d (A\u003e 1)? 100: 200; Alert (b);

If condition a\u003e 1. True, then variable b. Assign a value 100 otherwise the variable b assign the value 200 .

JS 3_4 task. To complement the code: 3 Local variables are announced using the VAR keyword. It is necessary to assign the value of the next ternary statement in the MAX variable: if A is greater than b, then return A, otherwise we return b.
Code fragment:

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


Questions for self-control:

  1. What is the syntax of the ternary operator?
  2. How many arguments have a ternary operator?

Switching Operator in JavaScript - Switch

The Switch JavaScript operator serves to check the variable to a variety of values:

Syntax:

switch (variable or expression) (Case option1: //..block operators .. Break Case Option2: //..block operators .. Break Default: //..block operators ..)

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 operators corresponding to this case..

A block starting with the service word DEFAULT can be omitted. Block operators will be performed if none of the listed values \u200b\u200bin all case. Not suitable.

Important: The BREAK operator is required after each of the considered variable value (after each case.); If not to use it, then all 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 we take ... Break; Case 2: // if (a \u003d\u003d\u003d 2) Alert ("two"); // then we take ... Break; Default: // Else Alert ("Many"); // otherwise we take ...)

How to group several options?

To fulfill the same operators, a grouping of several case.. As in the example above:

Case 0: Case 1: Alert ("Zero or One"); Break; ...

At a \u003d 0 and a \u003d 1, the same operator is performed: alert ("zero or one");

Example 4: Send from user to enter color. Display translation into English input. For color "blue" and "blue" Submit the same value.


✍ Solution:
  • Create a web page with an HTML skeleton and tag script..
  • Initialize the variable color
  • var color \u003d prompt ("What color?");

    var color \u003d prompt ("What color?");

  • Check the value of the variable using the design switsh.By displaying each value - the corresponding translation:
  • switch (Color) (Case "Red": Alert ("Red"); Break; Case "Green": Alert ("Green"); Break; // ...

    If the variable colorit has the meaning of "red", then transfer the translation into the modal window - "Red" and exit the design (Break;). If the variable color It has the meaning of "green", to display in the modal window - "Green" and exit the design (Break;).

  • For flowers "blue" and "blue" Perform a grouping:
  • // ... Case "Blue": Case "Blue": Alert ("Blue"); Break; // ...

    If the variable colorit has the meaning of "blue" or variable colorit has the meaning of "blue", then display the translation into the modal window - "Blue" and exit the design (Break;).

  • Organize the output for those colors that are not provided by the program:
  • // ... Default: Alert ( "Y We have no information on this color")) // End of Switch

    // ... Default: Alert ("Y We do not have information about this color")) // End of Switch

  • Test script in the browser.

JS 3_6 task. Find and correct the errors in the following code fragment:

14 15 16 17 VAR Number \u003d Prompt ( "Enter the number 1 or 2:"); Switch (Case "1" (document.write (one ");); Break; Case" 2 "(document.write (" two ");); break; Default (Document.Write ( "You have entered a value other than 1 and 2") ; } ; }

vAR Number \u003d Prompt ("Enter the number 1 or 2:"); SWITCH (CASE "1" (document.write (one ");); break; case" 2 "(document.write (" two ");); Break; Default (Document.Write (" you introduced value other than 1 and 2 "););)


JS 3_7 task. What will be displayed on the screen when performing the next code?:

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 3_8 task. The user request the number - the number of raven on the branch. Depending on the number entered (not more than 10), output the message: - Sits on the branch 1 crow. - Sits on the branch 4 crows - Sits on the branch 10 Roron

  1. Depending on the introduced number, the end of the word changes "crow".
  2. To check the use of the Switch JavaScript operator.
  3. Save this page in the results folder (it is useful for further work).


Questions for self-control:

  1. In which case, it is advisable as a conditional operator to use the design switch?
  2. What is the Default block in the operator switch?
  3. Is it necessary to use the Break operator in the design switch?
  4. How the grouping is carried out for several options for values \u200b\u200bin the operator switch?

Cyclic Operators of the JavaScript language - for

Syntax:

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

Important: The cycle in JavaScript for is used when it is known in advance how many times cyclic actions should be repeated (how many iterations at the cycle)

  • As an initial value of the iteration meter, an assignment expression is used: for example, i \u003d 0 - the cycle counter starts from scratch:
  • for (var i \u003d 0; condition; the increment of the counter) (//..block operators ..)

  • As an increment of the counter, the step is indicated with which the meter should increase: for example, indicates that each cycle iteration will be accompanied by an increase in 1 :
  • for (var i \u003d 0; condition; I ++) (//..block operators ..)

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

Consider an example of using the FOR Cycle in JavaScript:

Example 5: Display the sequence of numbers 0 1 2 3 ... 9 , each digit - from a new line. 0 1 2 ... 8 9


✍ Solution:
  • To display the sequence of numbers, we will use the FOR cycle counter, which must change its value from 0 before 9 According to the sequence.
  • So, for the initial value of the cycle counter Set the value equal to 0 ; as cycle Conditions Set the final value - ii \u003d 9; Step counter must be equal 1 (I ++), since the difference between sequence members is one:
  • for (var i \u003d 0; i<10; i++) { document.write(i+"
    "); }

    In the example, the cycle counter values \u200b\u200bare displayed on the screen, since the increment of the I ++ counter, respectively, will appear on the screen 0 1 2 3 ... 9 , and each digit - from a new line (tag
    ).

  • Test script in the browser.

JS 3_9 task. 1 before 15 .

  1. As a sequence of numbers, use the cycle counter for.
  2. For a variable-adder, use the variable identifier sUM..

Code fragment:

For (Var i \u003d ...; ...; ...) (Sum \u003d Sum + ...;) ...

Cycle exit operators break and continue. in javascript. Operator EXIT.

The BREAK operator interrupts the entire body of the cycle, i.e. Exit the cycle to JavaScript.

While the Continue operator interrupts the execution of the current iteration of the cycle, but, while continuing the execution of the cycle from the following iteration.

Consider the work of Break and Continue operators on the example:

Example: Oblect the code fragment algorithm. What will be derived?

Code fragment:

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:
  • In the third line of the example there is a condition due to which the figure 4 Will not display: Operator continue.switch to the next iteration of the cycle without completing the current one.
  • In line number 5 exit from the cycle, but at the same time the figure 8 It will be displayed, since the output statement is up to the condition (in the 4th line). Meeting breakThe interpreter will complete the operation of the cycle.
  • So On the screen will be: 0 1 2 3 5 6 7 8 - Each digit from a new line.

JS 3_10 task. Withdraw the sum of all integers from 1 before 15 , eliminating from the total number of numbers 5 and 7 .

Exit operator

The Javasctipt language provides an exit operator from the program code - the EXIT statement.
Most often, the operator is used to exclude user entry error.


Consider an example:

Example 6: Request user enter a number. If not the number is entered, then display a message. "The number is necessary!" and stop the work of the program.


✍ Solution:
  • Initialize the variable number The value entered by the user in the modal window:
  • vAR Number \u003d Prompt ("Enter the number");

  • Using the PARSEINT function of the row conversion to an integer, check whether the value entered is the number:
  • number \u003d Parseint (Number); // Return Nan - not the number

    In the event that no number is entered, the function will return the Nan value (from the English. nOT A NUMBER - not number).

  • Check the value of the variable number Using the iSnan function:
  • x \u003d isnan (Number); // Return True if the value is not numeric

    Isnan function returns value true. In case the variable is not a number

  • By rules "Lie" Organize Variable Value Check X.. If the value is not numeric output the corresponding comment and complete the program:
  • if (x) (Alert ("Number!"); EXIT; // Exit the program)

  • To continue the program (if the entered value was number), output the following window with an input supply:
  • alert ("Enter the second number"); // When you enter, the operator is not executed

  • Test script in the browser.

Questions for self-control:

  1. List three cycle parameters for And explain their purpose.
  2. What operators are designed to exit the cycle and for its interrupt? Give examples of their use.
  3. For which the operator is intended eXIT?

Is there a few meters in one for?

Interesting work with a FOR cycle is possible when used at the same time two counters in the cycle.
Consider an example:

Example 7: Using the script, print the following pairs variable to three lines: i \u003d 0 j \u003d 2 i \u003d 1 j \u003d 3 i \u003d 2 j \u003d 4


✍ Solution:
  • In the FOR Cycle, organize two meters: Counter I for sequence 0 1 2 , meter j for sequence output 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 cycle now has two values \u200b\u200bthat are listed. through commas (for example, the first parameter with two values: i \u003d 0, j \u003d 2). The parameters themselves are listed through a comma(;).

  • To output from 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);)

Generation page "On the fly": How is it?

Before performing the following task, consider an example. dynamic Building HTML Page With javascript.

Example 8:

  • You must dynamically generate marked and numbered lists on the web page depending on the data entered by the user: request from the user to enter view of the list (numbered (digit 1) or marked (digit 2)) and then number of list items.
  • Depending on the answer, display tags or a marked or numbered list with the required number of items.
  • If a non-existent type of list is entered, then issue a message "Enter the correct type!" and exit a program ().

Recall Tags:
numerized list tags:

<oL\u003e <li\u003e <li\u003e <li\u003e </ ol\u003e

marked list tags:

var ListType \u003d Prompt ("Enter" 1 "- if the marked list," 2 "- if the numbered list");

  • Check the entered value: for a numbered list (digit 1) Display the tag
      , for labeled (digit 2) - tag
        . If another value is entered, output the remark and finish the program:

            ") ELSE (Alert (" Enter the correct type "); EXIT;)

          • Initialize the variable kolvo. The value entered by the user in the modal window:
          • var kolvo \u003d Prompt ("Enter the number of items");

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

          • Since the lists are closed with appropriate tags, depending on the list of the list, output 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 script in the browser.
    2. JS 3_11 task.
      Write a script that displays tags input(controls) of different types, depending on the figures entered:

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

      The number of derived tags should also be requested.

      Recall Tags:

      For 1 - text field: For 2 - Button: For 3 - Radio:

      An example of output:

      JS 3_12 task. Draw a 9x9 chess board using JavaScript For cycles. "Draw" board follows HTML tags for the table:

      Recall Tags:

      <table Border \u003d "1" width \u003d "30%"\u003e <tr\u003e <tD\u003e-</ TD\u003e -</ TD\u003e </ tr\u003e </ Table\u003e

      --

      • For drawing 9 lines, it is necessary to organize an external FOR cycle with a meter i.
      • To draw 9 cells in each line, it is necessary to organize an internal (embedded) FOR cycle with a j.
      • To draw tags cells and strings, use the Document.Write method.

      Result:

      Additionally:

      1. In the cells of the table, display the multiplication table using the cycle counters (I and J).
      2. The first row and the first column to withdraw with the red background (attribute of the BGCOLOR table cells):
        <tD BGCOLOR \u003d "RED"\u003e-</ TD\u003e

        -

      Result:


      Questions for self-control:

      1. Explain what the concept of "dynamic page building" means?
      2. What language design is most often used when building a page?

      Cyclic JavaScript - While Language Operators

      Whele operator syntax:

      while (condition) (//..block operators ..);

      Example: Disposal to the dialog box 1000 (2, 4, 8 ... 512). Use alert () method


      ✍ Solution:
      • Listing 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 → A composite assignment operation is used: a product combined with assignment, i.e. the same as a \u003d a * 2

      • Test the result in the browser.

      How do Break and Continue operators work in the While cycle?

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

      Decend degrees will be output to 128 inclusive, and value 64 will be missed. Those. In dialog boxes, we will see: 2 4 8 16 32 128

      JS 3_13 task. What values \u200b\u200bwill the following code fragment?

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


      JS 3_14 task. Write the construction code h. in degree y.Using the While cycle. Request values \u200b\u200bof variables and output the result using alert ().

      Complete 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 number of the number:

      1 2 3 4 5 6 7 8 9 10 11 12 13 VAR Counter \u003d Prompt ("Enter the number"); var factorial \u003d 1; Document.Write ( "Factorial numbers:" + 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 the number"); var factorial \u003d 1; Document.Write ("Factorial numbers:" + 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 3_16 task. Modify the program about entering the user name:

      Request the user's name until the user really enters the name (i.e., the field will really be filled and the Cancel key cannot be pressed). When the name is entered, then output "Hello, name!". Document.

      How to search for errors in javascript?

      In some cases, the code on the page does not work in incomprehensible for what reason. Where to look for a mistake? In such cases, you can apply the TRY..Catch statement.

      The Try..Catch operator is trying to perform a code fragment, and if there is an error in the code, then it is possible to give an error to the screen.
      The error is stored in the E.Message object.

      Consider the work of the operator using the example:

      Example: Write an error operator in the program. Check the presence of an error in the assumed erroneous code: if the error in the code is present - issue a message "Error processing: error name". After checking the erroneous operator, regardless of whether there is an error in the code, issue a message "Finishing actions"


      ✍ Solution:
      • As a message with an error, we use the Prompt () method, written with an error - promt (). Error message enclose in the TRY unit:
      • alert ("To"); Try (Promt ("Enter the number"); // Operator with an error)

        Try with English. - "Trying", thus, we put the TRY operator in front of the code fragment, which, perhaps, contains an error (in our case, there is really a mistake).

      • An error notification message should be placed in the Catch block:
      • 6 7 8 9 Catch (E) (Alert ( "Error processing:"+ E.Message); )

        catch (E) (Alert ("Error Processing:" + E.Message);)

        If the error is really there, then the Catch statement (from English. Catch ") saves this error in the E object. In the future, it can be displayed in the E.Message dialog box.

      • The final message that must be output regardless of whether the error is in the code, place it in the Finally block:
      • finally (alert ("final actions");) alert ("after");

        If there is still an error, then the interpreter after its output in our example will go to the execution of the Catch block, and then finally (from the English "Completion", "Finally"), which always will be completed, regardless of whether the error was or not. Even if an error occurs in the Catch block.

      Important: FINALLY block in design is optional.


      JS 3_17 task. Perform an example described above with the following modifications:

    3. Remove the FINALLY block and follow the code execution.
    4. Put instead of an erroneous operator unmistakable and see what the result will be.
    5. Summary:

      The lesson described the following JavaScript language operators and designs:

      JavaScript conditional operators:

    6. IF operator
    7. Conditional assignment (ternary operator)
    8. Switch switch operator
    9. Cycle operators:

    10. Cycle for
    11. While cycle
    12. Cycle Do ... While
    13. Cycle for ... in
    14. Final task JS 3_18.
      Create a game for two:

      1. The program asks for the first player to enter a number from 1 before 100 (The second player does not see the entered number). The second player then asks to guess the entered number. A message is displayed in response. "few" or "lot" Depending on the response entered. If a player is guessing, - a congratulation is displayed. If not guessing - the game continues (until the number is guessed).
      2. Calculate the number of attempts and give out the result when the number is solved.


      Questions for self-control:

      1. In which cases it is advisable to use the for in cycle? Name an example of its use.
      2. What is the purpose of the TRY..Catch statement?
      3. Explain the assignment of each TRY.Catch operator block.

      In this article, consider conditional and logical JavaScript operators.

      JavaScript conditional statements

      Conditional operators - These are the Operators of the JavaScript language (ECMAScript), which, depending on some condition, allow you to perform one or more specific instructions.

      Forms of conditional operators in JavaScript:

      • conditional IF operator (with one branch);
      • conditional operator IF ... ELSE (with two branches);
      • conditional operator ELSE IF ... (with several branches);
      • terner operator (? :);
      • sWITCH selection operator.

      Conditional operator if.

      IF operator syntax:

      If (condition) instruction

      The conditional IF statement consists of:

      • keyword if;
      • conditions (expressions in parentheses), which should be True or False (or be given to one of these values);
      • instructions that need to performIf the condition is true or is given to it.

      For example:

      If (true) Count \u003d 4;

      In this example, the value is true. This means that the COUNT \u003d 4 instruction will always be performed. This example is simply given to explain the principle of operation of the IF operator, because He is deprived of any meaning.

      For example, we will increase the value of the VOTES variable to 1, if it (its type) is a number:

      If (Typeof votes \u003d\u003d\u003d "Number") votes ++;

      If you need to perform several instructions, they must be placed in curly brackets:

      If (Typeof votes \u003d\u003d\u003d "Number") (Votes ++; Console.log ("number of votes:" + votes);)

      If (Typeof votes \u003d\u003d\u003d "Number") (votes ++;)

      IF ... ELSE operator

      The IF ... ELSE operator is used when it is necessary when you are truth than the condition to perform some instructions, and with others with falsehood.

      Syntax:

      If (condition) (one or more instructions (one or more instructions will be executed when the condition is true or given to true)) ELSE (one or more instructions (will be executed when the condition is false or is given to FALSE))

      For example, withdraw a message about whether the number is even or not:

      If (Number% 2) (Console.log ("Number of odd!");) ELSE (Console.log ("Number What!");)

      The rule of the condition to True or False

      If the expression in the IF statement condition is not equal to true or false, then JavaScript will lead it to one of these values. It performs this action using the so-called "lies rule".

      The meaning of this rule: any expression is true, except for the following values.:

      • false (lie);
      • "" or "" (empty string);
      • Nan (special numeric data type "not number");
      • 0 (number "zero");
      • null ("empty" value);
      • undefined ("Uncertain" value).

      For example, we will withdraw a welcome message to the browser console, depending on what value is stored in the variable NameUser:

      IfUser) (Console.log ("Hi," + Name + "!");) ELSE (Console.log ("Hi, Guest!");)

      If the NameUser variable will contain an empty string, then according to the rule of lies, it will be given to the value of False. Consequently, the message "Hi, Guest!" Will be displayed in the console .

      And if, for example, the NameUser variable will contain the Timur string, the expression on the condition will be given to the value of True. As a result, the message "Hi, Timur!" Will appear in the console .

      ELSE IF operator ... (several conditions)

      Syntax:

      If (condition1) (instructions 1) ELSE IF (condition2) (instructions 2) ELSE IF (condition3) (instructions 3 // ...) ELSE If (Condition N) ELSE (instructions that will be executed if neither One of the conditions is not equal to true or is not given to this value)

      Conditional (ternary) operator (? :)

      Terner operator - The JavaScript operator that can be used when it is necessary to perform one of the two given expressions depending on the condition.

      Syntax:

      Condition? Expression1: Expression2

      Are the ternary operator consists of three operands that are separated by symbols? and:. The Terchnary Operator's condition is set in the first operand. It can also be concluded in brackets. If the condition is true or will be given to this value, expression will be performed1, otherwise - expression 2.

      For example:

      (Number\u003e 10)? Console.log ("Number more than 10!"): Console.log ("Number less than or equal to 10");

      In JavaScript, multiple ternary operators are allowed (? :):

      Var DayNumber \u003d New Date (). GetDay (); Day \u003d (daynumber \u003d\u003d\u003d 0)? "Sunday": (daynumber \u003d\u003d\u003d 1)? Monday: (DayNumber \u003d\u003d\u003d 2)? Tuesday: (DayNumber \u003d\u003d\u003d 3)? "Wednesday": (DayNumber \u003d\u003d\u003d 4)? "Thursday": (daynumber \u003d\u003d\u003d 5)? "Friday": (daynumber \u003d\u003d\u003d 6)? Saturday: "Unknown day of the week"; Console.log ("Today" + Day.TolowerCase () + ".");

      The above example, but using the multiple recording of the IF operator ... ELSE:

      Var DayNumber \u003d New Date (). GetDay (); if (daynumber \u003d\u003d\u003d 0) (day \u003d "Sunday";) ELSE if (daynumber \u003d\u003d\u003d 1) (day \u003d "Monday";) ELSE if (daynumber \u003d\u003d\u003d 2) (Day \u003d "Tuesday";) ELSE If (daynumber \u003d\u003d\u003d 3) (day \u003d "environment";) ELSE if (daynumber \u003d\u003d\u003d 4) (day \u003d "Thursday";) ELSE if (daynumber \u003d\u003d\u003d 5) (Day \u003d "Friday"; ) ELSE if (daynumber \u003d\u003d\u003d 6) (Day \u003d "Saturday";) Else (Day \u003d "Unknown day of the week";) Console.log ("Today" + Day.TolowerCase () + ".");

      SWITCH operator

      The SWITCH statement is designed to perform one version of instructions from several depending on the expression value. The choice of one or another variant is determined by means of strict equality of the result of an expression value (CASE).

      Syntax operator SWITCH:

      SWITCH (Expression) (Case value1: // ... Instructions that will be executed if the result of the expression calculation is "value1" break; // Optional instruction (if it is not used, then the following command operator SWITCH) Case value2: // ... Instructions that will be executed if the result of the expression calculation is "value2" break; // Optional instruction (if it is not used, then the following command of the SWITCH operator) will be executed) // ... Case value N: //. .. Instructions that will be executed if the result of the expression calculation is "value" Break; // Optional Instruction (if it is not used, then the following command of the Switch operator) Default: // Instructions that will be executed if the result of the expression is not equals not one of the values)

      The Keyword Default is optional. It is used when you need to specify the instructions that need to be performed if the result of the expression is not equal to any single option (CASE).

      The BREAK instruction is optional. It is designed to interrupt the execution of the SWITCH operator and transfer the manual running after it.

      For example, we will bring a message to the browser console on the number of candies:

      Var countcandyboys \u003d 1, CountCandygirls \u003d 2, Message; Switch (CountCandyboys + CountCandygirls) (Case 1: Message \u003d "One Candy"; Break; Case 2: Case 3: Message \u003d "Two or Three Candies"; Break; Case 4: Message \u003d "Four Candies"; Break; Default: Message \u003d "Not alone, not two, not three and not four candy";) // Withdraw a message to the console Console.log (Message);

      In the above example, the calculated expression is 3. Therefore, the MESSAGE \u003d "Two or three candy" and Break will be performed. The BREAK instruction will interrupt further execution of the SWITCH statement and will transmit the management of the instruction running after it, i.e. Console.log (Message). She will withdraw the message to the console "Two or three candy".

      For example, we will bring out the current day of the week into the console:

      Var Day \u003d ""; Switch (New Date (). GetDay ()) (Case 0: Day \u003d "Sunday"; Break; Case 1: Day \u003d "Monday"; Break; Case 2: Day \u003d "Tuesday"; Break; Case 3: Day \u003d "Wednesday"; Break; Case 4: Day \u003d "Thursday"; break; Case 5: Day \u003d "Friday"; Break; Case 6: Day \u003d "Saturday"; Break; Default: Day \u003d "Unknown day of the week";) Console.log ("Today" + Day.TolowerCase () + ".");

      An example in which the Break instruction is not used:

      Var Result \u003d "Success"; SWITCH (Result) (CASE "SUCCESS": CONSOLE.LOG ("SUCCESS!"); CASE "INVALIDCAPTCHA": CONSOLE.LOG ("Invalid Capper!"); Default: Console.log ("Error!");)

      In this example, the expression of the SWITCH operator is success. Consequently, the Console.log instruction will be executed ("Success!"), Which will bring the message "Success!" in the console. But since after it there is no BREAK instruction, then the execution of the script will be continued in the following version. Thus, the instructions will be executed before those while still to meet Break or the end of the SWITCH operator will be achieved. As a result of this example, 3 messages will be displayed in the console: "Success!" . "Invalid captcha!" And "Error!" .

      In some cases, it may be required that behavior, but not in this. An error is simply made here.

      Fixed version of the example:

      Var Result \u003d "Success"; Switch (Result) (CASE "SUCCESS": CONSOLE.LOG ("SUCCESS!"); BREAK; CASE "INVALIDCAPTCHA": console.log ("Invalid Capple!"); Break; Default: Console.log ("Error!" );)

      Logic operators

      JavaScript distinguish the following logical operators:

      • && - logical "and";
      • || - logical "or";
      • ! -Logic "not."

      If boolean values \u200b\u200bare used in the Operand1 && Operand2 logical expression, the result of this expression will be True if each of them is true; Otherwise, the value of this expression will be the value of FALSE.

      False && False // False True && False // False False && True // False True && True // True

      If no boolean values \u200b\u200bare used in the Operand1 && Operand2 logical expression, then the result of this expression will be Operand1, if it can be given to FALSE; Otherwise, the result of this expression will be Operand2.

      5 && 0 // 0 1 && 5 // 5 "String" && undefined // undefined "String1" && "String2" // "String2"

      If in logical expression Operand1 || Operand2 used boolean values, the result of this expression will be true if at least one of them is true; Otherwise, the value of this expression will be the value of FALSE.

      False || false // False True || False // True False || True // True True || True // True.

      If in logical expression Operand1 || Operand2 uses not boolean values, the result of this expression will be Operand1, if it can be given to TRUE; Otherwise, the result of this expression will be Operand2.

      5 || 0 // 5 1 || 5 // 1 "String" || undefined // "String" "String1" || "String2" // "String1"

      The result of a logical expression! Operand1 will be true if Operand1 is false or can be given to this value; Otherwise, the result of this expression will be the value of FALSE.

      False // True! True // False! "Row" // False! 5 // False "