What are conditional statements in JavaScript

JavaScript / branch

Control structures are instructions which in turn contain instruction blocks. This makes it possible to control the execution of the instructions contained in the blocks according to certain rules.

There are basically two types of control structures: branches and loops. By means of branches it is possible to make the execution of one or more instruction blocks dependent on conditions (case distinction). Loops allow a block of instructions to be executed repeatedly.

If-then conditions with "if" [edit]

You can make the execution of statements conditional. In a branch (conditional instruction), an instruction block is only run through if a condition is met. Alternatively, if the condition is not met, a second statement block can be run through.

if (expression) {// statement block of the true branch (is executed if the condition is fulfilled) statement; statement;} else {// statement block of the false branch (is executed if the condition is not fulfilled) statement; statement;}


With you introduce an if-then-condition (if = if). This is followed by the wording of the condition in brackets. In order to formulate such conditions, you need comparison operators and in most cases also variables. For cases in which the condition is not met, you can define an "otherwise" branch. This is done through (else = otherwise). The Else branch is not absolutely necessary.

Note if several instructions follow below and depending on or, these always in curly Brackets must be included (see also the section on statement blocks).
document.addEventListener ('DOMContentLoaded', Secret); functionGeheim () {varPasswort = 'Traumtaenzer'; varEingabe = window.prompt ('Please enter the password', ''); if (Enter! = Password) {alert ( 'Wrong password!');} Else {location.href = 'secret.htm';}}
The example shows a simple password query.

The script is noted in a function called, which is called as soon as the HTML file is completely loaded. For this purpose, the DOMContentLoaded event is monitored dynamically with addEventListener.
Within the function, a dialog window () asks the user to enter the password. The return value of, the entered password, is saved in the variable.

With) the script asks whether the input is different from the value previously assigned to the variable. If this is the case, i.e. both values ​​are not the same, then the entry was incorrect. In this case, a corresponding message is output with. In the other case (), if and have the same value, another page is called with location.href, namely the "protected" page.
Note: One such password query is no meaningful optionto control access to a website. Because the password is readable for everyone in the source text and the "protected" page can be called up bypassing the password query. You should therefore use reliable protection mechanisms for access protection on websites in practice.

Common problem [edit]

It often happens that an if-query doesn't work as expected. Regardless of what value is checked, the If branch is always used and not, as expected, in the Else branch. It is very likely that this is due to the fact that instead of making a comparison, an assignment was noted.

If you write down the assignment instead, it will be answered successfully with.

You can avoid this error by interchanging, since no variable can be assigned to a number.

Simple either-or query [edit]

For simple either-or conditions there is the conditional (ternary) operator a special syntax that you can use as an alternative to the if / else statement.

document.addEventListener ('DOMContentLoaded', function () {document.querySelector ('# check'). addEventListener ('click', answer); functionAntwort () {varErresult = (document.Formular.Eingabe.value == '42' )? 'RICHTIG!': 'FALSCH!'; Vartext = 'The answer is' + result; document.querySelector ('output'). InnerText = text;}});
The example contains a JavaScript function called.

When the document is loaded, an EventHandler is added with addEventListener, which is called when the user clicks on the click button with the label and the id = "check" in the form with the click event.

The function checks whether the value of the input field in the form () has the value. Depending on this, either the value or is assigned to the variable. Then a corresponding sentence is put together (see also operator for string linking) and output in the output element.

A simple either-or query is introduced with a condition. The condition must be in brackets, in the example (). A question mark is noted behind it. A value is given after the question mark that is current if the condition is met. This is followed by a colon, followed by a value in the event that the condition is not met. Since these are values ​​that are only useful for further processing if they are saved in a variable, such an either-or query is usually preceded by a variable, in the example the variable. This type of statement assigns the result of the either-or query to the variable.

You need relational operators to formulate conditions.

Differentiation of cases with "switch" [edit]

With and you can distinguish between exactly two cases. If you want to differentiate more finely, that is, to differentiate between several cases, you can write down several if-queries one after the other, but there is a more elegant possibility: the case differentiation with "switch".

varEingabe = window.prompt ('Enter a number between 1 and 4:', ''), text = ''; switch (input) {case "1": text = 'You are very humble!'; break; case "2": text = 'You are a sincere biped!'; break; case "3": text = 'You won a tricycle!'; break; case "4": text = 'Get on all fours and become more modest! '; break; default: text =' You are unfortunately staying stupid! '; break;} varausgabe = document.getElementById (' output '); output.innerHTML = text;


With you initiate a case distinction (switch = switch). This is followed by a variable or expression, enclosed in round brackets, for whose current value you make the case distinction. In the example this is the variable with the name. This variable is given a value before the case distinction, because a dialog window () with an input field prompts the user to enter a number between 1 and 4. The entered value is saved in.

The individual cases that you want to query are noted within curly brackets. You initiate each individual case (case). This is followed by the specification of the value that you want to check for. The instruction in the example above then means something like: 'if the input variable has the value "1"'. In the example, an individual message is output for each case.

The word at the end of each case is also important (break = abort). If you omit the word, all of the following cases will be carried out, but you usually don't want that.

In the event that none of the defined cases apply, you can define the case at the end of the case distinction. The instructions below are carried out if none of the other cases apply.

Special feature: same instructions [edit]

Sometimes the same code should be executed for different values ​​of the case distinction. To do this, simply put the relevant cases one below the other.

varEingabe = window.prompt ('Enter a number between 1 and 6:', ''), text = 'Your input is'; switch (input) {case "1": text + =' neither a prime nor a composite number. '; break; case "2": case "3": case "5": text + =' a prime number. '; break; case "4": case "6": text + =' a composite number. ' ; break; default: text = 'Invalid input'; break;}

Special feature: value ranges [edit]

If a range of values ​​is to be checked instead of an exact value, the code must look like this:

varEingabe = window.prompt ('Enter a number between 50 and 100:', ''), text = ''; switch (true) {case (input <50): text = 'The number' + Enter + 'is clearly too small. '; break; case (input> 100): text =' The number '+ input +' is clearly too big. '; break; default: text =' Well please, you understood the task! '; break ;}

Unlike other programming languages ​​that accept a range of values ​​in conditional statements, two things are particularly noticeable in JavaScript:

1.) The variable whose value you want to distinguish is not written in the round brackets after the word, but in round brackets after the word.
2.) Since the listed cases always check Boolean expressions, the word must be written in the round brackets after the word, because the condition of one of these cases must be met.

Web links [edit]