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 false 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 ​​true 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 object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:

Varb = new Boolean(false); if (b) // this condition is truthy

Examples

Using if...else

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

Using else if

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

If (x > 50) ( /* do the right thing */ ) else if (x > 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 = 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 = 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 Explorer Operasafariandroid 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 supportYesSafari 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

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

Over 2 million domain names in service.

Promotion, mail for domain, solutions for business.

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

Bootstrap Framework: Fast Responsive Layout

Step by step video course on the basics adaptive layout in the Bootstrap framework.

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

Make up to order and get money.

*Mouseover to pause scrolling.

Back forward

Functions and if-else conditions in JavaScript

Often with using JavaScript there is a need to perform different actions under different conditions.

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

General Syntax if-else constructs next:

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

As an example, consider this code:

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

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

Also note that the double equal sign (==) is used for comparison.

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

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

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

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

For example:

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

Logical operators AND, OR and NOT

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

And written as && and is used when more than one condition needs to be checked for truth.

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

The syntax is the following:

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

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

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

The syntax is the following:

If (condition1 || condition2) ( action ) if (hour==11 || hour==10) ( alert("It's not noon yet!") );

Not written as ! and is used for negation.

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

The syntax is:

If (!(condition)) ( action ) if (!(hour==11)) ( alert("It's not 11 o'clock") );

Functions in JavaScript

Instead of just adding Javascript to the page so that the browser executes the code when it reaches it, you can make the script only run when an event fires.

For example, let's say you've created a JavaScript whose task is to change the background color of a page when a certain button is clicked. In this case, you need to "tell" the browser that this script should not be executed simply because the queue has reached it.

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

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

Look at given example script written as a function:

Click on the button to see what this script does:

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

The function call (i.e. the call to it) occurs in this line:

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

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

The general syntax for functions is as follows:

Function functionname(variable1, variable2,..., variableN) ( ​​// Here comes the body of the function, what it does )

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

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

In addition, the use capital letters also plays a role in naming variables. If you have a function named myfunction(), then an attempt to address it as myfunction(), MYFUNCTION() or MyFunction() will cause an error.

Liked the material and want to thank?
Just share with your friends and colleagues!


See also:

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

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

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

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


Questions for self-control:

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

Switch statement in javaScript - switch

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

Syntax:

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

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

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

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

Compare with operator IF:

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

How to group multiple options?

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

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

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

Example 4: Ask the user to enter a color. Send translation to English language entered color. For color "blue" and "blue" produce the same value.


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

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

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

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

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

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

  • Organize the output for those colors that are not provided by the program:
  • // ... default : alert( "We don't have information for this color") ) // end switch

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

  • Test the script in a browser.

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

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

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


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

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

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


Task Js 3_8. Ask the user for a number - the number of crows on the branch. Depending on the entered number (no more than 10), display a message: - Sitting on a branch 1 crow- Sitting on a branch 4 crows- Sitting on a branch 10 crows

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


Questions for self-control:

  1. In which case is it appropriate as conditional statement use the construct switch?
  2. What is the purpose of the default block in the statement switch?
  3. Is it necessary to use the break statement in the construction switch?
  4. How grouping is done for multiple value options in an operator switch?

Loop statements in javaScript - For

Syntax:

for(initial counter value; condition; counter increment) ( //..statement block.. )

Important: The javascript for loop is used when it is known in advance how many times the 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=0 - the loop counter starts from zero:
  • for(var i = 0; condition; counter increment) ( //.. statement block.. )

  • 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 = 0; condition; i++) ( //..statement block.. )

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

Consider an example of using a for loop in javascript:

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


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

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

  • Test the script in a browser.

Task Js 3_9. 1 before 15 .

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

Code snippet:

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

Loop exit statements break and continue in JavaScript. Operator exit

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

While the continue statement interrupts the execution of the current iteration of the loop, but, while continuing the execution of the loop from the next iteration.

Consider the operation of the break and continue statements using an example:

Example: Understand the code snippet algorithm. What will be output?

Code snippet:

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

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


✍ Solution:
  • In the third line of the example, there is a condition due to which the number 4 will not be displayed: operator continue will go 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 printed to the screen, since the output statement comes before the condition (on the 4th line). Having met break, the interpreter will exit the loop.
  • That. on the screen will be: 0 1 2 3 5 6 7 8 - each digit on a new line.

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

Exit Statement

The javasctipt language provides an operator for exiting program code - the exit operator.
Most often, the operator is used to exclude a user input error.


Consider an example:

Example 6: Ask the user to enter a number. If not a number, then display a message "A number is needed!" and stop the program.


✍ Solution:
  • Initialize Variable number the value entered by the user in the modal window:
  • var number = prompt("Please enter a number");

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

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

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

    isNaN function returns value true if the variable is not a number

  • By the "lie" rule organize a variable value check x. If the value is not numeric, print the corresponding remark and end the program:
  • if (x)( alert("Number needed!"); exit; // program exit )

  • To continue the program (if the entered value was a number), display the following window prompting for input:
  • alert("Enter the second number");// if you enter not a number, the operator 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. Which statements are intended to exit the loop and to interrupt it? Give examples of their use.
  3. What is the operator for? exit?

Is it possible to have multiple counters in one FOR?

An interesting work with the for loop is possible when using simultaneously two counters in a cycle.
Consider an example:

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


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

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

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

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

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

Page generation "on the fly": how is it?

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

Example 8:

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

Let's remember the tags:
numbered list tags:

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

bulleted list tags:

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

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

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

          • Initialize Variable Kolvo the value entered by the user in the modal window:
          • var kolvo=prompt("Enter number of points");

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

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

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

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

    1. Test the script in a browser.
    2. Task Js 3_11.
      Write a script that displays tags input(control elements) of different types, depending on the number entered:

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

      The number of displayed tags should also be requested.

      Let's remember the tags:

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

      Sample output:

      Task Js 3_12. Draw a 9x9 checkerboard using javascript for loops. "Drawing" the board follows the html tags for the table:

      Let's remember the tags:

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

      --

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

      Result:

      Additionally:

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

        -

      Result:


      Questions for self-control:

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

      Loop statements in javaScript - While

      The syntax of the while statement is:

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

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


      ✍ Solution:
      • Script listing:
      • 1 2 3 4 5 var a = 1 ; while (a< 1000 ) { a*= 2 ; alert(a) ; }

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

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

      • Test the result in a browser.

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

      Example:

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

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

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

      Task Js 3_13. What values ​​will the following code snippet output?

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


      Task Js 3_14. Write construction code X to a degree y using a while loop. Query variable values ​​and display the result with alert() .

      Add code:

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

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

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

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

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


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

      Prompt for a username until the user actually enters a username (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 unknown reason. Where to look for an 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, then it is possible to display the error on the screen.
      The error is stored in the e.message object.

      Consider the operation of the operator on an example:

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


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

        Try from English. - "try", thus, we put the try statement before 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 operator stores this error in the e object. In the future, it can be displayed in a dialog box - e.message .

      • Put the final message that you want to display regardless of whether there is an error in the code, put it in a finally block:
      • finally ( alert("finishing actions"); ) alert("after");

        If there is still an error, then the interpreter, after its output in our example, will switch to executing 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 in the construct is optional.


      Task Js 3_17. Run 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 language operators and constructs:

      Javascript conditional statements:

    6. if statement
    7. Conditional assignment (ternary operator)
    8. switch statement
    9. Loop statements:

    10. for loop
    11. while loop
    12. 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 response is a message "few" or "a lot of" depending on the entered answer. If the player guesses correctly, congratulations are displayed. If he does not guess, 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 appropriate to use a For In loop? Give an example of its use.
      2. What is the purpose of the try..catch statement?
      3. Explain the purpose of each try..catch statement block.

      In everyday life, it is often necessary to 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 statement, and in the next article about switch-case.

      Syntax of the if-else conditional statement next:


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

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

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

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

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

      using curly braces

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

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

      Inside if you can write any logical operations whether they are simple or complex. You can also use the AND (&&) and OR (||) operators.

      Comment! The presence of the else block is optional.

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

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

      if-else if-else statement

      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 socket 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 the house to the electrical network.

      Now let's move on to programming.

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

      We can only connect one device

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

      We can only connect two devices

      "); document.write("

      For example TV and laptop

      "); )else( document.write("

      We can connect all devices from home to the electrical network

      "); }

      Depending on the value of the socket variable, one or another block of code will work. 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 work, and if socket has any other value (even a negative number), then the third block of code will work.

      Short for if else

      An abbreviation can be used when, depending on a certain condition, a variable can receive one or another value.


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

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

      Variable a more variable b

      " : "

      Variable a less variable b

      "; //Output the result document.write(x);

      That's all I wanted to tell you in this article. The if-else conditional statement 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 another switch-case conditional statement.

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

      Logical operators

      Logical operators are used when checking a condition, in order not to be repeated, I will make an abbreviation: the left operand is L.O., and the right operand is P.O.

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

      Now consider the following script:

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

      As in the previous script, here I used the construction with to shorten the 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. Notice that we didn't use curly braces in this example. in the js if conditional statement, they are relevant only when you need to execute not one line of code, but several.

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

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