Conditionals and loop statements

Conditionals – Conditional statements execute or skip other statements depending on the value of a specified expression. Various conditionals are discussed

If – It allows JavaScript to make decisions, or, more precisely, to execute statements conditionally. It has three forms. The first is:

Syntax Example                 
if (expression)

statement

if (qty<1)

qtystatus = “Out of stock”;

In this form, if the expression evaluates to true, statement is executed else nothing is executed. Multiple statements are parenthesized. The second form has an else clause that is executed when expression is false and is:

Syntax Example                 
if (expression)

statement1

else

statement2

if (qty<1)

qtystatus = “Out of stock”;

else

qty–;

In this form, if the expression evaluates to true, statement1 is executed else statement2.

The third form has an else clause with an if that is executed when expression is false and is:

Syntax Example                 
if (expression1)      statement1

else if (expression2)      statement2

else      statement3

if (qty<1) qtystatus = “Out of stock”;

else if (qty<0)    qtystatus = “Order Pending”;

else    qty–;

In this form, if the expression1 evaluates to true, statement1 is executed else expression2 is evaluated and statement3 is evaluated.

All the forms can be nested in each other or in themselves. By default an else clause is part of the nearest if statement.

switch – Multiple conditions to evaluate needs multiple ifs and nesting hence, to test against a set of conditions, switch is used and it’s syntax is

Syntax Example                 
switch(expression) {

case 1 : statement1

break;

case 2 : statement2

break;

default : statement3

break;

}

switch(qty) {

case 0 : qtystatus = “Out of stock”;

break;

case -1 : qtystatus = “Order Pending”;

break;

default : qty–;

break;

}

A switch evaluates the value of expression and then looks for a case label whose expression evaluates to the same value after matching, it executes specific statements as labeled by the case else the statements with label default: is executed. If there is no default: label, the switch statement skips the block of code altogether. The break keyword at end of each case, causes jump to the end of the switch statement.

ternary statement – The ternary operator shortens this if/else statement into a single statement.

Syntax Example                 
result = (condition) ? ‘something’ : ‘somethingelse’; var b=5;

(b == 5) ? a=”true” : a=”false”;

Loops – They are used for repetitive execution of statement(s) dependent upon expression evaluation. JavaScript has four looping statements: while, do/while, for, and for/in.

while – It’s syntax is given below

Syntax Example                 
while (expression)

statement

number=0;

while (number<5)

{ console.log(number);     number++; }

Statement(s) executes till expression given after while, evaluates to true else skip the block .

When the expression before while is first evaluated and it evaluates to false then, the execution skips over the statement(s) or the loop body. But, if it evaluates to true, execution of the statement(s) takes place and is repeated by jumping back to the top of the loop and evaluating

expression again. As in the example above, loop variable number starts with 0 and increases by 1 till it is less than 5.

do/while – It’s syntax is given below

Syntax Example                 
do

statement

while (expression);

number=0;

do (number<5)

{ console.log(number);     number++; }

It is similar to the while loop, except that the loop expression is tested at the bottom of the loop rather than at the top thus, the loop body of the loop is always executed at least once. It is less commonly used.

for – It’s syntax is given below

Syntax Example                 
for(initialize ; test ; increment)

statement

for ( number=0; number<5; number++ )

console.log(number);

It is convenient to use than other loop statement. In it the initialization, the test, and the update of the loop variable separated by semicolons, are given as an expression in it’s syntax.

It can become an infinite loop if the test expression is omitted or if for(;;) is used.

for/in – It’s syntax is given below

Syntax Example                 
for (variable in object)

statement

for(var loopvar in objvar)

console.log(objvar[loopvar]);

It is similar to for loop statement, but it uses a variable in the expression, which evaluates to an lvalue or a single variable which moves on an object like array. objvar in the expression evaluates to an enumerable object over which loopvar variable moves one-by-one. Statement(s) serves as the body of the loop. In the example, first the object, objvar is evaluated and if it evaluates to null or undefined, the execution skips the loop. But, if objvar evaluates to a enumerable object, the loop body is executed for each enumerable property of the object.

Label Statement – If a statement is labeled by preceding it with an identifier and a colon as:

 

Syntax Example                 
identifier: statement even_number:

if(i%2==0)

{if(i==12)

break even_number;

document.write(i); }

A label is used to identify a statement to refer to it elsewhere in program. It can be used with the break or continue statements to modify the execution of a loop.

break – It causes the execution to move out of the innermost enclosing loop or switch statement.

Syntax Example                 
break; for(i = 0; i < a.length; i++) {

if (a[i] == result) break; }

It is used with switch statement and in loops to exit prematurely or for reason, to exit the loop. In the above example, when the element in array ‘a’ is matched, the loop exits.

continue – It is similar to the break statement but, it restarts a loop at the next iteration and skips the execution of remaining loop body.

Syntax Example                 
continue;

 

for(i = 0; i < a.length; i++) {

if (a[i] != result) continue; }

Thus, in a while, do/while loop, for and for/in loop statements, the test expression is tested again and as per result loop body is executed or skipped to end.

return – It is used within a function and specifies the value of returned by that function.

Syntax Example                 
return expression; function square(x) { return x*x; }

On executing the return statement, the function containing it, returns the value of expression to its caller. As in the example: above if x has value 2 so, 4 is returned. Functions with no return statement returns nothing. Return is usually at the last of a function, and may be used anywhere else also but will return to the caller and skipping execution of rest of the statements.

 

throw – The throw statement indicates some exceptional condition or error has occurred which is indicated by throw of an exception or to handle it or to take necessary actions. Exceptions are caught with the try/catch/finally statement.

Syntax Example                 
throw expression; if (x < 0) throw new Error(“x must not be negative”);

The expression may be a value of any type i.e. a number for an error code or a string for a message. JavaScript also throws an error by using the error class. After an exception is thrown, the normal program execution immediately stops and jumps to the exception handler given in the catch clause of the try/catch/finally statement.

try/catch/finally – The try clause defines the code whose exceptions are to be handled by statements given after catch clause. The finally block contains code that always executes, regardless of what happens in the try block. The catch and finally blocks are optional, at least one of these blocks are needed with try.

 

Syntax Example                 
try {

tryStatements

}

catch(exception){

catchStatements

}

finally {

finallyStatements

}

try {

var x = y;   // Cause an error.

}

catch(e) {

document.write (“Error Message: ” + e.message);

}

finally

{

document.write (“Finally error message: ” + e.message);

}

An identifier in parentheses of the catch keyword is assigned the value associated with the exception.

Comments in JavaScript Code – Comments are used to documentation. JavaScript offers two comment styles-

Multiple line comment – It extends over multiple lines for detailed discussions of important parts. It begins with /* and ends with */.

Single line comment – It is for short, pithy descriptions which will fit on a single line. It begins with // and ends at the end of the current line.

Both comment styles may be mixed freely in the same JavaScript program.

Go to- Certified PHP Developer Tutorial

JavaScript Operators (comparison, arithmetic, string, etc.)
Event Objects and handlers

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?