Contacts

Javascript If two conditions are executed to display a message. Conditional operators. Cyclic Operators of the JavaScript language - for

Lesson number 5.
IF branch operators in javascript

Branch operators Designed to ensure that the program can run this or that block of code, depending on the faithfulness of True or not faithful to FALSE conditions.

Branching operators There are five species, in this lesson we will look at two of them:
- Branch Operator IF
- Branch Operator IF ELSE

Runs the code if the condition returns TRUE.

As a condition, in branching operators, comparison or logical operations are usually performed.

The scheme of the IF branch operator is as follows:

If (condition) (code starts if the condition returns true)

We give an example with an IF branch operator:

// Create two variables VAR Numone; var numtwo; // assign variables numone \u003d 5; numtwo \u003d 3; If (Numone\u003e Numtwo) (Alert ("Condition Returned True");)

In the script, we created two variables Numone and NumtWo, assigned them numeric values \u200b\u200b5 and 3.

Then created a branch operator if, which compares the values \u200b\u200bof two variables. If the comparison operation returns True, the code will start the code located between the curly brackets. In our case, the window will appear with the message, the condition returned True. If the comparison operation returns False, then nothing happens.

Double layers //, are comment. After a double slash, you can write any text, the JavaScript language interpreter, will perceive it as a comment and will not be processed. As we remember, in languages \u200b\u200band, you can also create comments.

Branch Operator IF ELSEIt is designed to start a block of code, depending on the value that the condition returns: True or False

The IF ELSE Branch Operator Scheme is as follows:

If (condition) (code starts if the condition returns true) ELSE (the code will start if the condition returns false)

We give an example with the Branch Operator if Else:

Var numone; var numtwo; numone \u003d 5; numtwo \u003d 3; If (Numone\u003e Numtwo) (Alert ("Condition Returned True");) ELSE (Alert ("Condition Returned False");)

Assign the NUMTWO variable, the number is greater than 5, for example 7, then the condition returns false and the window will appear with the condition, the condition returned FALSE.

Let's go back to our hares

Recall the task about Zaitsev and Mazaya from last chapter.
Without the use of conditions and actions performed (or not executed)
depending on the conditions, calculate the number of hares in the last
the boat will not be easy.

Add a Lastboatrabbit branching to the poundation:

Var Lastboatrabbits \u003d. fUNCTION (TotalRabbitS)(if (TotalRabBits \u003d\u003d\u003d 0) (// Return 0;) ELSE (var restrabbits \u003d TotalRabBits% 6; if (restrabbits \u003d\u003d\u003d 0) (// Return 6;) ELSE (RETURN RESTRABBITS;)));

So, if there are no hares on the river, the last boat will not bring anyone (in fact, it will return almost immediately, because Grandfather will definitely know that there are no hares on the river).

And if the number of hares on the river is more 6, then the latter will be a boat completely loaded by hares.

What else could it be improved in this program? I would use a separate variable,
storen the number of hares placed in the boat, in case grateful
hares will give a big boat with a big boat. Like which suddenly.

fUNCTION (TotalRabbitS)(If (TotalRabBits \u003d\u003d\u003d 0) (Return 0;) ELSE (VAR RESTRABBITS \u003d TotalRabBits% Boatcapacity; if (restrabbits \u003d\u003d\u003d 0) (Return Boatcapacity;) ELSE (Return Restrabbits;)));

Syntax branching

Branching may have a part that is executed if the condition is incorrectly
and may not have it:

// Option with two branches: if (rainisfalling) (Stayome (); // If Rainisfalling \u003d\u003d True, this part is performed. ) ELSE (Walkinapark (); // otherwise this part is performed } // Option with one branch: if (musicisplaying) (dance ();) // If Musicisplaying \u003d\u003d False, the program execution simply goes on

Conditions

As a condition in IF, an expression of a comparison of two numbers or lines may appear
using operations \u003d\u003d,\u003e,< , >= , <= , != и === , любая переменная, которой
it was assigned a logical value and simply any value as a result of work
If will be reduced to a logical value.

Examples of comparison:

10\u003e 5 // \u003d\u003e True 11< 6 // => False 5\u003e \u003d 5 // \u003d\u003e True 3! \u003d 3 // \u003d\u003e False "ABC" \u003d\u003d "ABC" // \u003d\u003e True "ABC" \u003d\u003d\u003d "ABC" // \u003d\u003e True

Variables as a condition:

VAR CONDITION \u003d 10\u003e 5; If (CONSOLE .LOG ("10\u003e 5"); // will be executed }

Logic Operations on Terms

Several expressions returning a logical (or logical) values
you can combine with logical operations. Such operations are called:
logical and &&, logical or || and logical denial! .

True && True; // \u003d\u003e True False || false; // \u003d\u003e False! false; // \u003d\u003e True

Logical and returns true only if TRUE from both sides
logical or returns False only if it is false from both sides.
The denial returns false for true and, on the contrary, True for False.

According to the rules of JavaScript, the values \u200b\u200bof 0, null and undefined are given to FALSE.
However, getting the result && we will get the first integral value that
caused to False, and getting the result || - the first integral value
which is given to True:

0 && TRUE; // \u003d\u003e 0 6 || 7 || false; // \u003d\u003e 6! 0; // \u003d\u003e True

Thus, the function that returns the number of hares in the last boat could be rewritten so:

var boatcapacity \u003d 6; Var Lastboatrabbits \u003d. fUNCTION (TotalRabbitS)(Return TotalRabBits && (TotalRabBits% Boatcapacity || Boatcapacity););

Tasks

  1. Write the FizzBuzz feature that accepts the Number and:
    • For numbers, multiple three, returns "Fizz"
    • For numbers, multiple five, returns "buzz"
    • For numbers, multiple fifteen (at the same time three and five), returns "Fizzbuzz"
    • In other cases, returns the original number
  2. Write an Igotonorth poundation that accepts the Number parameter and determines whether the number is suitable for us. The number is suitable if it is greater than 10, less than 30 and more times 7.

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.

If the programming would always be linear, then it would probably not be it. After all, in almost any program there are various branching, which depend on certain external or internal factors. These are such branches are created using conditional operatorswhich in this article I will tell you.

General form conditional Operator in JavaScript such:

If (condition) (
// block of operators
}
eLSE (
// block of operators
}

First goes the keyword ifthat tells the browser, which is further a conditional operator. Inside the brackets indicates a condition that, accordingly, returns true. or false. If the expression in brackets was true. (true), then the first block of operators is performed if the condition false (false), then a block of operators in eLSE.. Also block eLSE. It is not obligatory, and then I will give such an example.

Let's now practice already in practice. Let us decide such a task: the user enters the number, and we display a report - more it or less 5 .


iF (X.< 5) alert ("Введённое число меньше пяти");

We will analyze this example. First string we call a function prompt.which displays the window asking you to enter a number. Further, the user enters the number that is written to the variable x.. And then there is a condition that I translate so: If x is less than 5, then display a message: "Inserted number is less than five", otherwise display the message "Entered number more than five". Expression x.< 5 Returns either true. ( < 5 ) or false (x\u003e \u003d 5). Also note that we do not use curly brackets. Why? Because we use only one operator (function alert ()). In principle, we can deliver them, and nothing will change, however, here they will be superfluous.

However, our task contains a significant error. If the user enters " 5 ", we have a message" The number entered more than five", However, this is not entirely correct. Therefore, let's transform the condition in this way:

IF (X.< 5) alert ("Введённое число меньше пяти");
eLSE.
if (x \u003d\u003d 5) Alert ("You have entered five");
ELSE Alert ("Entered number is more than five");

As you can see block eLSE. In the first condition transformed. In block eLSE. Checked for equality X and 5. And if so, the corresponding message is displayed, otherwise it is displayed that the number is greater than five. That is, the condition inside the condition is completely normal. Also note that I still did not put braces, because iF-ELSE. This is one operator. And when only one operator, the presence of brackets is optional.

Let's discern another example. Create a variable that will be true.if the entered number is positive and falseif the number is negative.

Var x \u003d prompt ("Enter the number");
vAR POSITIVE \u003d TRUE;
iF (X.< 0) positive = false;
alert (Positive);

This example uses a classic example when we take some variable and assign the default value to it. And if required, I change. In this case, we change the default value if the number is negative. However, this example could be written more beautiful:

Var x \u003d prompt ("Enter the number");
vAR POSITIVE \u003d X< 0;

In other words, we are variable positive. Immediately assign the result of comparison x. and zero.

Now let's talk about the so-called sophisticated conditions. In the examples above, we considered only simple conditions, however, there are also other conditions that consist of several conditions. And here two operations are used: && - logical I. and || - logical or. Let's write such a condition:

If ((x<= 5) && (x >\u003d 0)) (// block of operators)

This condition (complex condition) will give true.then and only when x.<= 5 И x >= 0 . Otherwise, returned false.

Consider a difficult condition with logical or.

If ((x<= 5) || (x == 6)) {//блок операторов}

You can translate it like this: if x.<= 5 ИЛИ x == 6 , then return true.Otherwise false.

The last thing I want to say that there are conditions that consist of several logical and or orAnd, sometimes, you have to strain your head very seriously to figure it out in such a condition.

That's all I wanted to say conditional operators in JavaScript. And then only practice is needed. Alas, but without practice, you will never learn how to use this operator, without knowing the knowledge of which it is simply meaningless. So come up with some simple task (on the similarity of the one that we decided above) and decide it.

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