Contacts

JavaScript Operator allows you to set the necessary program branches. JavaScript: IF and ELSE - Instructions for conditions. Logic Operations on Terms

Good day. In touch, Alexey Gulein. In the last article we disassembled creating cycles in javascript . In this article I would like to tell about conditional Operator in JavaScript. In general, all programming consists of conditions, and in all programming languages \u200b\u200b(JavaScript has not exceeded) there is a concept of a conditional operator. The meaning of the conditional operator It is that if the condition is performed, then these actions are made if it is not done - then do other actions. The general scheme of the conditional operator looks like this:

If (condition) (// block of operators); ELSE (// block of operators)

Let's immediately write any example: we will request a user's number and, if it is even, output "This is an even number", if not - "This is an odd":

Conditional operator JavaScript

If you dial this code, you will see that everything works. Now I will show you how important syntax in JavaScript. Remove the sign ";" Before ELSE and the code will immediately stop working. Therefore, always be careful. In one of the following articles, I will tell how to catch errors in javascript.
One conditional operator can insert into another. Let's add the verification that the user has made the number "0".

Conditional operator JavaScript

Now I will show you how to check several conditions. There is such a concept as a logical "and" (denoted by the symbols &&). There is also a concept logical "or" (denoted by symbols ||). Priority in logical "and" higher, i.e. First, check this condition, and then check the logical "or".
Let's analyze such an example: let us create a random number from 1 to 10. It is necessary to output the phrase "the desired number \u003d" and the number itself, if this number is not equal to 6 and more than 5 or more 1, but less than 4:

Conditional operator JavaScript

In this case, the desired numbers are: 2,3,7,8,9,10. Other numbers do not comply with the condition.
I also want to draw your attention to the operator "! \u003d", Which means "not equal." Finally, when drafting conditions, always pay attention to the layout of the brackets. Most errors are associated with their incorrect arrangement.

In everyday life, it is often necessary to make any decision, depending on which condition. For example, if the weather is warm on the weekend, we will eat on the sea, otherwise, if it is overcast, then sit down at home.

In programming, this is also found very often. For this exist Two conditional operators, it is 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.

The syntax of the conditional operator IF-ELSE following:


If the truth condition (true), the code is executed from the IF block, otherwise, if the condition is false, the code from the ELSE block is performed.

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

Var Money \u003d 35000; // Suppose we have 35,000 euros // the car we want to buy costs 50,000 euros. And such an IF condition arises (Money\u003e 50000) (Document.Write ("We can buy a car");) Else (Document.Write ("Not enough money for buying a car");)

We save the document, open it in the browser and see that this message "not enough money for buying a car was launched on the page. If we had more than 50,000 euros, I would execute the code from the IF block. If we were exactly 50,000 euros, we could also not buy a car, because 50,000 no more than 50,000. In order for the condition in this case, it is necessary to write a sign anymore or equal to (\u003e \u003d) .

Comment! Logical operation is equally written by two signs of equality (\u003d\u003d). There is also a logical operation less or equal to (

using figure brackets

If only one operator is present, the curly brackets should be installed, if the block is more than one operator, then the curly brackets are required.

The example above will work perfectly and without curious brackets, since only one operator is located in both blocks.

Inside if you can write any logical operations, whether they are simple or complex. You can use Operators and (&&) and or (||).

Comment! The presence of the ELSE block is not mandatory.

For example, if a is equal to b, and C is d, then we display the corresponding message, otherwise if there is no ELSE block, then we simply go further to the next line.

Var a \u003d 4, b \u003d 4, c \u003d 8, d \u003d 8; if ((a \u003d\u003d b) && (c \u003d\u003d d)) document.write ("A is equal to B and C is D"); Document.Write ("Next List of Code");

IF - ELSE IF - ELSE

After the IF block, one and more ELSE IF blocks can follow, and at the end already the ELSE block. It is convenient in the case when you need to use more than one condition.


For a better understanding, take some kind of example from everyday life. For example, we have a certain number of outlets. If we have only one outlet in the room, then we can connect only one device if two outlets can connect two devices and if more, we can connect to the electrical network, all devices from home.

We now turn to programming.

Var socket \u003d 2; // Number of sockets in the house IF (Socket \u003d\u003d 1) Document.Write ("

We can only connect one device

"); ELSE If (Socket \u003d\u003d 2) (Document.Write ("

We can connect only 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 realized that if Socket is 1, then the first block of code will work. If Socket is 2, then the second block of the code will work and if the Socket has any other value (even a negative number), then the third block code will work.

Abbreviated entry if ELSE

The abbreviated record can be used in the case when depending on the condition, the variable can obtain this or that value.


For example, if the value of the variable A is greater than the value of the variable B, then in the X variable we will write such a message, "variable a greater than the variable B", otherwise we write that "variable a less than the variable b".

Var a \u003d 50, b \u003d 100, x; x \u003d (a\u003e b)? "

Variable A. more variable B.

" : "

Variable A. less variable B.

"; // Display the resulting Document.Write (X) result;

That's all about what I wanted to tell you in this article. The conditional IF-ELSE statement is used than in each script, so it is very important to know it and understand. In the next article, I will tell you about another SWITCH-CASE conditioner.

Conditional operators

Conditional operators allow you to skip or perform other operators depending on the value of the specified expression. These operators are decision-making points in the program, and sometimes they are also called operators of "branching".

If you submit that the program is the road, and the javascript interpreter is a traveler, going through it, then conditional operators can be represented as an intersection, where the program code branches two or more roads, and at such intersections the interpreter must choose which road to move on .

IF / ELSE operator

The IF statement is a basic controller that allows the JavaScript interpreter to make solutions or, more precisely, perform the operators depending on the conditions. The IF operator has two forms. First:

if (expression) operator

In this form, the expression is first calculated. If the result is true, the operator is executed. If the expression returns a false value, the operator is not executed. For example:

If (username \u003d\u003d null) // If the username variable is NULL or undefined username \u003d "alex"; // Determine It

Please note that brackets around the conditional expression are mandatory part of the IF operator syntax.

The second form of the IF operator enters the ELSE design, which is performed in cases where the expression returns a false value. Its syntax:

if (expression) operator1 ELSE operator2

This form performs the operator1 if the expression returns the true value, and the operator2, if the expression returns a false value. For example:

If (n \u003d\u003d 1) Console.log ("1 new message received."); Else Console.log ("Received" + N + "new messages.");

Operator ELSE if.

The IF / ELSE statement calculates the expression value and performs one or another fragment of the 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 apply the ELSE IF statement. Formally, it is not an independent JavaScript operator; This is only a common programming style, which consists in applying the recurring IF / ELSE operator:

If (n \u003d\u003d 1) (// Perform block 1) ELSE if (n \u003d\u003d 2) (// Run block 2) ELSE if (n \u003d\u003d 3) (// Run block 3) ELSE (// if neither One of the previous ELSE statements was not executed, execute block 4)

In this fragment there is nothing special. This is just a sequence of IF operators, where each IF statement is part of the ELSE design of the previous operator.

SWITCH operator

The IF statement creates a branch in the program execution stream, and the multiposition branch can be implemented by several ELSE IF operators. 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 waste re-calculate the value of the same expression in several IF operators.

The SWITCH operator is designed for such situations. The Switch keyword should be expressed in brackets and block of code in curly brackets:

switch (expression) (instructions)

However, the full syntax of the SWITCH operator is more complicated than shown here. Different places in the block are labeled in a key word case.Behind which the expression and colon symbol should be.

When the SWITCH statement is performed, it calculates the value of the expression, and then searches for the Case label corresponding to this value (the correspondence is determined using the identity operator \u003d\u003d\u003d). If the label is found, the code block is running, starting from the first instruction following the case of the CASE. If the CASE label with the corresponding value is not found, execution begins with the first instruction following the special mark default:. If the default label: missing, the SWITCH statement unit is fully skipped.

The work of the SWITCH operator is difficult to explain in words, it looks much clearer the explanation on the example. The following SWITCH statement is equivalent to repeating IF / ELSE operators shown in the previous example:

Switch (n) (Case 1: // runs if n \u003d\u003d\u003d 1 // Run the block 1 break; // here stop Case 2: // Perform if N \u003d\u003d\u003d 2 // Run Block 2 Break; / / Here Start Case 3: // Performed if N \u003d\u003d\u003d 3 // Run Block 3 Break; // Stop Default: // If everything else does not fit ... // Run Block 4 Break; // )

Pay attention to the keyword break At the end of each CASE block. The BREAK operator leads to the transfer of control to the end of the SWITCH operator and continue the execution of the operators following. Case designs in the SWITCH statement set only the starting point of the program code performed, but do not specify any endpoints.

In the absence of BREAK operators, the SWITCH operator will start executing the code block with the CASE label corresponding to the expression value, and will continue to perform the operators until it reaches the end of the block. In rare cases, this is useful for writing a program code that goes from one CASE mark to the next one, but in 99% of cases it should be carefully completed each block of the CASE operator Break. (When using Switch inside the function instead of Break, you can use the RETURN statement. Both of these operators are used to complete the operation of the Switch operator and prevent transition to the next Case Tag.)

The following is a more practical example of using the SWITCH statement, it converts the value to a string in a method dependent on the type of value:

Function Convert (X) (Switch (TypeOF x) (// Convert a number to a hexadecimal integer CASE "Number": Return X.Tostring (16); // Return a string enclosed in Case "String": Return "" "+ x + "" "; // Any other type is converted by the usual way to Default: Return X.Tostring ();)) Console.log (Convert (1067)); // Result "42b"

Please note that in the two previous examples, the numbers or string literals followed the keywords. That is how the SWITCH statement is most often used in practice, but the ECMAScript standard allows you to specify arbitrary expressions after CASE.

The Switch operator first calculates the expression after the Switch keyword, and then CASE expressions in the order in which they are specified until the coincidence value is found. The fact of the coincidence is determined using the identity operator \u003d\u003d\u003d, and not using the equality operator \u003d\u003d, therefore, the expressions must match without any conversion of types.

Since each other execution of the SWITCH operator is calculated not all CASE expressions, the use of CASE expressions that have side effects, such as feature calls and assignments, should be avoided. Sostly all is limited in the expressions of CASE constant expressions.

As previously explained, if none of the CASE expressions do not correspond to the expression switch, the SWITCH operator starts executing the operator with the DEFAULT: Tag. If the default label: missing, the SWITCH operator's body is completely skipped. Please note that in previous examples, the default label: specified at the end of the SWITCH operator's body after all CASE marks. This is a logical and usual place for it, but in fact it can be located anywhere inside the SWITCH operator.

In this article, consider conditional and logical JavaScript operators.

JavaScript conditional statements

Conditional operators - These are the Operators of the JavaScript language (ECMAScript), which, depending on some condition, allow you to perform one or more specific instructions.

Forms of conditional operators in JavaScript:

  • conditional IF operator (with one branch);
  • conditional operator IF ... ELSE (with two branches);
  • conditional operator ELSE IF ... (with several branches);
  • terner operator (? :);
  • sWITCH selection operator.

Conditional operator if

IF operator syntax:

If (condition) instruction

The conditional IF statement consists of:

  • keyword if;
  • conditions (expressions in parentheses), which should be True or False (or be given to one of these values);
  • instructions that need to performIf the condition is true or is given to it.

For example:

If (true) Count \u003d 4;

In this example, the value is true. This means that the COUNT \u003d 4 instruction will always be performed. This example is simply given to explain the principle of operation of the IF operator, because He is deprived of any meaning.

For example, we will increase the value of the VOTES variable to 1, if it (its type) is a number:

If (Typeof votes \u003d\u003d\u003d "Number") votes ++;

If you need to perform several instructions, they must be placed in curly brackets:

If (Typeof votes \u003d\u003d\u003d "Number") (Votes ++; Console.log ("number of votes:" + votes);)

If (Typeof votes \u003d\u003d\u003d "Number") (votes ++;)

IF ... ELSE operator

The IF ... ELSE operator is used when it is necessary when you are truth than the condition to perform some instructions, and with others with falsehood.

Syntax:

If (condition) (one or more instructions (one or more instructions will be executed when the condition is true or given to true)) ELSE (one or more instructions (will be executed when the condition is false or is given to FALSE))

For example, withdraw a message about whether the number is even or not:

If (Number% 2) (Console.log ("Number of odd!");) ELSE (Console.log ("Number What!");)

The rule of the condition to True or False

If the expression in the IF statement condition is not equal to true or false, then JavaScript will lead it to one of these values. It performs this action using the so-called "lies rule".

The meaning of this rule: any expression is true, except for the following values.:

  • false (lie);
  • "" or "" (empty string);
  • Nan (special numeric data type "not number");
  • 0 (number "zero");
  • null ("empty" value);
  • undefined ("Uncertain" value).

For example, we will withdraw a welcome message to the browser console, depending on what value is stored in the variable NameUser:

IfUser) (Console.log ("Hi," + Name + "!");) ELSE (Console.log ("Hi, Guest!");)

If the NameUser variable will contain an empty string, then according to the rule of lies, it will be given to the value of False. Consequently, the message "Hi, Guest!" Will be displayed in the console .

And if, for example, the NameUser variable will contain the Timur string, the expression on the condition will be given to the value of True. As a result, the message "Hi, Timur!" Will appear in the console .

ELSE IF operator ... (several conditions)

Syntax:

If (condition1) (instructions 1) ELSE IF (condition2) (instructions 2) ELSE IF (condition3) (instructions 3 // ...) ELSE If (Condition N) ELSE (instructions that will be executed if neither One of the conditions is not equal to true or is not given to this value)

Conditional (ternary) operator (? :)

Terner operator - The JavaScript operator that can be used when it is necessary to perform one of the two given expressions depending on the condition.

Syntax:

Condition? Expression1: Expression2.

Are the ternary operator consists of three operands that are separated by symbols? and:. The Terchnary Operator's condition is set in the first operand. It can also be concluded in brackets. If the condition is true or will be given to this value, expression will be performed1, otherwise - expression 2.

For example:

(Number\u003e 10)? Console.log ("Number more than 10!"): Console.log ("Number less than or equal to 10");

In JavaScript, multiple ternary operators are allowed (? :):

Var DayNumber \u003d New Date (). GetDay (); Day \u003d (daynumber \u003d\u003d\u003d 0)? "Sunday": (daynumber \u003d\u003d\u003d 1)? Monday: (DayNumber \u003d\u003d\u003d 2)? Tuesday: (DayNumber \u003d\u003d\u003d 3)? "Wednesday": (DayNumber \u003d\u003d\u003d 4)? "Thursday": (daynumber \u003d\u003d\u003d 5)? "Friday": (daynumber \u003d\u003d\u003d 6)? Saturday: "Unknown day of the week"; Console.log ("Today" + Day.TolowerCase () + ".");

The above example, but using the multiple recording of the IF operator ... ELSE:

Var DayNumber \u003d New Date (). GetDay (); if (daynumber \u003d\u003d\u003d 0) (day \u003d "Sunday";) ELSE if (daynumber \u003d\u003d\u003d 1) (day \u003d "Monday";) ELSE if (daynumber \u003d\u003d\u003d 2) (Day \u003d "Tuesday";) ELSE If (daynumber \u003d\u003d\u003d 3) (day \u003d "environment";) ELSE if (daynumber \u003d\u003d\u003d 4) (day \u003d "Thursday";) ELSE if (daynumber \u003d\u003d\u003d 5) (Day \u003d "Friday"; ) ELSE if (daynumber \u003d\u003d\u003d 6) (Day \u003d "Saturday";) Else (Day \u003d "Unknown day of the week";) Console.log ("Today" + Day.TolowerCase () + ".");

SWITCH operator

The SWITCH statement is designed to perform one version of instructions from several depending on the expression value. The choice of one or another variant is determined by means of strict equality of the result of an expression value (CASE).

Syntax operator SWITCH:

SWITCH (Expression) (Case value1: // ... Instructions that will be executed if the result of the expression calculation is "value1" break; // Optional instruction (if it is not used, then the following command operator SWITCH) Case value2: // ... Instructions that will be executed if the result of the expression calculation is "value2" break; // Optional instruction (if it is not used, then the following command of the SWITCH operator) will be executed) // ... Case value N: //. .. Instructions that will be executed if the result of the expression calculation is "value" Break; // Optional Instruction (if it is not used, then the following command of the Switch operator) Default: // Instructions that will be executed if the result of the expression is not equals not one of the values)

The Keyword Default is optional. It is used when you need to specify the instructions that need to be performed if the result of the expression is not equal to any single option (CASE).

The BREAK instruction is optional. It is designed to interrupt the execution of the SWITCH operator and transfer the manual running after it.

For example, we will bring a message to the browser console on the number of candies:

Var countcandyboys \u003d 1, CountCandygirls \u003d 2, Message; Switch (CountCandyboys + CountCandygirls) (Case 1: Message \u003d "One Candy"; Break; Case 2: Case 3: Message \u003d "Two or Three Candies"; Break; Case 4: Message \u003d "Four Candies"; Break; Default: Message \u003d "Not alone, not two, not three and not four candy";) // Withdraw a message to the console Console.log (Message);

In the above example, the calculated expression is 3. Therefore, the MESSAGE \u003d "Two or three candy" and Break will be performed. The BREAK instruction will interrupt further execution of the SWITCH statement and will transmit the management of the instruction running after it, i.e. Console.log (Message). She will withdraw the message to the console "Two or three candy".

For example, we will bring out the current day of the week into the console:

Var Day \u003d ""; Switch (New Date (). GetDay ()) (Case 0: Day \u003d "Sunday"; Break; Case 1: Day \u003d "Monday"; Break; Case 2: Day \u003d "Tuesday"; Break; Case 3: Day \u003d "Wednesday"; Break; Case 4: Day \u003d "Thursday"; break; Case 5: Day \u003d "Friday"; Break; Case 6: Day \u003d "Saturday"; Break; Default: Day \u003d "Unknown day of the week";) Console.log ("Today" + Day.TolowerCase () + ".");

An example in which the Break instruction is not used:

Var Result \u003d "Success"; SWITCH (Result) (CASE "SUCCESS": CONSOLE.LOG ("SUCCESS!"); CASE "INVALIDCAPTCHA": CONSOLE.LOG ("Invalid Capper!"); Default: Console.log ("Error!");)

In this example, the expression of the SWITCH operator is success. Consequently, the Console.log instruction will be executed ("Success!"), Which will bring the message "Success!" in the console. But since after it there is no BREAK instruction, then the execution of the script will be continued in the following version. Thus, the instructions will be executed before those while still to meet Break or the end of the SWITCH operator will be achieved. As a result of this example, 3 messages will be displayed in the console: "Success!" . "Invalid captcha!" And "Error!" .

In some cases, it may be required that behavior, but not in this. An error is simply made here.

Fixed version of the example:

Var Result \u003d "Success"; Switch (Result) (CASE "SUCCESS": CONSOLE.LOG ("SUCCESS!"); BREAK; CASE "INVALIDCAPTCHA": console.log ("Invalid Capple!"); Break; Default: Console.log ("Error!" );)

Logic operators

JavaScript distinguish the following logical operators:

  • && - logical "and";
  • || - logical "or";
  • ! -Logic "not."

If boolean values \u200b\u200bare used in the Operand1 && Operand2 logical expression, the result of this expression will be True if each of them is true; Otherwise, the value of this expression will be the value of FALSE.

False && False // False True && False // False False && True // False True && True // True

If no boolean values \u200b\u200bare used in the Operand1 && Operand2 logical expression, then the result of this expression will be Operand1, if it can be given to FALSE; Otherwise, the result of this expression will be Operand2.

5 && 0 // 0 1 && 5 // 5 "String" && undefined // undefined "String1" && "String2" // "String2"

If in logical expression Operand1 || Operand2 used boolean values, the result of this expression will be true if at least one of them is true; Otherwise, the value of this expression will be the value of FALSE.

False || false // False True || False // True False || True // True True || True // True.

If in logical expression Operand1 || Operand2 uses not boolean values, the result of this expression will be Operand1, if it can be given to TRUE; Otherwise, the result of this expression will be Operand2.

5 || 0 // 5 1 || 5 // 1 "String" || undefined // "String" "String1" || "String2" // "String1"

The result of a logical expression! Operand1 will be true if Operand1 is false or can be given to this value; Otherwise, the result of this expression will be the value of FALSE.

False // True! True // False! "Row" // False! 5 // False "

JavaScript - Lesson 7. Branching in the program - IF operator

Very often there is a situation where we need to do any action depending on any condition. For example, we have an online clothing store. We ask the user who he (a man or woman) and, depending on the answer, displays a list of relevant goods (male or female). When writing such programs is used Conditional operator if. The syntax is as follows:

IF B (S1)
ELSE (S2)

Where B. - logical type expression, and S1. and S2. - Operators.

It works like this: the value of the expression is calculated. B.if it is true, then the operator is performed S1.if it is false, then the operator is running S2.. Line ELSE (S2) You can lower.

I think the example will be clearer. Let us have a form into which the user enters 3 values. We write a script that will determine the maximum of the numbers entered.

To begin with, write a form code in the HTML page:

JavaScript if

Now on the script.js page, write the function code:

fUNCTION MAXZNACH (OBJ) (var a \u003d 1 * obj.zn1.value; var b \u003d 1 * obj.zn2.value; var c \u003d 1 * obj.zn3.value; var m \u003d a; if (b\u003e m) m \u003d b; if (c\u003e m) m \u003d c; obj.res.value \u003d m;)

So, our function takes three values \u200b\u200bfrom the form, for the maximum ( m.) We are taking the value a.. Then we compare: if the value b. More maximum (i.e. a.), then the maximum becomes b.otherwise the maximum remains a. (Because expression in brackets is not true). Further, as comparing the following value. c. With maximum. The answer is displayed in the result field ( rES.).

In general, such a scenario could be written using the method max Object Math.considered in the past lesson, and the code would turn into shorter:

fUNCTION MAXZNACH (OBJ) (var a \u003d 1 * obj.zn1.value; var b \u003d 1 * obj.zn2.value; var c \u003d 1 * obj.zn3.value; obj.res.value \u003d math.max (Math .max (a, b), c);)

This is me to the fact that the programming is still creative, and one task can be solved in different ways. The task of the programmer find the most optimal option. But this is so, a lyrical retreat. Let's return to the IF conditional operator and consider a more interesting example. We write a script, which is the time of which, when you hover the mouse cursor on the image, it will increase by creating the effect of approximation.

How do you remember in HTML you can set the size of the inserted image. If the specified sizes are larger or less than the original, the browser will automatically pague the original under these sizes. This we use. Let us have such a picture:

The width of the original 302 pixel. We want that the picture was 102 pixels width on the page, and when you hover the cursor, up to 302 pixels increased. With the HTML page everything is clear:

JavaScript if

And in our function, in addition to the conditional operator, we will use the standard JavaScript function setTimeout.which causes a user function at a given time interval:

FUNCTION BIGPICT () (VAR W \u003d Document.tigr.width; if (w thus, the function checks the width of the picture ( width.) And, if it is less than 302 pixels, then increases this width of 10 pixels. Function setTimeout. Calls our function bigPict every half a second, thanks to which the size of the picture will increase as long as the condition w will not be false.

To visually make approximation more smoothly try to reduce the width of the width and time of reference to the function. Play with these numbers and find the most optimal.

Today, everyone, as a homework, add our scenario as the picture when the mouse cursor enters the initial values \u200b\u200b(i.e., 102 pixels). If it does not work, then download



Did you like the article? Share it