Conditional Statements in Javascript - IF-ELSE Construction - Conditions in Javascript - Basics. Conditional statements Examples with if in javascript

💖 Do you like it? Share the link with your friends

A conditional operator allows you to skip or execute a certain block of code depending on the result of calculating a specified expression - a condition. A conditional statement can be said to be a decision point in a program; sometimes it is also called a branch statement. If you imagine that a program is a road, and the PHP interpreter is a traveler walking along it, then conditional statements can be thought of as crossroads where the program code branches into two or more roads, and at such crossroads the interpreter must choose which road to take next .

if statement

The if statement is the simplest of the branch statements.

The syntax of the if statement is:

The if statement first evaluates the conditional expression specified in parentheses, the result of which is a Boolean value. If the result obtained is true, then the instruction is executed. If the expression returns false, then the instruction is not executed. An expression of any complexity can be used as a condition.

If the body of the if statement uses only one instruction, then enclosing it in curly braces is possible, but not necessary. However, if you need to execute more than one instruction in the body of an if statement, then these several instructions must be enclosed in curly braces. Please note that there should not be a semicolon after the closing curly brace.

The following code demonstrates the use of the if statement:

If statements can be nested within other if statements:

Pay attention to the last example: the instruction does not have to be written exactly under the if statement; if the instruction is not large in size, then it can be written in one line.

if else statement

And so we learned that the if statement allows you to execute instructions if the condition is true. If the condition is false, then no action is performed. However, it is often necessary to execute certain instructions if a certain condition is true and other instructions if the condition is false. It is for such cases that if else branching is used. It consists of an if statement followed by a block of statements and keyword else followed by another block of statements.

The syntax of the if else statement is:

The else statement is optional. The block of instructions located after else is executed by default, i.e. when the conditional expression in if returns false . The else statement cannot be used separately from the if statement. The else block should only appear after the if statement; it can be considered the default action.

Modifying our previous example slightly, we can see how the if else statement works if the condition returns false:

The if else statement can be nested. Such nested conditional statements occur quite often in practice. An if statement is nested if it is nested inside another if or else block. If your code uses multiple if statements in a row, the else always refers to the closest if:

The last else does not apply to if($a) because it is not in the inner block, so the closest one to it is if($i) . The else statement inside the block is related to if($b) because this if is the closest one to it.

elseif/else if construct

The if/else statement evaluates the value of a conditional expression and executes a particular fragment program code. But what if you need to execute one of many fragments? If you need to check several conditions in a row, then the elseif or else if construction is suitable for this (this is the same construction, just written differently). Formally, it is not an independent PHP construct - it is just a common programming style that consists of using repeated if/else statements. It allows additional conditions to be tested until true is found or the else block is reached. The elseif/else if statement must appear after the if statement and before the else statement, if there is one.

Here three conditions are checked and, depending on the value of the $username variable, different actions.

There's really nothing special about this piece. It is simply a sequence of if statements, where each if statement is part of the else clause of the previous if statement. For those who have encountered this form of notation for the first time and do not really understand how it works, we will rewrite the same example, only in an equivalent syntactic form that fully shows the nesting of structures:

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

Logical operators

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

  • && - Logical "AND"
  • || - "OR"
  • ! - "NOT"
  • > - L.O. more P.O.
  • >= - L.O. greater than or equal to P.O.
  • < - Л.О. меньше П.О.
  • = 5 && 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 with construct to shorten the program code. However, to display information we used the Popup function (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 conditional js if statement; they are relevant only when you need to execute not one line of code, but several.

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

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

    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 false . 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:

    Var b = 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 elseif 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

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsif...else
    Chrome 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

    Let's start learning about conditional statements in JavaScript. Here we will look at the If-Else construct. Translated into Russian, this condition reads as If-Then.

    But before we start talking about conditions in JavaScript, let's look at how and where they occur in real life.

    For example, if it is clear in the evening, we will go to the park.

    if this car costs less than $1000, then I will buy it, etc.

    Thus, as you probably already understood, the condition “If” and the consequence “Then” are encountered quite often in our lives. That is, our behavior in various situations mainly depends on certain conditions.

    The same applies to programming languages. They have special constructs that allow you to set certain conditions and perform actions if the specified conditions are met or not met.

    Let's try to implement some simple example of using conditional statements, or rather the If-Else construct in JavaScript.

    First, let's look at how the If statement works in JavaScript.

    To do this, below we will first give an example and then analyze it.

    var weather = "clear" ; /* create a pogoda variable and assign it the value “clear” */

    if(pogoda == "clear") /* create a condition: if pogoda equals "clear" - TRUE*/

    ( /* That... */

    document.write();

    My family and I go to the Park in the evening

    What should you pay attention to in the example above?

    First, on equal signs == and assignments = in JavaScript. They should be distinguished: that is, first we create a variable and assign a value to it. Then in the If condition we talk about equality.

    Secondly, when talking about the fulfillment or non-fulfillment of a condition enclosed in curly braces (), it should be understood that the JavaScript language perceives the condition as either True or False. That is, if the condition is True, as in our case, then the action enclosed in curly braces () is performed.

    If the condition is False, as in the example below, then the condition contained in curly braces() will not be executed.

    var weather = "cloudy" ;

    if(pogoda == "clear" ) /* now the condition is FALSE: pogoda does not equal "clear" */

    document .write ("My family and I are going to the Park in the evening" );

    This is how the conditional operator If works: if the condition is True, the action is performed, if False, the action will not be performed. It's simple.

    Now let's talk about how the If-Else construct works in JavaScript. Else is translated as “Otherwise”.

    Let's turn to real life again. In most cases, if any condition is met, then we do one thing. If it is not fulfilled - “Otherwise”, then we do something else.

    Let's continue working with the examples given earlier.

    If it's clear in the evening, we'll go to the park, otherwise (if it's cloudy) we will stay at home and watch TV.

    Or if this car costs less than $1000, then I will buy it, otherwise (if it costs more) I will go on a trip with this money.

    JavaScript also has this ability to provide an alternative ( do something else), if the condition is not met. In JavaScript, we can create similar conditions using the If-Else construct. Let's take an example.

    var weather = "cloudy" ; /* assign the variable “pogoda” the value “cloudy” */

    if(pogoda == "clear") /* create a condition: if pogoda equals "clear" - this is TRUE */

    document .write ("My family and I are going to the Park in the evening" );

    else /* otherwise - if pogoda does not equal "clear" - this is FALSE */

    {
    document.write("

    " + "We stay at home - watch TV");
    }

    We stay at home - watch TV

    Let's look at the example given.

    So, if the condition is True, then the action following the If statement, enclosed in curly braces () is performed.

    If the condition is False, then the action following the Else statement is performed, also enclosed in curly braces ().

    We looked at how the simple but often used If-Else construct works in JavaScript. And here, for the future, it should be said that no matter how complex the condition may be, what matters first is whether it is True or False.

    To consolidate the material covered “Conditional statements in Javascript - IF-ELSE Construction”, let's look at another example.

    Only now we use the If-Else condition when working with numbers.

    var count = 10 ;

    if(count = 3 ) /* create a condition: if the number of elements of the friends array is greater than or equal to 3, then....*/

    document .write("This is a large array with at least 3 elements");

    else /* otherwise... */

    {
    document .write ("This is a small array with less than 3 elements" );

    Reg.ru: domains and hosting

    The largest registrar and hosting provider in Russia.

    More than 2 million domain names in service.

    Promotion, domain mail, business solutions.

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

    Bootstrap framework: fast adaptive layout

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

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

    Layout to order and get paid.

    *Mouse over to pause scrolling.

    Back forward

    Functions and if-else conditions in JavaScript

    Often when using JavaScript there is a need to perform different actions when different conditions are met.

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

    The general syntax of an if-else construct is as follows:

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

    As an example, consider the following code:

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

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

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

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

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

    More difficult conditions if you can create simply by adding them, for example, to a 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 You can use so-called logical operators.

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

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

    The syntax is as follows:

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

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

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

    The syntax is as follows:

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

    Not is written as ! and is used for negation.

    For example: If there are either 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 and having the browser execute the code when it comes to it, you can make the script execute only when an event occurs.

    For example, you created JavaScript whose task is to change background color pages when you click on a specific button. In this case, you need to "tell" the browser that this script should not be executed simply because it is its turn.

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

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

    Look at this example of a script written as a function:

    function myfunction() ( alert("Welcome!"); )

    Click the button to see what this script does:

    If the line alert("Welcome!"); If it weren't written inside a function, it would be executed every time the browser reached that line. But since we wrote it inside a function, this line is not executed until we click the button.

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

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

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

    The general syntax for functions is as follows:

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

    Curly braces: ( and ) indicate the start and end of a function.

    A typical mistake when creating functions is inattention and ignoring the importance of character case. The word function must be exactly function . The Function or FUNCTION option will cause an error.

    In addition, the use of capital letters plays a role when specifying variable names. If you have a function named myfunction(), then an attempt to address her as Myfunction(), MYFUNCTION() or MyFunction() will cause an error.

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


    See also:



tell friends