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 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. He performs this action using the so-called “rule of lies.”

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"


Let's start learning about conditional statements in JavaScript. Here we will look at the If-Else construct. Translated into Russian, this condition reads as If-Then.

But before we start talking about conditions in JavaScript, let's look at how and where they occur in real life.

For example, if it is clear in the evening, we will go to the park.

if this car costs less than $1000, then I will buy it, etc.

Thus, as you probably already understood, the condition “If” and the consequence “Then” are encountered quite often in our lives. That is, our behavior in various situations mainly depends on certain conditions.

The same applies to programming languages. They have special constructs that allow you to set certain conditions and perform actions if the specified conditions are met or not met.

Let's try to implement some simple example of using conditional statements, or rather the If-Else construct in JavaScript.

First, let's look at how the If statement works in JavaScript.

To do this, below we will first give an example and then analyze it.

var weather = "clear" ; /* create a pogoda variable and assign it the value “clear” */

if(pogoda == "clear") /* create a condition: if pogoda equals "clear" - TRUE*/

( /* That... */

document.write();

My family and I go to the Park in the evening

What should you pay attention to in the example above?

First, on equal signs == and assignments = in JavaScript. They should be distinguished: that is, first we create a variable and assign a value to it. Then in the If condition we talk about equality.

Secondly, when talking about the fulfillment or non-fulfillment of a condition enclosed in curly braces (), it should be understood that the JavaScript language perceives the condition as either True or False. That is, if the condition is True, as in our case, then the action enclosed in curly braces () is performed.

If the condition is False, as in the example below, then the condition enclosed in curly braces () will not be executed.

var weather = "cloudy" ;

if(pogoda == "clear" ) /* now the condition is FALSE: pogoda does not equal "clear" */

document .write ("My family and I are going to the Park in the evening" );

This is how the conditional operator If works: if the condition is True, the action is performed, if False, the action will not be performed. It's simple.

Now let's talk about how the If-Else construct works in JavaScript. Else is translated as “Otherwise”.

Let's turn to real life again. In most cases, if any condition is met, then we do one thing. If it is not fulfilled - “Otherwise”, then we do something else.

Let's continue working with the examples given earlier.

If it's clear in the evening, we'll go to the park, otherwise (if it's cloudy) we will stay at home and watch TV.

Or if this car costs less than $1000, then I will buy it, otherwise (if it costs more) I will go on a trip with this money.

JavaScript also has this ability to provide an alternative ( do something else), if the condition is not met. In JavaScript, we can create similar conditions using the If-Else construct. Let's take an example.

var weather = "cloudy" ; /* assign the variable “pogoda” the value “cloudy” */

if(pogoda == "clear") /* create a condition: if pogoda equals "clear" - this is TRUE */

document .write ("My family and I are going to the Park in the evening" );

else /* otherwise - if pogoda does not equal "clear" - this is FALSE */

{
document.write("

" + "We stay at home - watch TV" );
}

We stay at home - watch TV

Let's look at the example given.

So, if the condition is True, then the action following the If statement, enclosed in curly braces () is performed.

If the condition is False, then the action following the Else statement is performed, also enclosed in curly braces ().

We looked at how the simple but often used If-Else construct works in JavaScript. And here, for the future, it should be said that no matter how complex the condition may be, what matters first is whether it is True or False.

To consolidate the material covered “Conditional statements in Javascript - IF-ELSE Construction”, let's look at another example.

Only now we use the If-Else condition when working with numbers.

var count = 10 ;

if(count = 3 ) /* create a condition: if the number of elements of the friends array is greater than or equal to 3, then....*/

document .write("This is a large array with at least 3 elements");

else /* otherwise... */

{
document .write ("This is a small array with less than 3 elements" );

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.

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

An else statement can be used in conjunction with an 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

Control instructions are instructions that control the execution of program code. Typically, the executing code in a control instruction is called the body of that instruction.

Control instructions can be nested and can also be used inside other control instructions.

Conditional instructions

By default, the JavaScript interpreter executes instructions one after another in the order they appear in the source code. In cases where the execution or non-execution of some instructions must depend on the fulfillment or non-fulfilment of some condition, conditional instructions are used.

if statement

The if statement has two forms. Syntax of the first form:

The expression in parentheses is called the condition for executing an if statement, or condition for short. First, the value of the expression is calculated. The resulting value is implicitly converted to a Boolean type if necessary. If the result of evaluating the expression is true , then the statement is executed. If the expression returns false , then the statement is not executed:

If (true) alert("Completed!"); if (false) alert("Will not execute!");

The if syntax allows you to execute only one statement, but if you need to execute more than one statement you need to use a compound statement:

If (true) ( ​​var str = "Hello!"; alert(str); )

Syntax of the second form:

If (expression) statement; else statement;

The else keyword allows you to add a statement that is executed if the condition evaluates to false:

If (false) alert("Fails"); else alert("Running");

As already mentioned, control instructions can be nested, which allows you to create the following constructs:

Var num = 2; if (num == 1) ( alert("num value: " + num); ) else if (num == 2) ( alert("num value: " + num); ) else ( alert("I don’t know this number !"); )

There is nothing special in this code. It is simply a sequence of statements, where each if statement is an else part of the previous if statement. This form of notation may not seem entirely clear at first glance, so let’s consider a syntactically equivalent form showing the nesting of if statements:

Var num = 2; if (num == 1) ( alert("num value: " + num); ) else ( if (num == 2) ( alert("num value: " + num); ) else ( alert("I don’t know this numbers!"); ) )