Functions and if-else conditions in JavaScript. Conditional statement if else Js conditional statement

Conditional statements

Conditional statements allow you to skip or execute other statements depending on the value of a specified expression. These statements are decision points in a program and are sometimes also called branch operators.

If you imagine that a program is a road, and the JavaScript 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/else statement

The if statement is a basic control statement that allows the JavaScript interpreter to make decisions, or more accurately execute statements, based on conditions. The if statement has two forms. First:

if (expression) statement

In this form, the expression is first evaluated. If the result obtained is true, then the statement is executed. If the expression returns false, then the statement is not executed. For example:

If (username == null) // If the username variable is null or undefined username = "Alex"; // define it

Note that parentheses around a conditional expression are a required part of the if statement syntax.

The second form of the if statement introduces an else clause that is executed when the expression evaluates to false. Its syntax is:

if (expression) statement1 else statement2

This form executes statement1 if the expression evaluates to true and statement2 if the expression evaluates to false. For example:

If (n == 1) console.log("1 new message received."); else console.log("Received " + n + " new messages.");

else if statement

The if/else statement evaluates the value of an expression and executes a particular fragment program code, depending on the result. But what if you need to execute one of many fragments? Possible way to do this is to use the else if statement. Formally, it is not a standalone JavaScript operator; This is just a common programming style of using a repeated if/else statement:

If (n == 1) ( // Execute block 1 ) else if (n == 2) ( // Execute block 2 ) else if (n == 3) ( // Execute block 3 ) else ( // If neither one of the previous else statements was not executed, execute block 4)

There's 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 statement.

switch statement

An if statement creates a branch in the flow of the program, and multi-state branching can be implemented using several else if statements. However this is not always best solution, especially if all branches depend on the value of the same expression. In this case, it is wasteful to re-evaluate the same expression in multiple if statements.

The switch statement is designed specifically for such situations. The switch keyword is followed by an expression in parentheses and a block of code in curly braces:

switch(expression) ( instructions )

However full syntax The switch statement is more complex than shown here. Various places in the block are marked with a keyword case followed by an expression and a colon character.

When a switch statement is executed, it evaluates the value of the expression and then looks for a case label that matches that value (the match is determined using the identity operator ===). If the label is found, the block of code is executed, starting with the first statement following the case label. If a case label with a matching value is not found, execution begins with the first statement following the special label default:. If the default: label is missing, the entire switch statement block is skipped.

The operation of the switch statement is difficult to explain in words; the explanation is much clearer with an example. The following switch statement is equivalent to the repeated if/else statements shown in the previous example:

Switch(n) ( case 1: // Executed if n === 1 // Execute block 1 break; // Stop here case 2: // Executed if n === 2 // Execute block 2 break; / / Stop here case 3: // Execute if n === 3 // Execute block 3 break; // Stop here default: // If all else fails... // Execute block 4 break; // Stop here )

Pay attention to the keyword break at the end of each case block. The break statement causes control to be transferred to the end of the switch statement and the execution of the following statements to continue. Case statements in a switch statement specify only the starting point of the program code to be executed, but do not specify any end points.

If there are no break statements, the switch statement will begin executing the block of code with the case label corresponding to the value of the expression and continue executing the statements until it reaches the end of the block. In rare cases, this is useful for writing code that moves from one case label to the next, but in 99% of cases you should carefully end each case block with a break statement. (When using a switch inside a function, you can use a return statement instead of a break. Both of these statements serve to terminate the switch statement and prevent it from going to the next case label.)

Below is a more practical example of using the switch statement, it converts a value to a string in a way that depends on the type of the value:

Function convert(x) ( switch(typeof x) ( // Convert a number to a hexadecimal integer case "number": return x.toString(16); // Return a quoted string case "string": return """ + x + """; // Any other type is converted in the usual way default: return x.toString(); ) ) console.log(convert(1067)); // Result "42b"

Note that in the previous two examples, the case keywords were followed by numbers or string literals. This is how the switch statement is most often used in practice, but the ECMAScript standard allows you to specify arbitrary expressions after the case.

The switch statement first evaluates the expression after the switch keyword, and then the case expressions in the order in which they are specified, until a matching value is found. The fact of a match is determined using the identity operator === rather than the equality operator ==, so the expressions must match without any type conversion.

Because not all case expressions are evaluated each time a switch statement is executed, you should avoid using case expressions that have side effects such as function calls and assignments. It is safest to limit case expressions to constant expressions.

As explained earlier, if no case expression matches a switch statement, the switch statement begins executing the statement labeled default:. If the default: label is missing, the body of the switch statement is skipped entirely. Note that in the previous examples, the default: label is included at the end of the body of the switch statement, after all the case labels. This is a logical and common place for it, but in fact it can be located anywhere within a switch statement.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

if (condition) statement1 condition An expression that is considered to be either truthy or false . statement1 Statement that is executed if condition is truthy . Can be any statement, including further nested if statements. To execute multiple statements, use a block statement (( ... )) to group those statements. To execute no statements, use an empty statement. statement2 Statement that is executed if condition is false and the else clause exists. Can be any statement, including block statements and further nested if statements.

Description

Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.

If (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN

To see how this works, this is how it would look if the nesting were properly indented:

If (condition1) statement1 else if (condition2) statement2 else if (condition3) ...

To execute multiple statements within a clause, use a block statement (( ... )) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if statements:

If (condition) ( statements1 ) else ( statements2 )

Do not confuse the primitive Boolean values ​​true and false with truthiness or falsiness of the Boolean object. Any value that is not false , undefined , null , 0 , -0 , NaN , or the empty string (""), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:

Var b = new Boolean(false); if (b) // this condition is truthy

Examples

Using if...else

if (cipher_char === from_char) ( result = result + to_char; x++; ) else ( result = result + clear_char; )

Using else if

Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if:

If (x > 50) ( /* do the right thing */ ) else if (x > 5) ( /* do the right thing */ ) else ( /* do the right thing */ )

Assignment within the conditional expression

It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:

If (x = y) ( /* do the right thing */ )

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

If ((x = y)) ( /* do the right thing */ )

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "if statement" in that specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of "if statement" in that specification.
Standard
ECMAScript 3rd Edition (ECMA-262)
The definition of "if statement" in that specification.
Standard
ECMAScript 1st Edition (ECMA-262)
The definition of "if statement" in that specification.
Standard Initial definition

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
if...elseChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

Control instructions- These are instructions that allow you to 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 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 condition for fulfillment if statements or briefly condition. 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;

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

If (false) alert("Will not execute"); 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's nothing special about 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!"); ) )

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. For this there are two conditional statements are 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.

Syntax of the if-else conditional statement next:


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 , 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 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 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 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 more variable b

" : "

Variable a less 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

The else statement can be used in conjunction with the if statement. It is translated as “otherwise” and specifies an alternative code.

Var digit = 4; if (digit

Note the different spellings of curly braces in in this example for if and else statements. It is not at all necessary to write it this way; both syntaxes are correct.

After the statement else can go new instructions if. 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
Internet