Computer literacy, assistance and repair

Js shorthand for if. Functions and if-else conditions in JavaScript

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”.

The meaning of this rule: any expression is true, except for 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 the Boolean expression operand1 && operand2 uses Boolean values, the expression evaluates to true if each 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

If in a logical expression operand1 || operand2 uses non-Boolean values, the result of this expression will be operand1 if it can be cast to true ; otherwise the result of this expression will be operand2.

5 || 0 // 5 1 || 5 // 1 "line" || undefined // "string" "string1" || "line2" // "line1"

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"

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 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 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 that fully shows the nesting of structures:

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 to in this case was true, then you 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 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 an 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.

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

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

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

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


Questions for self-control:

  • What is the syntax of the ternary operator?
  • How many arguments does the ternary operator have?
  • Switch operator in javascript - switch

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

    Syntax:

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

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

    The block starting with the service word default can be omitted. The block statements will be executed if none of the listed values ​​are present in all case doesn't fit.

    Important: The break statement is required after each considered variable value (after each case); if you do not use it, then all the statements below will be printed

    Compare with the operator IF:

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

    How to group several 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: Prompt the user to enter a color. Output the English translation of the 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 using a construct sweat, 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 display the translation in the modal window - “red” and exit the structure (break;). If the variable color has the value “green”, then display the translation in the modal window - “green” and exit the structure (break;).

    • For flowers "blue" And "blue" perform 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 in the modal window - “blue” and exit the structure (break;).

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

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

    • Test the script in a browser.

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

    14 15 16 17 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" ) ; ) ; )

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


    Js task 3_7. What will be displayed on the screen when running the following code?:

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


    Js task 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 the message: - 1 crow is sitting on a branch - 4 crows are sitting on a branch - 10 crows are sitting on a branch

  • Depending on the number entered, the ending of the word changes "crow".
  • To check, use the javascript Switch operator.
  • Save this page in your results folder (it will be useful for future work).

  • Questions for self-control:

  • In what case is it advisable to use the construction as a conditional operator switch?
  • What is the purpose of the default block in the statement? switch?
  • Is it necessary to use the break statement in a construction? switch?
  • How to group for multiple value options in a statement switch?
  • Cyclic operators JavaScript language- For

    Syntax:

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

    Important: The javascript for loop is used when it is known in advance how many times cyclic actions should be repeated (how many iterations does the loop have)

    • 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) ( //..block of statements.. )

    • The increment of the counter specifies the step with which the counter should increase: for example, it indicates that each iteration of the loop will be accompanied by its increase by 1:
    • for(var i = 0; condition; i++) ( //..block of statements.. )

    • The loop condition is the final value of the counter: for example, i10, stops the loop:
    • for(var i = 0; i

    Related publications