Javascript branching. Conditional statements

Let's return to our hares

Let's remember the task about hares and Mazai from the last chapter.
Without using conditions and actions performed (or not performed)
depending on the conditions, count the number of hares in the last
it won't be easy for the boat.

Let's add branching to the lastBoatRabbits function:

var lastBoatRabbits = function (totalRabbits) ( if (totalRabbits === 0) ( // return 0 ; ) else ( var restRabbits = totalRabbits % 6 ; if (restRabbits === 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 know for sure that there are no hares on the river).

And if the number of hares on the river is a multiple of 6, then the last boat will be fully loaded with hares.

What else could be improved in this program? I would use a separate variable,
storing the number of hares that fit in the boat, in case the grateful
the hares will give Mazai a bigger boat. You never know what suddenly.

function (totalRabbits ) ( if (totalRabbits === 0 ) ( return 0 ; ) else ( var restRabbits = totalRabbits % boatCapacity; if (restRabbits === 0 ) ( return boatCapacity; ) else ( return restRabbits; ) ) ); Branching Syntax

A branch may have a part that is executed if the condition is false,
or may not have it:

// Option with two branches: if (rainIsFalling) ( stayHome(); // If rainIsFalling == true, this part is executed) else ( walkInAPark(); // Otherwise, this part is executed) // Option with one branch: if ( musicIsPlaying) ( dance(); ) // If musicIsPlaying == false, program execution just moves on Conditions

The condition in if can be an expression comparing two numbers or strings,
using the operations == , > ,< , >= , 5 // => true 11< 6 // =>false 5 >= 5 // => true 3 != 3 // => false "abc" == "abc" // => true "abc" === "abc" // => true Variables as conditions : var condition = 10 > 5 ; if (condition) ( console .log("10 > 5" ); // Will be executed ) Logical operations on conditions

Multiple expressions that return a Boolean (or coercible to a Boolean) value
can be combined using logical operations. Such operations are called:
logical AND && , logical OR || and logical negation! .

true && true ; // => true false || false ; // => false !false ; // => true

Logical AND returns true only if both sides of it are true.
logical OR returns false only if both sides of it are false .
Negation returns false for true and, conversely, true for false .

According to Javascript rules, the values ​​0, null and undefined are cast to false.
However, getting the result && we get the first unreduced value, which
is cast to false , and the resulting result is || - first unreduced value,
which evaluates to true:

0 && true ; // => 0 6 || 7 || false ; // => 6 !0 ; // => true

Thus, the function returning the number of hares in the last boat could be rewritten as follows:

var boatCapacity = 6 ; var lastBoatRabbits = function (totalRabbits) ( return totalRabbits && (totalRabbits % boatCapacity || boatCapacity); ); Quests
  • Write a function fizzbuzz that takes a number parameter and:
    • For numbers that are multiples of three, returns "Fizz"
    • For numbers that are multiples of five, returns "Buzz"
    • For numbers that are multiples of fifteen (both three and five), returns "FizzBuzz"
    • Otherwise, returns the original number
  • Write a function iGoToNorth that takes a number parameter and determines whether the number passed to us is appropriate. The number is suitable if it is greater than 10, less than 30 and a multiple of 7.
  • 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 braces It is not necessary to put it, if there is more than one statement 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, whether they are 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 more, then we can connect to electrical network, all devices from home.

    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 negative number) then the third block of code will work.

    Shorthand for if else

    The shorthand notation can be used when, depending on a certain 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 than one 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.

    If programming were always linear, then it probably wouldn’t exist. After all, in almost any program there are various ramifications that depend on certain external or internal factors. Such branches are created using conditional operators, which I will tell you about in this article.

    The general form of a conditional statement in JavaScript is:

    If (condition) (
    //Operator block
    }
    else(
    //Operator block
    }

    First comes the if keyword, which tells the browser that what follows is a conditional statement. Inside the parentheses is a condition that returns true or false, respectively. If the expression in brackets was true ( true), then the first block of statements is executed if the condition is false ( false), then the block of statements in else is executed. Also, the else block is optional, and I will give such an example later.

    Let's now practice it in practice. Let's solve this problem: the user enters a number, and we display a message - it is greater or less than 5.


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

    Let's look at this example. With the first line we call the prompt function, which displays a window asking you to enter a number. Next, the user enters a number, which is written to the variable x. And then comes the condition, which I translate as follows: If x is less than 5, then display the message: "The entered number is less than five", otherwise display the message "The entered number is greater than five". Expression x< 5 возвращает либо true ( < 5 ) или false (x >= 5). Also note that we are not using curly braces. Why? Because we use only one operator (the alert() function). In principle, we can install them, and nothing will change, however, here they will be superfluous.

    However, our task contains a significant error. If the user enters "5", then we display the message "The entered number is greater than five", however, this is not entirely correct. So let's transform the condition this way:

    If(x< 5) alert ("Введённое число меньше пяти");
    else
    if (x == 5) alert ("You entered five");
    else alert("The number entered is greater than five");

    As you can see, the else block in the first condition has been transformed. In the else block, the equality of x and 5 is checked. And if this is so, then the corresponding message is displayed, otherwise, it is displayed that the number is greater than five. That is, a condition within a condition is completely normal. Also note that I still left out the curly braces since the if-else is a single statement. And when there is only one operator, the presence of parentheses is not necessary.

    Let's look at another example. Let's create a variable that will be true if the entered number is positive, and false if the number is negative.

    Var x = prompt("Enter a number");
    var positive = true;
    if(x< 0) positive = false;
    alert(positive);

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

    Var x = prompt("Enter a number");
    var positive = x< 0;

    In other words, we immediately assign the positive variable the result of comparing x and zero.

    Now let's talk about the so-called difficult 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 AND and || - logical OR. Let's write this condition:

    If ((x = 0)) (//block of statements)

    This condition (complex condition) will evaluate to true if and only if x = 0. Otherwise, false will be returned.

    Let's consider a complex condition with logical OR.

    If((x