Syntax if else. Conditional statements. bulleted list tags

In this example, we first declare four variables using keyword var, 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) ;

    )

    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 enclosed 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 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" );

    In this article we will look at the conditional and logical operators of the JavaScript language.

    JavaScript Conditional Statements

    Conditional operators are JavaScript (ECMAScript) operators that, depending on some condition, allow one or more specific instructions to be executed.

    Forms of conditional statements in JavaScript:

    • conditional if statement (with one branch);
    • conditional statement if...else (with two branches);
    • conditional statement else if... (with several branches);
    • ternary operator (?: );
    • switch selection statement.
    Conditional if statement

    The syntax of the if statement is:

    If (condition) statement

    The conditional if statement consists of:

    • keyword if ;
    • conditions (expressions in parentheses) that must evaluate to true or false (or be cast to one of these values);
    • instructions to be executed if the condition is true or evaluates to true.

    For example:

    If (true) count = 4;

    This example uses true as the condition. This means that the instruction count = 4 will always be executed. This example It is simply given to explain the principle of operation of the if statement, because it is devoid of any meaning.

    For example, let's increase the value of the votes variable by 1 if it (its type) is a number:

    If (typeof votes === "number") votes++;

    If multiple instructions need to be executed, they must be placed in curly braces:

    If (typeof votes === "number") ( votes++; console.log("Number of votes: " + votes); )

    If (typeof votes === "number") ( votes++; )

    If...else statement

    The if...else statement is used when it is necessary to execute some instructions if a condition is true, and others if it is false.

    Syntax:

    If (condition) ( one or more statements (will be executed when the condition is true or is reduced to true) ) else ( one or more statements (will be executed when the condition is false or is reduced to false) )

    For example, let's print a message to the console about whether the number is even or not:

    If (number % 2) ( console.log("The number is odd!"); ) else ( console.log("The number is even!"); )

    Rule for bringing a condition to true or false

    If the expression in the condition of an if statement is not true or false , then JavaScript will cast it to one of those values. This action he fulfills it using the so-called “lie rule”.

    Meaning of this rule: any expression is true except the following values:

    • false (false);
    • "" or "" (empty string);
    • NaN (special numeric data type “not a number”);
    • 0 (number “zero”);
    • null("empty" value);
    • undefined (“undefined” value).

    For example, let's display a welcome message in the browser console, depending on what value is stored in the nameUser variable:

    If (nameUser) ( console.log("Hello, " + name + "!"); ) else ( console.log("Hello, guest!"); )

    If the nameUser variable contains an empty string, then according to the lie rule, it will be cast to the value false. Consequently, the message “Hello, guest!” will be printed to the console. .

    And if, for example, the nameUser variable contains the string “Timur”, then the expression in the condition will be reduced to the value true. As a result, the console will display the message “Hello, Timur!” .

    else if... statement (multiple conditions)

    Syntax:

    If (condition1) (instructions 1) else if (condition2) (instructions 2) else if (condition3) (instructions 3 //...) else if (conditionN) (instructions N) else (instructions that will be executed if neither one of the conditions is not true or is not reduced to this value)

    Conditional (ternary) operator (?:)

    Ternary operator is a JavaScript operator that can be used when you need to execute one of two given expressions depending on a condition.

    Syntax:

    Condition? expression1: expression2

    The ternary operator consists of three operands that are separated using symbols? And: . The condition of the ternary operator is specified in the first operand. It can also be enclosed in parentheses. If the condition is true or will be reduced to this value, expression1 will be executed, otherwise expression 2 will be executed.

    For example:

    (number > 10) ? console.log("The number is greater than 10!") : console.log("The number is less than or equal to 10");

    JavaScript allows multiple ternary operators (?:):

    Var dayNumber = new Date().getDay(); day = (dayNumber === 0) ? "Sunday": (dayNumber === 1) ? "Monday" : (dayNumber === 2) ? "Tuesday" : (dayNumber === 3) ? "Wednesday" : (dayNumber === 4) ? "Thursday" : (dayNumber === 5) ? "Friday": (dayNumber === 6) ? "Saturday" : "Unknown day of the week"; console.log("Today " + day.toLowerCase() + ".");

    The above example, but using multiple notation of the if...else statement:

    Var dayNumber = new Date().getDay(); if (dayNumber === 0) ( day = "Sunday"; ) else if (dayNumber === 1) ( day = "Monday"; ) else if (dayNumber === 2) ( day = "Tuesday"; ) else if (dayNumber === 3) ( day = "Wednesday"; ) else if (dayNumber === 4) ( day = "Thursday"; ) else if (dayNumber === 5) ( day = "Friday"; ) else if (dayNumber === 6) ( day = "Saturday"; ) else ( day = "Unknown day of the week"; ) console.log("Today " + day.toLowerCase() + ".");

    switch statement

    The switch statement is designed to execute one of several instructions depending on the value of the expression. The choice of one or another option is determined by the strict equality of the result of the expression to the value of the case (case).

    Switch statement syntax:

    Switch (expression) ( case value1: // ... instructions that will be executed if the result of evaluating the expression is “value1” break; // optional instruction (if not used, the next command of the switch statement will be executed) case value2: // ... instructions that will be executed if the result of evaluating the expression is “value2” break // optional instruction (if not used, the next command of the switch operator will be executed) // ... case valueN: // . .. instructions that will be executed if the result of evaluating the expression is “valueN” break; // optional instruction (if not used, the next command of the switch statement will be executed) default: // instructions that will be executed if the result of the expression is not equal to more than one of the values)

    The default keyword is optional. It is used when you need to specify instructions that need to be executed if the result of an expression does not equal any value of the case (case).

    The break statement is optional. It is designed to interrupt the execution of a switch statement and transfer to control the instruction that comes after it.

    For example, let's display a message in the browser console about the number of candies:

    Var countCandyBoys = 1, countCandyGirls = 2, message; switch (countCandyBoys + countCandyGirls) ( case 1: message = "One candy"; break; case 2: case 3: message = "Two or three candies"; break; case 4: message = "Four candies"; break; default: message = "Not one, not two, not three or four candies"; ) // print a message to the console console.log(message);

    In the above example, the evaluated expression is 3. Therefore, the message = "Two or three candies" and break instructions will be executed. The break instruction will interrupt further execution of the switch statement and transfer control to the instruction that comes after it, i.e. console.log(message) . It will display the message “Two or three candies” in the console.

    For example, let's display the current day of the week in the console:

    Var day = ""; switch(new Date().getDay()) ( case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; day = "Friday"; break = "Saturday"; console.log("Today " + day.toLowerCase() + ".");

    An example that does not use the break statement:

    Var result = "success"; switch (result) ( case "success": console.log("Success!"); case "invalidCaptcha": console.log("Invalid Captcha!"); default: console.log("Error!"); )

    In this example, the switch statement expression is success. Therefore, the statement console.log("Success!") will be executed, which will print the message "Success!"

    to the console. But since there is no break statement after it, execution of the script will continue in the next version. Thus, instructions will be executed until a break is encountered on the path or the end of the switch statement is reached. As a result of running this example, 3 messages will be output to the console: “Success!” , “Invalid captcha!”

    and “Error!” .

    In some cases this behavior may be required, but not in this case. There was simply a mistake made here.

    Corrected example:

    Var result = "success"; switch (result) ( case "success": console.log("Success!"); break; case "invalidCaptcha": console.log("Invalid Captcha!"); break; default: console.log("Error!" ; )

    • Logical operators
    • JavaScript distinguishes between the following logical operators:
    • && - logical "AND";

    || - logical "OR"; ! -logical "NOT". If in

    logical expression

    operand1 && operand2 are boolean values, then the result of this expression will be true if each of them is true ; otherwise the value of this expression will be false .

    False && false // false true && false // false false && true // false true && true // true

    If the Boolean expression operand1 && operand2 uses non-Boolean values, the result of the expression will be operand1 if it can be cast to false ; otherwise the result of this expression will be operand2.

    5 && 0 // 0 1 && 5 // 5 "line" && undefined // undefined "line1" && "line2" // "line2"

    If in a logical expression operand1 || operand2 uses boolean values, then the result of this expression will be true if at least one of them is true ; otherwise the value of this expression will be false .

    False || false // false true || false // true false || true // true true || true // true

    The Boolean expression!operand1 will evaluate to true if operand1 is false or can be cast to that value; otherwise the result of this expression will be false .

    False // true !true // false !"string" // false !5 // false"

    Control instructions are instructions that control the execution of program code. Typically, the executing code in a control instruction is called the body of that instruction.

    Control instructions can be nested and can also be used inside other control instructions.

    Conditional instructions

    By default, the JavaScript interpreter executes instructions one after another in the order they appear in source code. In cases where the execution or non-execution of some instructions must depend on the fulfillment or non-fulfillment of some condition, conditional instructions are used.

    if statement

    The if statement has two forms. Syntax of the first form:

    The expression in parentheses is called the condition for executing an if statement, or condition for short. First, the value of the expression is calculated. The resulting value is implicitly converted to a Boolean type if necessary. If the result of evaluating the expression is true , then the statement is executed. If the expression returns false , then the statement is not executed:

    If (true) alert("Completed!"); if (false) alert("Will not execute!");

    The if syntax allows you to execute only one statement, but if you need to execute more than one statement you need to use a compound statement:

    If (true) ( ​​var str = "Hello!"; alert(str); )

    Syntax of the second form:

    If (expression) statement; else statement;

    The else keyword allows you to add a statement that is executed if the condition evaluates to false:

    If (false) alert("Fails"); else alert("Running");

    As already mentioned, control instructions can be nested, which allows you to create the following constructs:

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

    There's nothing special about this code. It is simply a sequence of statements, where each if statement is an else part of the previous if statement. This form of notation may not seem entirely clear at first glance, so let’s consider a syntactically equivalent form showing the nesting of if statements:

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

    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 an else keyword 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 piece of 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 you to check additional conditions until true is found or the else block is reached. The elseif/else if construct must be placed after the if statement and before else operator, if there is one.

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

    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, fully showing the nesting of structures: