JavaScript - tutorial - 07 - conditional statements

revision:


Content

Conditional statements in JavaScript: if/else statements else if statements Nested if . . .else statement switch Conditional examples


Conditional statements in JavaScript:

top

- "if" to specify a block of code to be executed, if a specified condition is true.

- "else" to specify a block of code to be executed, if the same condition is false.

- "else if" to specify a new condition to test, if the first condition is false.

- "switch" to select one of many blocks of code to be executed.

P.S. - Note that "if" is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.


if/else statements

top

syntax

        if (condition) { 
          what to do if condition is met 
        } else { 
             what to do if condition is not met 
        }
    

the if/else statement executes a block of code if a specified condition is true.

If the condition is false, another block of code can be executed.
P.S.: The if/else statement is part of JavaScript's "conditional statements", which are used to perform different actions based on different conditions.

Examples: if... else

Click the button to display a time-based greeting.


code:
                    <div>
                        <button onclick="myFunction()">click me</button><br>
                        <a class="spec-2" id="condition1"></a>     
                    </div>
                    <script>
                        function myFunction() {
                            var time = new Date().getHours();
                            var greeting;
                            if (time < 20) {
                                greeting = "Good day !!";
                            } else {
                                greeting = "Good evening !!";
                            }
                            document.getElementById("condition1").innerHTML = greeting;
                        }
                    </script>
                

Please input a number between 1 and 10:



code:
                    <div class="spec">
                        <input style="margin-left: 3vw" id="numb" type="text">
                        <button type="button" onclick="myFunc()">submit</button><br><br>
                        <a id="condition2"></a>    
                    </div>
                    <script>
                        function myFunc() {
                            var x, text;
                            // Get the value of input field with id="numb"
                            x = document.getElementById("numb").value;
                            // If x is Not a Number or less than one or greater than 10, output "input is not valid"
                            // If x is a number between 1 and 10, output "Input OK"
                            if (isNaN(x) || x < 1 || x > 10) {
                                text = "Input not valid";
                            } else {
                                text = "Input OK";
                            }
                            document.getElementById("condition2").innerHTML = text;
                        }
                    </script>
                

Good evening!


Good evening!


Good evening!

Good evening!

code:
                    <div>
                        <p class="spec" id="condition3">Good evening!</p><br>
                        <p class="spec" id="condition4">Good evening!</p><br>
                        <p class="spec" id="condition5">Good evening!</p>
                        <p class="spec" id="condition6">Good evening!</p>
                    </div>
                    <script>
                        if (new Date().getHours() < 18) {
                           document.getElementById("condition3").innerHTML = "Good day!";
                        }
                        
                        var number = 2;
                        if (number < 10)
                        {
                         document.getElementById("condition4").innerHTML = ('The number is less than ten.')
                        }
        
                        const age = 18;
                        if (age >= 18) {
                            document.getElementById("condition5").innerText = "I am an adult.";
                            document.getElementById("condition6").innerText = "I may vote.";
                        }
                    </script>
                 




code:
                    <div>
                        <p class="spec" id="condition7"></p><br>
                        <p class="spec" id="condition8"></p><br>
                        <p class="spec" id="condition9"></p><br>
                    </div>
                    <script>
                        const hour = new Date().getHours(); 
                        let greeting;
                        if (hour < 18) {
                            greeting = "Good day";
                        } else {
                            greeting = "Good evening";
                        }
                        document.getElementById("condition7").innerHTML = greeting;
        
                        var nummer = 11;
                        if (nummer < 10){
                            document.getElementById("condition8").innerHTML = 'The number is less than ten.'
                        }
                        else{
                            document.getElementById("condition8").innerHTML = 'The number is greater than ten.'
                        }
        
                        const age_1 = 17;
                        if (age_1 >= 18) {
                            document.getElementById("condition9").innerHTML = "He is an adult.";
                        } else {
                            document.getElementById("condition9").innerHTML = "He is a child.";
                        }
                    </script>
                

If presence

When doing "if checks", assignment operators can sometimes be omitted. At a certain point in our code, we need to check if a variable is present or not. The if present shorthand helps to achieve that with a simple code.

longhand

                        if (likeJavaScript === true)
                        if (isLovely === true)
           
                        let a;
                        if ( a !== true ) {
                        // do something...
                        }

                        if (x === true) { 
                            // do something 
                          }

                        if(isGirl === true){
                            console.log('isGirl')
                          }
                

shorthand

                    if (likeJavaScript)
                    if (isLovely)
                
                    let a;
                    if ( !a ) {
                        // do something...
                    }

                    if (x) { 
                        // do something 
                      }
                    
                    if(isGirl){
                        console.log('isGirl')
                    }
                

else if statements

top

The "else if" statement specifies a new condition if the first condition is false.

syntax

        if (condition1) { 
            // block of code to be executed if condition1 is true
        } else if(condition2){ 
            // block of code to be executed if condition1 is false and condition2 is true 
        } else{
            // block of code to be executed if condition1 is false and condition2 is false
        }
    

Examples: else if statements

greetings

code:
                    <div>
                        <button style="margin-left: 3vw" onclick="myFunction1()">Try it</button>
                        <a id="condition10"></a>         
                    </div>
                    <script>
                        function myFunction1() {
                            var greeting1;
                            var time = new Date().getHours();
                            if (time < 10) {
                                greeting1 = "Good morning !!";
                            } else if (time < 20) {
                                greeting1 = "Good day !!";
                            } else {
                                greeting1 = "Good evening !!";
                            }
                            document.getElementById("condition10").innerHTML = greeting1;
                        }
                    </script>
                

guess a letter

I'm thinking of a letter. Guess which: a, b, c, d or e?

code:
                    <div class="spec">
                        <p>I'm thinking of a letter. Guess which: a, b, c, d or e?</p>
                        <input id="myInput" type="text">
                        <button onclick="myFunction2()">Try it</button>
                        <a id="condition11"></a>         
                    </div>
                    <script>
                        function myFunction2() {
                            var letter = document.getElementById("myInput").value;
                            var text;
                            if (letter === "c") {
                                text = "Spot on! Good job!";
                            } else if (letter === "b" || letter === "d") {
                                text = "Close, but not close enough.";
                            } else {
                                text = "Waaay off..";
                            }
                            document.getElementById("condition11").innerHTML = text;
                        }
                    </script>
                

Examples: else if statements

code:
                    <div>
                        <p class="spec" id="condition12"></p>
                        <p class="spec" id="condition13"></p>
                        <p class="spec" id="condition14"></p>
                    </div>
                    <script>
                        const time = new Date().getHours();
                        let greeting_1;
                        if (time < 10) {
                            greeting_1 = "Good morning";
                        } else if (time < 20) {
                            greeting_1 = "Good day";
                        } else {
                            greeting_1 = "Good evening";
                        }
                        document.getElementById("condition12").innerHTML = greeting_1;
        
                        var nummer = 10;
                        if (nummer < 10){
                            document.getElementById("condition13").innerHTML = 'The number is less than ten.'
                        }
                        else if (nummer == 10){
                            document.getElementById("condition13").innerHTML = 'The number is equal to ten.'
                        }
                        else{
                            document.getElementById("condition13").innerHTML = 'The number is greater than ten.'
                        }
        
                        let az = 10, bz = 20;
                        if (az > bz) {
                            document.getElementById("condition14").innerHTML = 'a is greater than b';
                        } else if (az < bz) {
                            document.getElementById("condition14").innerHTML = 'a is less than b';
                        } else {
                            document.getElementById("condition14").innerHTML = 'a is equal to b';
                        }
                    </script>
                

Nested if . . .else statement

top

Using an if...else statement inside of an if...else statement is called a nested if...else statement.

Examples: nested if..else statements

code:
                        <div>
                            <input class="spec" type="text" id="condition15" oninput="function_A()" placeholder=" input your age";/>
                            <p class="spec" id="condition16"></p>
                            <p class="spec"id="condition17"></p>
                            <input class="spec" type="text" id="condition18" oninput="function_B()" placeholder=" input a number between 0 and 30";/>
                            <p class="spec" id="condition19"></p>
                        </div>
                        <script>
                            function function_A(){
                                let age_A = document.getElementById("condition15").value;
                                if( age_A < 18 ){
                                    document.getElementById("condition16").innerHTML = "You are a minor."; 
                                    document.getElementById("condition17").innerHTML = "Not eligible to Work."; 
                                } else {
                                    if(age_A >= 18 && age_A <= 60){
                                        document.getElementById("condition16").innerHTML = "You are eligible to work.";
                                        document.getElementById("condition17").innerHTML = "Please fill in your details and apply."; 
                                    } else {
                                            document.getElementById("condition16").innerHTML = "You are too old to work as per the government rules";
                                            document.getElementById("condition17").innerHTML = "Please Collect your pension!";    
                                        } 
                                    }
                                }
                           
                            function function_B(){
                                let input = document.getElementById("condition18").value;
                                if (input <= 10){
                                    document.getElementById("condition19").innerHTML = "the number is smaller than 10 or 10";
                                } else {
                                    if (input > 10 && input < 20){
                                        document.getElementById("condition19").innerHTML = "the number is greater than 10 but smaller than 20";
                                    }else if (input >=20){
                                        document.getElementById("condition19").innerHTML = "the number is 20 or greater";
                                    }else{
                                    document.getElementById("condition19").innerHTML = "no number is presented";
                                    }
                                }
                            }
                        </script>
                       
                    

switch

top

The switch has one or more case blocks and an "optional" default.

The switch statement executes a block of code depending on different cases. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.

The switch statement is often used together with a "break" or a "default" keyword (or both). These are both optional: the "break" keyword breaks out of the switch block; the "default" keyword specifies some code to run if there is no case match.

If "default" is not the last case in the switch block, remember to end the default case with a break.

Syntax

        switch(x){ 
case 'value 1': ... [break] case 'value 2': ... [break] case 'value 3' ... [break] default: ... [break] }

When JavaScript reaches a "break" keyword, it breaks out of the switch block and will stop the execution inside the switch block.

The "default" keyword specifies the code to run if there is no case match.

switch cases use strict comparison (===). The values must be of the same type to match.

Examples: day of the week

code:
                    <div class="spec">
                        <a id="condition20"></a>         
                    </div>
                    <script>
                        var day;
                        switch (new Date().getDay()) {
                            case 0:
                                day = "Sunday";
                                break;
                            case 1:
                                day = "Monday";
                                break;
                            case 2:
                                day = "Tuesday";
                                break;
                            case 3:
                                day = "Wednesday";
                                break;
                            case 4:
                                day = "Thursday";
                                break;
                            case 5:
                                day = "Friday";
                                break;
                            case  6:
                                day = "Saturday";
                        }
                        document.getElementById("condition20").innerHTML = "Today is " + day;
                    </script>
                
code:
                    <div class="spec">
                        <a id="condition21"></a>      
                    </div>
                    <script>
                        var text;
                        switch (new Date().getDay()) {
                            case 0:
                                text = "Today is Sunday";
                                break;
                            case 1:
                                text = "Today is Monday";
                                break;
                            case 2:
                                text = "Today is Tuesday";
                                break;
                            case 3:
                                text = "Today is Wednesday";
                                break;
                            case 4:
                                text = "Today is Thursday";
                                break;
                            case 5:
                                text = "Today is Friday";
                                break;
                            case  6:
                                text = "Today is Saturday";
                            default:
                                text = "Looking forward to the weekend"
                        }
                        document.getElementById("condition21").innerHTML = text;
                    </script>
                

code:
                    <div class="spec">
                        <p id="condition22"></p>     
                    </div>
                    <script>
                        var text;
                        switch (new Date().getDay()) {
                            case 1:
                            case 2:
                            case 3:
                                text = "Working hard!";
                                break;    
                            case 4:
                            case 5:
                                text = "Soon it is Weekend";
                                break;
                            case 0:
                            case 6:
                                text = "It is Weekend";
                                break;
                            default:
                                text = "Looking forward to the Weekend";
                        }
                        document.getElementById("condition22").innerHTML = text;
                    </script>
                

Examples: inputs

Write banana, orange or apple in the input field and click the button.



code:
                    <div class="spec">
                        <p>Write banana, orange or apple in the input field and click the button.</p>
                        <input id="condition23" type="text">
                        <button onclick="myFruit()">Try it</button>
                        <a id="condition24"></a>  
                    </div>
                    <script>
                        function myFruit() {
                            var text;
                            var fruits = document.getElementById("condition23").value;
                            switch(fruits) {
                                case 'banana': text = "Banana is good!";
                                break;
                                case "orange": text = "I am not a fan of orange.";
                                break;
                                case "apple":  text = "How you like them apples?";
                                break;
                                default:
                                text = "I have never heard of that fruit...";
                            }
                        document.getElementById("condition24").innerHTML = text;
                        }
                    </script>
                

Enter a value



code:
                    <div class="spec">
                        <p style="margin-left: 1vw;">Enter a value</p>
                        <input style="margin-left: 2vw;" id="condition25" type="text"/>
                        <button onclick="myFunc2A()">Try it</button>
                        <a id="condition26"></a>
                    </div>
                    <script>
                        function myFunc2A(){
                            let text1;
                            let cijfer = document.getElementById('condition25').value;
                            switch(cijfer){
                                case '0':
                                case '1':
                                    text1 = 'one or zero';
                                    break;
                                case '2':
                                    text1 = 'two';
                                    break;
                                case '3':
                                    text1 = 'never executes!';
                                    break;
                                default:
                                    text1 = 'an unknown value!';   
                            }
                            document.getElementById('condition26').innerHTML = text1;
                        }
                    </script> 
                

Switch shorthand

longhand

                    const dayNumber = new Date().getDay();
                    let day;
                    switch (dayNumber) {
                      case 0:
                        day = "Sunday";
                        break;
                      case 1:
                        day = "Monday";
                        break;
                      case 2:
                        day = "Tuesday";
                        break;
                      case 3:
                        day = "Wednesday";
                        break;
                      case 4:
                        day = "Thursday";
                        break;
                      case 5:
                        day = "Friday";
                        break;
                      case 6:
                        day = "Saturday";
                    }
                

shorthand

                    const dayNumber = new Date().getDay();
                    const days = {
                        0: "Sunday",
                        1: "Monday",
                        2: "Tuesday",
                        3: "Wednesday",
                        4: "Thursday",
                        5: "Friday",
                        6: "Saturday",
                      };
                      const day = days[dayNumber];
                     
                

More "switch" examples

Favorite Color

code:
                    <div>
                        <h4 class="spec-2">Favorite Color</h4>
                        <label class="spec-2"><input type="radio" name="fav_color" value="Blue" onclick="analyzeColor(this.value);"> Blue </label>
                        <label><input type="radio" name="fav_color" value="Red" onclick="analyzeColor(this.value);"> Red </label>
                        <label><input type="radio" name="fav_color" value="Green" onclick="analyzeColor(this.value);"> Green </label>
                        <label><input type="radio" name="fav_color" value="None" onclick="analyzeColor(this.value);"> None </label>
                        <p class="spec-2" id="condition27"></p>
                        <p class="spec-2" id="condition28"></p>
                    </div>
                    <script>
                        function analyzeColor(myColor) {
                            switch (myColor){
                                case "Blue":
                                    document.getElementById("condition27").innerText = "Just like the sky!";
                                    break
                                case "Red":
                                    document.getElementById("condition27").innerText ="Just like shiraz!";
                                    break
                                case "Green":
                                    document.getElementById("condition27").innerText ="Just like pastures!";
                                    break
                                default:
                                    document.getElementById("condition27").innerText = "Suit yourself then...";
                            }
                        }
            
                        let day_1;
                            switch (new Date().getDay()) {
                                case 0:
                                    day = "Sunday";
                                    break;
                                case 1:
                                    day = "Monday";
                                    break;
                                case 2:
                                    day = "Tuesday";
                                    break;
                                case 3:
                                    day = "Wednesday";
                                    break;
                                case 4:
                                    day = "Thursday";
                                    break;
                                case 5:
                                    day = "Friday";
                                    break;
                                case  6:
                                    day = "Saturday";
                                }
                        document.getElementById("condition28").innerHTML = "Today is " + day;
                    </script>
                

Write "Banana", "Orange" or "Apple" in the input field and click the button.

select a food: "sushi" , "pizza", or "dumpling", input it and click the button.

code:
                    <div>
                        <p class="example" style="margin-left:5vw;">Write "Banana", "Orange" or "Apple" in the input field 
                        and click the button.</p>
                        <input style="margin-left: 5vw;" id="condition29" type="text">
                        <button onclick="selectFruit()">try it</button>
                        <p class="spec" style="margin-left:5vw; margin-top: 1vw;" id="condition30"></p>
                        <p class="example" style="margin-left:5vw; margin-top:1vw;">select a food: "sushi" , "pizza",  or "dumpling", 
                        input it and 
                        click the button.</p>
                        <input style="margin-left: 5vw;" id="condition31" type="text">
                        <button onclick="selectFood()">try it</button>
                        <p class="spec" style="margin-left:5vw; margin-top: 1vw;" id="condition32"></p>
                    </div>
                    <script>
                        function selectFruit() {
                            var text;
                            var fruits = document.getElementById("condition29").value;
                            switch(fruits) {
                                case "Banana":
                                text = "Banana is good!";
                                break;
                                case "Orange":
                                text = "I am not a fan of orange.";
                                break;
                                case "Apple":
                                text = "How you like them apples?";
                                break;
                                default:
                                text = "I have never heard of that fruit...";
                            }
                            document.getElementById("condition30").innerHTML = text;
                            }
        
                            function selectFood(){
                                let food = document.getElementById("condition31").value;
                                switch (food) {
                                    case "sushi":
                                        document.getElementById("condition32").textContent = "Sushi is originally from Japan.";
                                        break;
                                    case "pizza":
                                        document.getElementById("condition32").textContent = "Pizza is originally from Italy.";
                                        break;
                                    case "dumpling":
                                        document.getElementById("condition32").textContent = "Dumpling is originally from China.";
                                        break;
                                    default:
                                        document.getElementById("condition32").textContent = "I have never heard of that dish.";
                                        break;
                                }
                            }
                    </script>
                

code:
                    <div>
                        <p class="spec" id="condition33"></p>
                        <p class="spec" id="condition34"></p>
                    </div>
                    <script>
                        let aa = 1;
                        switch (aa) {
                            case "1":
                                aa = 1;
                                break;
                            case 1:
                                aa = 'one';
                                break;
                            case 2:
                                aa = 'two';
                                break;
                            default:
                                aa = 'not found';
                                break;
                        }
                        document.getElementById("condition33").innerText = `The value is ${aa}`;
        
                        var d = new Date();
                        switch(d.getDay()) {
                            default: 
                                document.getElementById("condition34").innerText = "Looking forward to the weekend.";
                                break;
                            case 6:
                                document.getElementById("condition34").innerText = "Today is Saturday.";
                                break; 
                            case 0:
                                document.getElementById("condition34").innerText = "Today is Sunday.";
        
                        }
                    </script>
                

fruit pricing: "oranges", "apples", "bananas", "cherries", "mangoes", "papayas"

code:
                    <div>
                        <p class="spec" style="margin-left:5vw;">fruit pricing: "oranges", "apples", "bananas",
                            "cherries", "mangoes", "papayas" </p>
                        <input style="margin-left: 5vw;" id="pricing" type="text">
                        <button onclick="priceFruit()">try it</button>
                        <p class="spec" style="margin-left:5vw; margin-top: 1vw;" id="switch04B"></p>
                    </div>
                    <script>
                        function priceFruit(){
                            let expr = document.getElementById("pricing").value;
                            switch (expr) {
                                case "oranges":
                                    document.getElementById("switch04B").textContent = "Oranges are $0.59 a 
                                    pound.";
                                    break;
                                case "apples":
                                    document.getElementById("switch04B").textContent = "Apples are $0.32 a 
                                    pound.";
                                    break;
                                case "bananas":
                                    document.getElementById("switch04B").textContent = "Bananas are $0.48 a
                                        pound.";
                                    break;
                                case "cherries":
                                document.getElementById("switch04B").textContent = "Cherries are $3.00 
                                    pound.";
                                    break;
                                case "mangoes":
                                case "papayas":
                                    document.getElementById("switch04B").textContent = "Mangoes and papayas are 
                                    $2.79 a pound.";
                                    break;
                                default:
                                    document.getElementById("switch04B").textContent = "Sorry, we are out of " + 
                                    expr + ".";
                                }
                        }
        
                    </script>
    
                

Conditional examples

top

JavaScript.Info - examples

examples
"if" statement:
               
                let year = prompt('In which year was ECMAScript-2015 specification published?', '');
                if (year == 2015) alert( 'You are right!' );

                if (year == 2015) {
                    alert( "That's correct!" );
                    alert( "You're so smart!" );
                }
            
boolean conversion:
               
                if (0) { // 0 is falsy
                    ...
                }

                if (1) { // 1 is truthy
                    ...
                }
            
"else" clause:
               
                let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
                if (year == 2015) {
                    alert( 'You guessed it right!' );
                } else {
                    alert( 'How can you be so wrong?' ); // any value except 2015
                }
            
several conditions:"else if":
               
                let year = prompt('In which year was the ECMAScript-2015 specification 
                published?', '');
                if (year < 2015) {
                alert( 'Too early...' );
                } else if (year > 2015) {
                alert( 'Too late' );
                } else {
                alert( 'Exactly!' );
                }
            
conditional operator ?:
               
                let accessAllowed;
                let age = prompt('How old are you?', '');
                if (age > 18) {
                accessAllowed = true;
                } else {
                accessAllowed = false;
                }
                alert(accessAllowed);

                let result = condition ? value1 : value2;

                let accessAllowed = (age > 18) ? true : false;

                // the comparison operator "age > 18" executes first anyway
                // (no need to wrap it into parentheses)
                let accessAllowed = age > 18 ? true : false;

            
multiple ?:
               
                let age = prompt('age?', 18);
                let message = (age < 3) ? 'Hi, baby!' :
                (age < 18) ? 'Hello!' :
                (age < 100) ? 'Greetings!' :
                'What an unusual age!';
                alert( message );
            
non-traditional use of '?':
               
                let company = prompt('Which company created JavaScript?', '');
                (company == 'Netscape') ?
                alert('Right!') : alert('Wrong.');