JavaScript

JavaScript If, If Else If Statement, Nested If Else, Switch Case Statement

JavaScript if Statement:

The JavaScript if statement is a conditional statement used to execute or to ignore certain statements of the program/script on conditional basis.

The JavaScript if statement evaluates the given condition. If the given condition is true, the statement (or set of statements) following the JavaScript if statement is executed. If the given condition is false, the statement (or set of statements) following the JavaScript if statement is ignored ( or skipped) and control transfer directly to next statement of JavaScript if  structure.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

The general syntax of JavaScript if structure for single statement is:

If (expression)

Statement-1;

Statement-2;

Where

Expression: Represents the test condition. It may be a relational expression or logical expression. It is used as test condition. If result of expression is nonzero (true), then “statement-1” is executed otherwise it is ignored (or skipped).


A script is given below to print a message if the value of variable “n” is greater than 100, otherwise ignore the statement.

<html>
<body>
<script type="text/JavaScript">
    var n;
    n = prompt("enter any value");
    if(n > 100)
        document.write("value is greater than 100"+"<br>");
    document.write("ok");
    
</script>
</body>
</html>

JavaScript if

When you put value less than 100 it will show the message “ok as you can see in the below image.

JavaScript if

And when you put the value greater than 100 it show the message” value is greater than 100” as you can seen in the below image.

JavaScript if

JavaScript if

JavaScript if Structure with Multiple statements:

You can also execute or ignore more than one statement following the JavaScript if statement. These statement are written within curly braces { } after JavaScript if statement. The set of statements surrounded by braces is called compound statement.

The syntax to write the compound statement in JavaScript if structure is:

If (expression)

{

Statement-1;

Statement-2;

.

.

Statement-m;

}

Statement-n;

In the above syntax, the set of statement (from statement-1 to statement-m) represent the compound statement. The statement-n represents the next statement. It comes immediately after the if structure.



A Script is given below to execute a compound statement if the given condition is true, i.e. if the value of ‘a’ is greater than 100

<html>
<body>
<script type="text/JavaScript">
    var n;
    n = prompt("Enter any value");
    if(n > 100)
    {
        document.write("Value is greater than 100"+"<br>");
        document.write("ok");
    }
    
</script>
</body>
</html>

JavaScript if

When you put value less than 100 it will not show any message as you can see in the below image.

JavaScript if

And when you put the value greater than 100 it show the message” value is greater than 100 ok” as you can seen in the below images.

JavaScript if

JavaScript if

In the above script, if the entered value of ‘n’ is greater than 100, then the given condition becomes true and the multiple statements enclosed in curly brackets, following the JavaScript if statement are executed. Similarly, if the entered value of ‘n’ is less than or equal to 100, then the given condition become false and the multiple statement following the JavaScript if statement are ignored.

Example: write JavaScript code to test whether a given integer is odd or even using simple JavaScript if  structure:

<html>
<body>
<script type="text/JavaScript">
    var n;
    n = parseInt(prompt("Enter any value"));
    if(n%2==0)
        document.write("Even Value"+"<br>");
    if(n%2==1)
        document.write("Odd Value");
    
    
</script>
</body>
</html>

JavaScript if

JavaScript if

JavaScript if

JavaScript if


The JavaScript if-else Structure:

The JavaScript if-else structure is used for making two-way decisions. In JavaScript if-else structure, one condition and two blocks of statement are given. Either one of the two blocks of statements is executed after evaluating the given condition.

The JavaScript if -else structure, first the given condition is tested. If the given condition is true, than the first block of statement is executed and the second block of statement is ignored. It the given condition is false, then the first block of statement is ignored and the second block of statements following the keyword else is executed. In any situation, one block is executed and other block is ignored.

The general syntax of simple JavaScript if-else structure is:

If (expression)

Statement-1;

Else

Statemtent-2;

In the above syntax, if result of expression is non-zero (true), then statement-1 is executed and statement-2 is ignored. Similarly, if result of expression is false (zero), then statement -1 is ignored and statement-2 is executed.

In case of compound statement, the syntax of JavaScript if -else structure is:

If (expression)

{

Block-1

}

else

{

Block-2

}

The JavaScript if -else structure may contain a single statement (without curly brackets) on one side and compound statement on another side.

The flowchart of JavaScript i -else structure is given below.

JavaScript if

A script is given below to find and print the minimum value of two values

<html>
<body>
<script type="text/JavaScript">
    var a, b,min;
    a=10;
    b=5;
    if(a<b)
        min=a;
    else
        min=b;
    document.write(min);
    
    
</script>
</body>
</html>

JavaScript if

In the above script, the value 10 and 5 are assigned to variable ‘a’ and ‘b’ respectively. The JavaScript if statement tests the condition (a<b). if (a<b) is true then the assigned to variable ‘min’. if condition is false, the value of ‘b’ is ignored and “min=b” is executed. There, the value 5 is assigned to “min”.


Example: write JavaScript code to input two values and print these value in ascending order by using ‘JavaScript if -else’ structure:

<html>
<body>
<script type="text/JavaScript">
    var a, b;
    a=parseInt(prompt("Enter 1st value"));
    b=parseInt(prompt("Enter 2nd value"));
    if(a < b )
        document.write(a + "<br>" + b);
    else
        document.write(b + "<br>" + a);
    
    
</script>
</body>
</html>

Enter the 1st value

JavaScript if

Enter the 2nd value

JavaScript if

JavaScript if

Conditional JavaScript Operator:

The conditional JavaScript Operator is denoted by ? and : signs. It is also used for making two-way decisions. The conditional JavaScript Operator is closely related to the simple ‘JavaScript if -else’ structure. It can be use as an alternative to simple ‘JavaScript if -else’ structure.

The general syntax of conditional JavaScript Operator is:

(condition) ? exp1 : exp2

Where

Condition:

Represents the condition. It may be a relational or logical expression. if it is true then computer will take action  on “exp1 and “exp2” is ignored. It condition is false, the computer will take action on exp2 and exp1 is ignored.

Exp1, exp2:

Both these expressions may be arithmetic expression or constant values or variables. Other statements of JavaScript such as input and output statement can also be used in place of exp1 and exp2

It may be noted that the conditional operator takes three operands (i.e. condition, exp1 and exp2). It is a ternary operator.

for example, to test and print whether a give number  ‘ n’ is odd or even, the statement using conditional JavaScript Operator is written as:

(n%2==0)?document.write(“even”):document.write(“odd number”)


A script is given below to find out the minimum number of two numbers using conditional operator.

<html>
<body>
<script type="text/JavaScript">
    var a, b,min;
    a=15;
    b=49;
    min=(a<b) ? a:b;
    document.write("Minimum Number is:"+min);
    
</script>
</body>
</html>

JavaScript if

The above script will be executed as:

  • The value 15 and 49 are assigned through assignment statement to variable ‘a’ and ‘b’ respectively.
  • The statement “min=(a<y) ? a:b;” will be executed. The test condition (a<b) will be evaluated; it is true because value of ‘a’ is less than b. So value of ‘a will be assigned to variable ‘min’
  • The value 15 will be displayed in browser window as you can see in the above image.

Example write JavaScript code to input a value for year and test whether it is a leap year or not using conditional operator:

<html>
<body>
<script type="text/JavaScript">
    var year;
    year = parseInt(prompt("Enter value for Year"));
    (year%4==0)?
    document.write("Leap Year"):
    document.write("Not Leap Year");
    
</script>
</body>
</html>

JavaScript if

JavaScript if

JavaScript if

JavaScript if

Nested if structure:

The JavaScript if statement is itself a statement and it can be used within another JavaScript if structure. When JavaScript if structure is used within another JavaScript if structure, it is called nested if structure.

The general form of nested if statement is given as:

If (condition-1)

{

If (condition-2)

{

Statements;

}

}

In the above syntax, the JavaScript if  statement that has “condition-1” contain another if statement that has “condition-2”. The nested if statement may also contain ‘else’ part.

The JavaScript if  statement that contain another statement is referred to as outer JavaScript if  statement, while the JavaScript if  statement used inside if (nested if statement) is referred to as inner if statement. The nested if statement will be executed only if outer if statement (that contains the nested if statement) is true.



For example, to check whether the value of variable ‘a’ is greater than the value of variables ‘b’ and ‘c’, the set of statement is

If(a>b)

If(a>c)

Document.write(“a is greater than b and c”);

In the above code, the JavaScript if  structure that has relational expression (a>c) is a nested JavaScript if  structure. It comes inside the if structure that has relational expression (a>b).

Example: write JavaScript code to input three values. Find out the greatest value using nested if statement:

<html>
<body>
<script type="text/JavaScript">
    var x,y,z,max;
    x=parseInt(prompt("Enter 1st Value"));
    y=parseInt(prompt("Enter 2nd Value"));
    z=parseInt(prompt("Enter 3rd Value"));
    if (x>y)
        if(x>z)
            max=x;
        else
            max=z;
        else
            if(y>z)
                max=y;
            else
                max=z;
        document.write("Maximum Value is:" +max);
    
</script>
</body>
</html>

JavaScript if

JavaScript if

JavaScript if

JavaScript if

Example write JavaScript code to find out the grade of a student base on the average marks obtained in three subjects:

The grade is calculated as:

  • If average is greater than 80, grade is A.
  • If average is less than 80 and greater than 60, grade is B.
  • If average is less than 60 and greater than 33, grade is C.
  • If average is less than 33, grade is F.
<html>
<body>
<script type="text/JavaScript">
    var eng,math,comp,avg,grade;
    eng=parseInt(prompt("Enter English marks"));
    math=parseInt(prompt("Enter Maths marks"));
    comp=parseInt(prompt("Enter Computer marks"));
    avg=(eng+math+comp)/3
    if (avg>33)
        if(avg>60)
        
            if (avg>80)
                grade= "A";
            else
                grade= "B";
        else
            grade= "C";
    else
        grade="F"
    document.write("Grade = "+grade);
    
</script>
</body>
</html>

JavaScript if

JavaScript if

JavaScript if

JavaScript if


Difference Between Nested if and sequence of JavaScript if  statements:

The nested if statement may contain multiple JavaScript if  statement s that may be nested up to any level. Some JavaScript if  statements are executed while other may be skipped.

In a sequence of JavaScript if  statements, multiple if statement are written one after the other. All if statements are executed in an order and no if statement is skipped.

For example, to find whether a number is positive, negative or zero, a script is given below in which three if statement are used in a sequence.

<html>
<body>
<script type="text/JavaScript">
    var num;
    num=parseInt(prompt("enter a number"));
    if (num > 0)
        document.write("the number is positive");
    if (num < 0)
        document.write("the number is negative");
    if (num == 0)
        document.write("the number is zero");
    
        
    
</script>
</body>
</html>

JavaScript if

JavaScript if

In the above script, three if statement are given in a sequences. Suppose the user enters a positive number. The number is tested with first JavaScript if  statement. The answer is true because number is positive. The message is displayed in browser window as you can see in above example image. after displaying the message, other two if statement will also be executed. Although the answers to these two JavaScript if  statements will be false. There is no need to executed these JavaScript if  statements. These statements be skipped. Otherwise processor of computer has to consume extra time without any purpose. The’ JavaScript if -else-if’ structure can be used to handle this kind of situation.

JavaScript if -else-if Statement:

When an JavaScript if -else statement is placed within another JavaScript if -else statement, it is referred to as ‘JavaScript if -else-if’ structure. The if-else-if structure is also referred to as nest ‘JavaScript if -else’ structure.

The nested if-else structure is used to select one of many block of code to be executed. This structure uses multiple test conditions and multiple blocks of statements. When any given test condition is true, the block if statements under that condition is executed and control exits from the nested if-else structure.

The general syntax of nested if-else structure is:

If (condition-1)

Block-1

else if (condition-2)

block-2

else if (condition-m)

block-m

else

block-n

in the above mentioned structure, the conditions are evaluated from the top and if one of them is true, the corresponding block of statements is executed and other conditions are skipped. The use of “else” part of condition-m is optional.

<html>
<body>
<script type="text/JavaScript">
    var num;
    num=parseInt(prompt("enter a number"));
    if (num > 0)
        document.write("the number is positive");
    else if (num < 0)
        document.write("the number is negative");
    else (num == 0)
        document.write("the number is zero");
    </script>
</body>
</html>

In the above script, ‘JavaScript if -else-if’ structure is used. Suppose the user enters a positive number. The number is tested with JavaScript if  statement. The answer is true because number is positive. The message is displayed in the browser window and rest f the conditions will be skipped.


Example write javascript code to input average marks of student and find out grade using nested if-else statement:

The criteria of grades are:

  • If average is greater than or equal to 90, grade is “A+”.
  • If average is greater than or equal to 80 and less than 90, grade is “A”.
  • If average is greater than or equal to 70 and less than 80, grade is “B”.
  • If average is greater than or equal to 60 and less than 70, grade is “C”.
  • If average is greater than or equal to 50 and less than 60, grade is “D”.
  • If average is greater than or equal to 40 and less than 50, grade is “E”.
  • Otherwise “Fail”.
<html>
<body>
<script type="text/JavaScript">
    var avg;
    avg= parseInt(prompt("enter average marks"));
    if (avg>= 90)
        document.write("A+");
    else if(avg>=80)
        document.write("A");
    else if(avg>=70)
        document.write("B");
    else if(avg>=60)
        document.write("C");
    else if(avg>=50)
        document.write("D");
    else if(avg>=40)
        document.write("E");
    else
        document.write("Fail");
        
    
</script>
</body>
</html>

JavaScript if

JavaScript if

JavaScript if

JavaScript if


JavaScript Switch Statement:

Although the nested if-else statement is used for multiple selections but it becomes complicated for large number of choices.

The switch statement is used as a substitute of nested if-else statement. It is used when multiple choices are given and one choice is to be selected. For example, this statement is used for menu selection.

The switch statement contains only one expression at its beginning and multiple case (each case contains a set of statements) within its body. One of the case (or block of statements) is selected for execution depending upon the value returned by this expression.

The general syntax of switch statement is:

switch (expression)

{

Case label-1:

Set of statement-1

Break;

Case label-2:

Set of statement-2

Break;

 

Default:

Set of statements-n

}

 

Where:

 

Switch:

It is a keyword of javascript. It indicates the beginning of switch statement.

Expression:

It is an expression. it may be a single variable or an arithmetic expression. the value returned by the expression must be an integer of a single character. It must not be a floating point value (or any other type of data). When switch statement is executed, the given expression is first evaluated. The value returned by the expression is compared successively with label-1, label-2-,-,-, until a match is found. If a case matches with the value returned by expression, then the block of statements following that case is executed until the ‘break’ statement is encountered. All other blocks are skipped.

Label-1, label-1:

Represent the labels for the cases. They may be numeric constant values or character constant values. All case labels must be different. The value returned by expression must be same as the data type of labels.

Default:

It is keyword of javascript. If the value returned by the expression is not matched to any on to the labels of the cases then the “set of statements-n” following ‘default’ is executed. The default part of  ‘switch’ statement is optional.

Flowchart of JavaScript switch Statement:

JavaScript if

The switch statement can be used within another switch selection statement, it is called the nested switch statement. The case constant values of the inner and the outer switch statement may contain common values.

Break Statement:

The ‘break’ statement is used to exit from the body the switch statement (or loop structure). After executing this statement, execution control is transferred to the statement that comes immediately after the switch statement (or loop structure).

In the switch statement the break statement is normally used at the end of statement in each case. If all break statement are omitted from the switch statement, then the statement of all the remaining cases that come after the matched case are also executed in a sequential order.

Example how to use switch case in JavaScript to displayed the corresponding name of the  day by entering from 1 to 7:

<html>
<body>
<script type="text/JavaScript">
    var n;
    n= parseInt(prompt("Enter a number from [1-7]"));
    switch(n)
    {
    case 1: document.write("Monday");
    break;
    case 2: document.write("Tuesday");
    break;
    case 3: document.write("Wednesday");
    break;
    case 4: document.write("Thursday");
    break;
    case 5: document.write("Friday");
    break;
    case 6: document.write("Saturday");
    break;
    case 7: document.write("Sunday");
    break;
    }
    
        
    
</script>
</body>
</html>

JavaScript if

JavaScript if

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button