Js is shorthand for if. JavaScript: if and else - conditional statements

Conditional statements

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

If you imagine that a program is a road, and the JavaScript 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/else statement

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

if (expression) statement

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

If (username == null) // If the username variable is null or undefined username = "Alex"; // define it

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

The second form of the if statement introduces an else clause that is executed when the expression evaluates to false. Its syntax is:

if (expression) statement1 else statement2

This form executes statement1 if the expression evaluates to true and statement2 if the expression evaluates to false. For example:

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

else if statement

The if/else statement evaluates the value of an expression and executes one or another piece of program code, depending on the result. But what if you need to execute one of many fragments? A possible way to do this is to use an else if statement. Formally, it is not a standalone JavaScript operator; This is just a common programming style of using a repeated if/else statement:

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

There's 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 statement.

switch statement

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

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

switch(expression) ( instructions )

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

When a switch statement is executed, it evaluates the value of the expression and then looks for a case label that matches that value (the match is determined using the identity operator ===). If the label is found, the block of code is executed, starting with the first statement following the case label. If a case label with a matching value is not found, execution begins with the first statement following the special label default: . If the default: label is missing, the entire switch statement block is skipped.

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

Switch(n) ( case 1: // Executed if n === 1 // Execute block 1 break; // Stop here case 2: // Executed if n === 2 // Execute block 2 break; / / Stop here case 3: // Execute if n === 3 // Execute block 3 break; // Stop here default: // If all else fails... // Execute block 4 break; // Stop here )

Note the break keyword at the end of each case block. The break statement causes control to be transferred to the end of the switch statement and the execution of the following statements to continue. Case statements in a switch statement specify only the starting point of the program code to be executed, but do not specify any end points.

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

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

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

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

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

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

As explained earlier, if no case expression matches a switch statement, the switch statement begins executing the statement labeled default:. If the default: label is missing, the body of the switch statement is skipped entirely. Note that in the previous examples, the default: label is included at the end of the body of the switch statement, after all the case labels. This is a logical and common place for it, but in fact it can be located anywhere within a switch statement.

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, we will go to the seaside, otherwise, if it is cloudy, we will sit at home.

This also happens very often in programming. There are two conditional statements for this: if-else and switch-case. In this article I will tell you about the if-else operator, and in the next article about switch-case.

The syntax of the if-else conditional statement is as follows:


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 the following 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 arises 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 appears 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 also would not be able to buy a car, because 50,000 is not more than 50,000. In order for the condition in this case to be true, we need to write a greater than or equal to 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 not necessary; if there is more than one operator in the block, then curly braces are required.

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

Inside if you can write any logical operations, be they 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 is equal to b AND c is equal to d"); document.write("Next line of code");

If - else if - else statement

After the if block, there may be one or more else if blocks, 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 sockets. 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 the house 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 equal to 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.

Shorthand for if else

The shorthand notation can be used when, depending on some 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 in variable x we ​​will write the following message, “Variable a is greater than variable b,” otherwise we will write that “Variable a is less than variable b.”

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

Variable a is greater than variable b

" : "

Variable a is less than variable b

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

That's all I wanted to tell you in this article. The conditional if-else statement is used in more ways than one in every script, so it is very important to know and understand it. In the next article I will tell you about another conditional operator switch-case.

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

    JavaScript has a conditional construct that affects the execution of the program. If (in English if) something exists, something is true, then do one thing, otherwise (in English else) - do something else.

    if statement

    Let's immediately look at how the if statement works; it is simple and does not require much explanation.

    If (condition) (code to execute if condition is true)

    It's simple: if the condition is true, then the code in the (...) block is executed.

    Var digit = 4; if (digit == 4) ( document.write("The value of the variable digit is 4."); )

    You can make a little strange code:

    Var digit = 4; if (true) ( ​​document.write("The condition is true."); )

    else statement

    The else statement can be used in conjunction with the if statement. It is translated as “otherwise” and specifies an alternative code.

    Var digit = 4; if (digit

    Pay attention to the different spelling of curly braces in this example for the if and else statements. It is not at all necessary to write it this way; both syntaxes are correct.

    After the else statement there can be a new if statement. This will check multiple conditions.

    Var digit = 4; if (digit

    JavaScript doesn't have an elseif statement (in one word) like PHP does.

    If you only need to execute one statement, then block curly braces (...) are not needed. In our example, you don’t have to write them:

    Var digit = 4; if (digit

    False in JavaScript

    The if (condition) statement evaluates and converts the condition (expression) in parentheses to a boolean type (true or false).

    Let's repeat that there is a lie in JavaScript.

    • Number 0 (zero).
    • Empty line "".
    • Boolean value false:)
    • The value is null.
    • The value is undefined.
    • The value is NaN (Not a Number).

    Everything else is true.

    A couple of possible errors:

    If ("false") document.write("This is true.
    "); if (false) document.write("This is true.

    ");

    Here you need to distinguish the string “false” (enclosed in quotes) from the Boolean value false.

    If (" ") document.write("This is true.
    "); else document.write("This is false.
    ");

    Here you need to distinguish the line " " (with a space inside) from the empty line "". A space inside a string makes it not empty, but containing a character. For the interpreter, the letter or space does not matter - a character is a character.

    Other conditionals in JavaScript
    • JavaScript switch construct.
    • Operator question mark

    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, you 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 the background color of the page when you click on a certain 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:

Publications on the topic