JavaScript. Branching statements

Branching is very essential to execute program with respect to certain condition. Here we will see how to use if-else keyword to implement program flow.

Branching statements enable you to make choices. JavaScript has two branching statements: if and switch. The if statement is so important that we’ve already seen it at work both in this and the previous chapter; we’ll take a look at it in depth here.

Statements can be executed conditionally by using an if statement. The if statement specifies a condition which gets tested when the if statement is executed. If the condition is true then the following statement is executed otherwise processing skips that statement.

Optionally a second statement can be attached to the if statement that will be executed if the condition is false.

pseudo code: if condition--> true-statement--> else--> false-statement

example

if x >y yprint "x is bigger than y"

else print "x is not bigger than y"

You can use multiple if...else if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements.

Syntax: The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.switch (expression)

{case condition 1: statement(s) break;

case condition 2: statement(s) break;

...

case condition n: statement(s) break;

default: statement(s) }

The break statements indicate to the interpreter the end of that particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: