Conditional Statements

  • Very often when you write code, you want to perform different actions for different decisions.
    You can use conditional statements in your code to do this.
  • In JavaScript we have the following conditional statements:
    • Use if to specify a block of code to be executed, if a specified condition is true
    • Use else to specify a block of code to be executed, if the same condition is false
    • Use else if to specify a new condition to test, if the first condition is false
    • Use switch to specify many alternative blocks of code to be executed
  • if Statement

    • Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
    • Syntax :
                        
          if (condition) {
            //  block of code to be executed if the condition is true 
          }
                        
                      
    • Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
    • EX :
                        
          if (hour < 18) {
            greeting = "Good day";
          }
                        
                      
  • The else Statement

    • Use the else statement to specify a block of code to be executed if the condition is false.
    • Syntax :
                        
          if (condition) {
            //  block of code to be executed if the condition is true
          } else {
            //  block of code to be executed if the condition is false
          }
                        
                      
    • EX :
                        
          if (hour < 18) {
            greeting = "Good day";
          } else {
            greeting = "Good evening";
          }
                        
                      
  • else if Statement

    • Use the else if statement to specify 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 the condition1 is false and condition2 is true
          } else {
            //  block of code to be executed if the condition1 is false and condition2 is false
          }
                        
                      
    • EX :
                        
          if (time < 10) {
            greeting = "Good morning";
          } else if (time < 20) {
            greeting = "Good day";
          } else {
            greeting = "Good evening";
          }
                        
                      

Switch Statement

  • Use the switch statement to select one of many code blocks to be executed.
  • EX :
                  
      switch(expression) {
        case x:
          // code block
          break;
        case y:
          // code block
          break;
        default:
          // code block
      }
                  
                
  • This is how it works:
    • The switch expression is evaluated once.
    • The value of the expression is compared with the values of each case.
    • If there is a match, the associated block of code is executed.
    • If there is no match, the default code block is executed.
  • EX :
                  
      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";
      }
                  
                
    The getDay() method returns the weekday as a number between 0 and 6.
  • The break Keyword

    • When JavaScript reaches a break keyword, it breaks out of the switch block.
    • This will stop the execution inside the switch block.
    • It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
    • If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
  • The default Keyword

    • The default keyword specifies the code to run if there is no case match.
    • EX :
                        
        switch (new Date().getDay()) {
          case 6:
            text = "Today is Saturday";
            break;
          case 0:
            text = "Today is Sunday";
            break;
          default:
            text = "Looking forward to the Weekend";
        }
                        
                      
    • The default case does not have to be the last case in a switch block
    • If default is not the last case in the switch block, remember to end the default case with a break.
  • Common Code Blocks

    • Sometimes you will want different switch cases to use the same code.
    • EX :
                        
        switch (new Date().getDay()) {
          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";
        }
                        
                      
      In this example case 4 and 5 share the same code block, and 0 and 6 share another code block.
  • Switching Details

    • If multiple cases matches a case value, the first case is selected.
    • If no matching cases are found, the program continues to the default label.
    • If no default label is found, the program continues to the statement(s) after the switch.
  • Strict Comparison

    • The values must be of the same type to match.
    • A strict comparison can only be true if the operands are of the same type.
    • EX :
                        
        let x = "0";
        switch (x) {
          case 0:
            text = "Off";
            break;
          case 1:
            text = "On";
            break;
          default:
            text = "No value found";
        }
                        
                      

Conditional (Ternary) Operator

  • JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
  • Syntax : variablename = (condition) ? value1:value2
  • EX : let voteable = (age < 18) ? "Too young":"Old enough";
  • If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough".

try and catch

  • The try statement allows you to define a block of code to be tested for errors while it is being executed.
  • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
  • The JavaScript statements try and catch come in pairs:
                  
      try {
        Block of code to try
      }
      catch(err) {
        Block of code to handle errors
      }
                  
                
  • throw Statement

    • The throw statement allows you to create a custom error.
    • Technically you can throw an exception (throw an error).
    • The exception can be a JavaScript String, a Number, a Boolean or an Object.
    • If you use throw together with try and catch, you can control program flow and generate custom error messages.
  • EX:
    <!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { const message = document.getElementById("p01"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } } </script> </body> </html>
  • finally Statement

    • The finally statement lets you execute code, after try and catch, regardless of the result.
    • Syntax :
                        
        try {
          Block of code to try
        }
        catch(err) {
          Block of code to handle errors
        }
        finally {
          Block of code to be executed regardless of the try / catch result
        }
                        
                      
    • EX:
      <!DOCTYPE html> <html> <body> <h2>JavaScript try catch</h2> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { const message = document.getElementById("p01"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "is empty"; if(isNaN(x)) throw "is not a number"; x = Number(x); if(x > 10) throw "is too high"; if(x < 5) throw "is too low"; } catch(err) { message.innerHTML = "Input " + err; } finally { document.getElementById("demo").value = ""; } } </script> </body> </html>

JS Function Definitions

  • JavaScript functions are defined with the function keyword.
  • You can use a function declaration or a function expression.
  • Function Declarations

    • Syntax : function functionName(parameters) { // code to be executed }
    • Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).
    • EX:
      <!DOCTYPE html> <html> <body> <p>This example calls a function which performs a calculation 3*4:</p> <p id="demo"></p> <script> var x = myFunction(4, 3); document.getElementById("demo").innerHTML = x; function myFunction(a, b) { return a * b; } </script> </body> </html>
  • Function Expressions

    • A JavaScript function can also be defined using an expression.
    • A function expression can be stored in a variable.
    • EX:
      
        const x = function (a, b) {return a * b};
        let z = x(4, 3);
                        
    • The function above is actually an anonymous function (a function without a name).
    • The function above ends with a semicolon because it is a part of an executable statement.
  • The Function() Constructor

    • As you have seen in the previous examples, JavaScript functions are defined with the function keyword.
    • Functions can also be defined with a built-in JavaScript function constructor called Function().
    • EX:
                        
        const myFunction = new Function("a", "b", "return a * b");
        let x = myFunction(4, 3);
                        
                      
      You actually don't have to use the function constructor. The example above is the same as writing.
                        
        const myFunction = function (a, b) {return a * b};
        let x = myFunction(4, 3);
                        
                      
    • Self-Invoking Functions

      • Function expressions can be made "self-invoking".
      • A self-invoking expression is invoked (started) automatically, without being called.
      • Function expressions will execute automatically if the expression is followed by ().
      • You cannot self-invoke a function declaration.You have to add parentheses around the function to indicate that it is a function expression.
      • EX:
                          
          (function () {
            let x = "Hello!!";  // I will invoke myself
          })();
                          
                        
      • The function above is actually an anonymous self-invoking function (function without name).
  • Functions are Objects

    • JavaScript functions have both properties and methods.
    • The arguments.length property returns the number of arguments received when the function was invoked.
    • EX:
                        
        function myFunction(a, b) {
          return arguments.length;
        }
                        
                      
    • The toString() method returns the function as a string.
    • EX:
                        
        function myFunction(a, b) {
          return a * b;
        }
        let text = myFunction.toString();
                        
                      
  • Function Parameters and Arguments

    • Function parameters are the names listed in the function definition.
    • Function arguments are the real values passed to (and received by) the function.
    • Parameter Rules
      • JavaScript function definitions do not specify data types for parameters.
      • JavaScript functions do not perform type checking on the passed arguments.
      • JavaScript functions do not check the number of arguments received.
    • Default Parameters
      • If a function is called with missing arguments (less than declared), the missing values are set to undefined.
      • Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter.
      • EX:
        <!DOCTYPE html> <html> <body> <p>Setting a default value to a function parameter.</p> <p id="demo"></p> <script> function myFunction(x, y) { if (y === undefined) { y = 2; } return x * y; } document.getElementById("demo").innerHTML = myFunction(4); </script> </body> </html>
    • Arguments Object
      • JavaScript functions have a built-in object called the arguments object.
      • The argument object contains an array of the arguments used when the function was called (invoked).
      • This way you can simply use a function to find (for instance) the highest value in a list of numbers.
      • Finding the largest number:
        <!DOCTYPE html> <html> <body> <p>Finding the largest number.</p> <p id="demo"></p> <script> function findMax() { let max = -Infinity; for(let i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; } document.getElementById("demo").innerHTML = findMax(4, 6,30,1,55); </script> </body> </html>
      • Sum of all arguments:
        <!DOCTYPE html> <html> <body> <p>Sum of all arguments:</p> <p id="demo"></p> <script> function sumAll() { let sum = 0; for(let i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } document.getElementById("demo").innerHTML = sumAll(1, 123, 500, 115, 44, 88); </script> </body> </html>
  • JavaScript Function Invocation

    • The code inside a function is executed when the function is invoked.
    • It is common to use the term "call a function" instead of "invoke a function".
    • this Keyword
      • In JavaScript, the thing called this, is the object that "owns" the current code.
      • The value of this, when used in a function, is the object that "owns" the function.
      • Note that this is not a variable. It is a keyword. You cannot change the value of this.
      • EX:
                              
        const myObject = {
          firstName:"Ahmed",
          lastName: "Mohamed",
          fullName: function () {
            return this.firstName + " " + this.lastName;
          }
        }
        myObject.fullName(); 
                              
                            

JavaScript For Loop

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

  • For Loop

    • The for loop has the following syntax:
                        
        for (statement 1; statement 2; statement 3) {
          // code block to be executed
        }
                        
                      
    • Statement 1 is executed (one time) before the execution of the code block.
      • Normally you will use statement 1 to initialize the variable used in the loop (let i = 0).
      • This is not always the case, JavaScript doesn't care. Statement 1 is optional.
      • You can initiate many values in statement 1 (separated by comma):
                              
          for (let i = 0, len = cars.length, text = ""; i < len; i++) {
            text += cars[i] + <br>;
          }
                              
                            
      • And you can omit statement 1 (like when your values are set before the loop starts):
                              
          let i = 2;
          let len = cars.length;
          let text = "";
          for (; i < len; i++) {
            text += cars[i] + <br>;
          }
                              
                            
    • Statement 2 defines the condition for executing the code block.
      • Often statement 2 is used to evaluate the condition of the initial variable.
      • This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
      • If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
      • If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.
    • Statement 3 is executed (every time) after the code block has been executed.
      • Often statement 3 increments the value of the initial variable.
      • This is not always the case, JavaScript doesn't care, and statement 3 is optional.
      • Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
      • Statement 3 can also be omitted (like when you increment your values inside the loop):
                              
          let i = 0;
          let len = cars.length;
          let text = "";
          for (; i < len; ) {
            text += cars[i] + <br>;
            i++;
          }
                              
                            
    • Loop Scope

      • Using var in a loop:

        using var, the variable declared in the loop redeclares the variable outside the loop.

                              
          var i = 5;
          for (var i = 0; i < 10; i++) {
            // some statements
          }
          document.getElementById("demo").innerHTML = i;
                              
                            
      • Using let in a loop:

        using let, the variable declared in the loop does not redeclare the variable outside the loop.
        When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

                              
          let i = 5;
          for (let i = 0; i < 10; i++) {
            // some statements
          }
          document.getElementById("demo").innerHTML = i;
                              
                            
  • For In Loop

    • The JavaScript for in statement loops through the properties of an Object
    • Syntax :
                        
        for (key in object) {
          // code block to be executed
        }
                        
                      
    • EX :
                        
        const person = {fname:"John", lname:"Doe", age:25}; 
        let txt = "";
        for (let x in person) {
          txt += person[x] + <br>;
        }
        document.getElementById("demo").innerHTML = txt;
                        
                      
    • For In Over Arrays

      • The JavaScript for in statement can also loop over the properties of an Array.
      • Syntax :
                              
              for (variable in array) {
                // code block to be executed
              }
                              
                            
      • EX :
                              
              const numbers = [45, 4, 9, 16, 25];
              let txt = "";
              for (let x in numbers) {
                txt += numbers[x];
              }
              document.getElementById("demo").innerHTML = txt;
                              
                            
      • Do not use for in over an Array if the index order is important.
      • The index order is implementation-dependent, and array values may not be accessed in the order you expect.
      • It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.
    • Array.forEach()

      • The forEach() method calls a function (a callback function) once for each array element.
      • EX:
        <!DOCTYPE html> <html> <body> <h2>JavaScript Array.forEach()</h2> <p>Calls a function once for each array element.</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); document.getElementById("demo").innerHTML = txt; function myFunction(value, index, array) { txt += index + " => " + value + " in [" + array + "] <br> "; } </script> </body> </html>
  • For Of Loop

    • The JavaScript for of statement loops through the values of an iterable object.
    • It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.
    • Syntax :
                        
        for (variable of iterable) {
          // code block to be executed
        }
                        
                      
    • variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
    • iterable - An object that has iterable properties.
    • Examples
      Looping over an Array
                        
        const cars = ["BMW", "Volvo", "Mini"];
        let text = "";
        for (let x of cars) {
          text += x;
        }
                        
                      
      Looping over a String
                        
        let language = "JavaScript";
        let text = "";
        for (let x of language) {
        text += x;
        }
                        
                      
  • While Loop

    • The while loop loops through a block of code as long as a specified condition is true.
    • Syntax :
                        
        while (condition) {
          // code block to be executed
        }
                        
                      
    • EX: In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:
                        
        while (i < 10) {
          text += "The number is " + i;
          i++;
        }
                        
                      
    • If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
  • Do While Loop

    • The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
    • Syntax:
                        
        do {
          // code block to be executed
        }
        while (condition);
                        
                      
    • EX: The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
                        
        do {
          text += "The number is " + i;
          i++;
        }
        while (i < 10);
                        
                      
    • Do not forget to increase the variable used in the condition, otherwise the loop will never end!
  • Break and Continue

    • The break statement "jumps out" of a loop.
    •                   
        for (let i = 0; i < 10; i++) {
          if (i === 3) { break; }
          text += "The number is " + i + <br>;
        }
                        
                      
      the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3.
    • The continue statement "jumps over" one iteration in the loop.
    •                   
        for (let i = 0; i < 10; i++) {
          if (i === 3) { continue; }
          text += "The number is " + i + "<br>";
        }
                        
                      
      This example skips the value of 3
  • JavaScript Labels

    • To label JavaScript statements you precede the statements with a label name and a colon:
                        
        label:
        statements
                        
                      
      The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.
      Syntax:
                        
        break labelname;
        continue labelname;
                        
                      
    • EX:
      <!DOCTYPE html> <html> <body> <h2>JavaScript break</h2> <p id="demo"></p> <script> const cars = ["BMW", "Volvo", "Saab", "Ford"]; let text = ""; list: { text += cars[0] + "<br>"; text += cars[1] + "<br>"; break list; text += cars[2] + "<br>"; text += cars[3] + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>