Author: Saim Khalid

  • Function() Constructor

    The Function() Constructor

    The JavaScript Function() constructor can dynamically create a function object at the run time. The functions created using Function() constructor have global scope only.

    The Function() constructor can be used to define the function at the run time, but you should use the Function() constructor with caution as it can lead to vulnerabilities in the code.

    We can pass multiple arguments to the Function() constructor. All arguments except the last argument are the names of the parameters in the new function to be created. The last argument is the function body.

    Syntax

    Following is the syntax to use the Function() constructor to create an object of the function in JavaScript

    const obj =newFunction(arg1, arg2..., functionBody);

    The Function() constructor can be called with or without new keyword to create a new function object. All the parameters are JavaScript strings.

    Parameters

    • arg1, arg2… − These are arguments (optional) names that are used in function body. These are treated as the names of parameters in the function to be created.
    • functionBody − This argument contains the JavaScript statements comprising the function definition.

    Example

    In the example below, we have passed the 3 arguments to the Function() constructor. The first 2 arguments are arguments for the func() function, and the third is a body of the func() function.

    In the output, the func() function returns the multiplication of 5 and 7.

    <html><body><p id ="output"></p><script>const func =newFunction("p","q","return p * q");
    
      document.getElementById("output").innerHTML ="The value returned from the function is: "+func(5,7);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value returned from the function is: 35
    

    Example

    In the example below, we passed the one argument to the Function() constructor. So, it considers it as the function body. All the parameters except the last one are optional.

    In the output, you can observe that the func() function returns the sum of 10 and 20.

    <html><body><p id ="output"></p><script>const func =newFunction("return 10 + 20");
    
      document.getElementById("output").innerHTML ="The value returned from the function is: "+func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value returned from the function is: 30
    

    Function Declaration or Function Expression as Parameter

    Creating function using Function constructor is less efficient than creating function using a function declaration or function expression and calling it within the code.

    We can write multiple statements in the functionBody parameter of the Function() constructor. All statements are separated by semicolons. We can create a function with function declaration or function expression and pass it as a statement in the fucntionBody parameter.

    Example

    In this example, we defined a function sum with function expression and passed to the Function() constructor as a part of the parameter (functionBody). Here the return statement is required.

    <html><body><p id ="output"></p><script>const add =newFunction("const sum = function (a, b) {return  a+ b};  return sum",)();    
    
      document.getElementById("output").innerHTML =add(5,10)// 15&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In this example, we defined a function anonymous function with function declaration and passed to the Function() constructor as a part of the parameter (functionBody). Here the return statement at the end is not required.

    <html><body><p id ="output"></p><script>const sayHello =newFunction("return function (name) { return Hello, ${name} }",)();    
    
      document.getElementById("output").innerHTML =sayHello("world");// Hello, world&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Please note that in both the examples above, the new Function is self-invoked.

  • Default Parameters

    The default parameters in JavaScript are a feature that allows you to specify a default value for a function parameter. The concept of the default parameters was introduced in the ES6. We can initialize the parameters with the default values. So, if the function is called with missing argument or argument with an undefined value, it uses the default value of the parameter in the function.

    The default value of a function parameter is “undefined” in JavaScript. When a function is called with missing arguments the parameters are set to ‘undefined’. The undefined parameter values are acceptable but can generate unusual outcomes.

    Before the ES6 version of JavaScript, we needed to check whether the parameter value was “undefined” inside the function body. If yes, they need to initialize the parameter with the proper value.

    Let’s understand it via the example below.

    functionsum(p, q){return p + q;}sum(10,20);// 30sum(10);// NaNsum();// NaN

    In this example, we observe the following −

    • sum(10, 20) returns the sum of the two arguments, i.e., 30. Here both arguments are passed.
    • sum(10) returns NaN. Here only one argument is passed. The second parameter q is set to undefined. Mathematical operation on undefined returns NaN.
    • sum() also returns NaN. Here both arguments are missing. So they are set to undefined.

    When we call the function with missing argument values, it returns NaN which is unusual.

    To overcome this problem, we can use default parameter values to be used if function is called with missing argument values.

    Default Parameters Syntax

    The syntax to use the function default parameters in JavaScript is as follows

    functionfunctName(param1 = defaultValue1, param2 = DefaultValue2, ..){// Use parameters here}

    In the above syntax, the default value of the param1 is set to defaultValue1, and the default value of the param2 is set to defaultValue2.

    Let’s look at the example below −

    Example (Default parameters)

    In the below code, parameter p and q contains the 30 and 40 default values, respectively.

    In the output, unlike the first example, you can see that it returns the sum of the default parameter values when any argument is missing.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionsum(p = 30, q = 40){return p + q;}
    
      output.innerHTML +="sum(10, 20)  -&gt;  "+sum(10,20)+"&lt;br&gt;";// 10 + 20 = 30
      output.innerHTML +="sum(10)  -&gt;  "+sum(10)+"&lt;br&gt;";// 10 + 40 = 50
      output.innerHTML +="sum()  -&gt;  "+sum()+"&lt;br&gt;";// 30 + 40 = 70&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(10, 20) -> 30
    sum(10) -> 50
    sum() -> 70
    

    Passing an expression as a default parameter value

    We can pass an expression as a default parameter value to a JavaScript function. The expression can also contain the values of the previous parameters.

    Example

    We pass the expression as a default parameter value in the code below. The expression contains the value of the previous parameters.

    In the output of the second function call, you can observe that the value of the r is 100, which is equal to (p = 5) * (q = 10) * 2. We haven't passed any argument in the third function call, so all parameters take the default value.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionsum(p = 2, q = p * 2, r = p * q * 2){return p + q + r;}
    
      output.innerHTML +="sum(5, 10, 15)  -&gt;  "+sum(5,10,15)+"&lt;br&gt;";// 5 + 10 + 15 = 30
      output.innerHTML +="sum(5, 10)  -&gt;  "+sum(5,10)+"&lt;br&gt;";// 5 + 10 + (5 * 10 * 2) = 115
      output.innerHTML +="sum()  -&gt;  "+sum()+"&lt;br&gt;";// 2 + 4 + 16 = 22&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(5, 10, 15) -> 30
    sum(5, 10) -> 115
    sum() -> 22
    

    You can't use the uninitialized parameter in the expression. Otherwise, the code will raise a reference error.

    Passing Undefined Argument

    When you pass the undefined argument to the function call, the JavaScript function definition uses the default parameter values to avoid unnecessary errors.

    <html><body><p id="output"></p><script>let output = document.getElementById("output");functionsum(p = 24, q = 26){return p + q;}
    
    
      output.innerHTML +="sum(5, undefined)  -&gt;  "+sum(5,undefined)+"&lt;br&gt;";// 5 + 26 = 31 
      output.innerHTML +="sum(undefined)  -&gt;  "+sum(undefined)+"&lt;br&gt;";// 24 + 26 = 50&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(5, undefined) -> 31
    sum(undefined) -> 50
    

    Function expression as a default parameter

    The JavaScript function expression can also be paased as a fucntion default parameter.

    In the example below, the getNum() function returns 5. We used the function expression as a default value of parameter q.

    The output shows that when the second argument is missing, the parameter uses the value returned from the getNum() function.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functiongetNum(){return5;}functionmul(p = 5, q = getNum()){return p * q;}
    
    
      output.innerHTML +="mul(10)  -&gt; "+mul(10)+"&lt;br/&gt;";
      output.innerHTML +="mul() -&gt; "+mul()+"&lt;br/&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    mul(10) -> 50
    mul() -> 25
    

    Function Optional Parameters

    The function default parameters are also called the optional parameters, as the function will give output without any error even if we don't pass the arguments for the optional parameter.

    You should pass all required parameters at the start and optional parameters at the function end.

    functionsum(p, q=10){return p+q;}

    In the above JavaScript code snippet, we put the optional parameter q at the end of the parameter list.

    Example

    The JavaScript code below shows that the first parameter is required, and the second parameter is optional.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionfunc(p, q=10){return p + q;}
    
      output.innerHTML +="func(10, 20) -&gt; "+func(10,20);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    func(10, 20) -> 30
    

    If we put the optional parameter at beginning, we may encounter error while calling the function with undefined value.

    functionsum(p=10, q){return p+q;}sum(,10)// Errorsum(10)// NaN

    So, if you pass only a single argument, it replaces the default value of the first parameter, and the second parameter remains undefined.

  • Function Parameters

    Function Parameters and Arguments

    The function parameters in JavaScript are variables listed inside the parentheses in the function definition. A function can have multiple parameters separated by commas. The function arguments are the values that are passed to function when it is called. We define function listing the parameters and call the function passing the arguments.

    The number of arguments that you pass to the function must match the number of parameters in the function definition. If not, you may get unexpected result.

    Syntax

    The syntax to use function parameters in JavaScript is as follows −

    functionfunctionName(parameter1, parameter2, parameter3){//statements}

    In the above syntax, the function parameters are ‘parameter1’, ‘parameter2’, and ‘parameter3’.

    Parameter Rules

    • JavaScript functions don’t check the number of arguments passed while invoking the function.
    • Don’t need to specify the data type of function parameters.
    • JavaScript compiler doesn’t perform the type-checking on the passed function arguments.

    The JavaScript function arguments are the variables or values passed to the function while invoking it.

    functionName(10, b,'Hello');

    In the above syntax, the first argument is of number data type, and the third is of string data type. The second argument is variable, which is defined earlier in the code.

    Example: Function Parameters and Arguments

    In the below code, the mult() function takes 4 parameters. You can observe that the type of parameters is not defined. We multiply the parameter values in the function body and return the resultant value.

    While calling the function, we passed 4 number values as a function argument. Users can observe the output of the function for the different function arguments.

    <html><body><p id ="output"></p><script>functionmult(a, b, c){let res = a * b * c;return res;}let ans =mult(2,3,4);
    
      document.getElementById("output").innerHTML ="The multiplication of 2, 3, and 4 is "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication of 2, 3, and 4 is 24
    

    Argument Object

    In JavaScript, each function can have an 'arguments' object. It contains all passed arguments while invoking the function in the array format. We can traverse through the array and get each argument even if the function's parameters are not specified.

    Example

    In the example below, the function definition doesn't contain any parameters, but we have passed the 4 arguments while calling the function. So, we traverse through the arguments[] array using the loop inside the function body to access all arguments one by one.

    In the function body, we merge all arguments and return the 'final' string.

    <html><body><p id ="output"></p><script>functionmerge(){let final ="";for(let p =0; p < arguments.length; p++){
    
            final += arguments[p]+" ";}return final;}let ans =merge("Hi","I","am","John!");
      document.getElementById("output").innerHTML ="The merged string is: "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The merged string is: Hi I am John!
    

    Passing Arguments by Value

    In the function, when you pass the argument by value to a function call, it sends the argument value to the parameter of the function definition. So, when you update the function parameters, the function argument doesn't get changed.

    Example

    In the below code, we have defined the 'val1' and 'val2' variables outside the function and passed them as a function argument.

    In the function body, we change the parameter value. In the output, you can see that even after updating the parameter value, the actual value of the 'val1' and 'val2' is not changed.

    <html><head><title> JavaScript - Arguments are passed by value </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionupdate(val1, val2){
    
         val1 =20;
         val2 =30;}var val1 ="Hello";var val2 ="World";
      output.innerHTML +="Before calling the function! &lt;br&gt;";
      output.innerHTML +="val1 = "+ val1 +", val2 = "+ val2 +"&lt;br&gt;";update(val1, val2);
      output.innerHTML +="After calling the function! &lt;br&gt;";
      output.innerHTML +="val1 = "+ val1 +", val2 = "+ val2 +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Before calling the function!
    val1 = Hello, val2 = World
    After calling the function!
    val1 = Hello, val2 = World
    

    Passing Arguments by Reference

    When you pass the object as an argument, the function sends the address of the object as a parameter to the function definition. So, it is called the arguments are passed by reference.

    In the function body, if you change the property of an object, it will also reflect the outside of the function.

    Example

    In the below code, we pass the 'obj' object as a function argument. In the function body, we change the value of the 'domain' property of the object.

    In the output, you can observe that the value of the 'domain' property is changed even outside the function after invoking the function as objects are passed by reference.

    <html><head><title> JavaScript - Arguments are passed by reference </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionupdate(obj){
    
         obj.domain ="www.tutorialspoint.com";}var obj ={
         domain:"www.google.com",}
      output.innerHTML +="Before calling the function! &lt;br&gt;";
      output.innerHTML +="domain = "+ obj.domain +"&lt;br&gt;";update(obj);
      output.innerHTML +="After calling the function! &lt;br&gt;";
      output.innerHTML +="domain = "+ obj.domain +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Before calling the function!
    domain = www.google.com
    After calling the function!
    domain = www.tutorialspoint.com
    

  • Function Expressions

    The function expression allows us to define a JavaScript function in an expression. JavaScript functions are defined using a function declaration or a function expression. The main difference between them is the function name. The function name can be omitted in function expressions. This helps to create anonymous functions in JavaScript. We can store the function expression in the variable and use that variable to invoke the function expression.

    Syntax

    The syntax of function expression in JavaScript is as follows

    function(parameter-list){
    
    statements
    };

    We can use a variable to store a JavaScript function expression

    constvarName=function(parameter-list){
    
    statements
    };

    Here the function expression is stored in the variable, varName. Once the function is assigned to a variable, the variable is used to invoke the function. Lets look at the example below

    constsum=function(x, y){return x + y;};let z =sum(2,3);

    In the above code the function expression is assigned to the variable sum. The variable sum is used as function to invoke the function.

    Please note there is no name after the function keyword. The function expression allows to define anonymous function.

    Named Function Expression

    We can define a named function as a function expression

    constsum=functionaddNumbers(x, y){return x + y;};let z =sum(2,3);

    But we need to invoke the function using the variable only. We cant use the function name to invoke the function.

    Immediately Invoked Function Expression

    A function expression can be used as the IIFE (immediately invoked function expression) which is invoked as soon as defined.

    (functiongreet(){alert("Hello World");})();

    Examples

    Example: Function Expression

    In the example below, we stored the function expression in the sum variable. The function expression adds two numbers and prints in the output.

    At last, we used the sum variable to invoke the function expression stored in that.

    <html><body><p id ="output"></p><script>constsum=function(){let a =10;let b =20;
    
         document.getElementById("output").innerHTML ="The sum of "+ a +" and "+ b +" is "+(a + b);}sum();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 10 and 20 is 30
    

    Example: The return statement in function expression

    The below code demonstrates the using the return statement in the function expression. You can use the return statement inside the function expression as you use it in the function definition.

    In the below code, the function returns the multiplication value of two numbers.

    <html><body><p id ="output"></p><script>constmul=function(a, b){return a * b;}let result =mul(4,5);
    
      document.getElementById("output").innerHTML ="The returned value from the function is "+ result;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The returned value from the function is 20
    

    Example: Using the function expression as a value

    The below example demonstrates using the function expression as a value. Here, we stored the function expression in the num variable and multiplied its returned value by 3.

    You may return the random number from the function expression and use the function expression as a value.

    <html><body><p id ="output"></p><script>constnum=function(){return2;}let result =num()*3;
    
      document.getElementById("output").innerHTML ="The multiplication value is "+ result;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication value is 6
    

    Example: Nested function expression

    The example below demonstrates using the nested function expression. We defined the function expression and stored it in the num variable. In the function expression body, we defined another function expression and stored it in the decimal variable.

    We call the decimal() function expression in the parent function expression and return its value. When we call the num() function expression, it returns the value returned by the decimal() function expression.

    <html><body><p id ="output"></p><script>constnum=function(){constdecimal=function(){return5;}returndecimal();}
    
      document.getElementById("output").innerHTML ="The returned value from the function is "+num();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The returned value from the function is 5
  • Functions

    function in JavaScript is a group of reusable code that can be called anywhere in your program. It eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

    Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

    JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.

    Function Definition

    Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

    All statements you need to execute on the function call must be written inside the curly braces.

    Syntax

    The basic syntax to define the function in JavaScript is as follows −

    functionfunctionName(parameter-list){
    
    statements
    }

    This type of function definition is called function declaration or function statement. We can also define a function using function expression. We will discuss function expression in details in the next chapter.

    The following example defines a function called sayHello that takes no parameter −

    functionsayHello(){alert("Hello there");}

    Function Expression

    The Function expression in JavaScript allows you to define a function as an expression. The function expression is similar to the anonymous function declaration. The function expression can be assigned to a varaible.

    The syntax of function expression in JavaScript is as follows

    constvarName=function(parameter-list){
    
    statements
    };

    In the example below, we have defined a JavaScript function using function expression and assigned it to a vriable name myFunc.

    constmyFunc=function(x, y){return x + y;};

    Calling a Function

    To invoke a function somewhere later in the script, you would simply need to write the name of that function with the parantheses () as shown in the following code.

    Example

    The below code shows the button in the output. When you click the button, it will execute the sayHello() function. The sayHello() function prints the “Hello there!” message in the output.

    <html><head><script type="text/javascript">functionsayHello(){alert("Hello there!");}</script></head><body><p>Click the following button to call the function</p><form><input type="button" onclick="sayHello()" value="Say Hello"></form><p> Use different text in the write method and then try...</p></body></html>

    Function Parameters

    Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.

    Example

    Try the following example. We have modified our sayHello function here. Now it takes two parameters.

    <html><head><script type ="text/javascript">functionsayHello(name, age){
    
            document.write(name +" is "+ age +" years old.");}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to call the function&lt;/p&gt;&lt;form&gt;&lt;input type ="button" onclick ="sayHello('Zara', 7)" value ="Say Hello"&gt;&lt;/form&gt;&lt;p&gt;Use different parameters inside the function and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The return Statement

    A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

    For example, you can pass two numbers in a function, and then you can expect the function to return their multiplication in your calling program.

    Example

    The code below defines a function that concatenates two parameters before returning the resultant in the calling program. Also, you may take a look that how it returns the value using the return statement.

    <html><head><script type="text/javascript">functionconcatenate(first, last){var full;
    
         full = first + last;return full;}functionsecondFunction(){var result;
         result =concatenate('Zara ','Ali');alert(result);}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to call the function&lt;/p&gt;&lt;form&gt;&lt;input type="button" onclick="secondFunction()" value="Call Function"&gt;&lt;/form&gt;&lt;p&gt;Use different parameters inside the function and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Functions as Variable Values

    In JavaScript, functions can be used same as other variables. Thats why JavaScript is said to have a first-calss functions. The functions can be passed as arguments to the other functions.

    Example

    In the example below, we have declared a function using function expression and use the function to concatenate with other string.

    <html><body><div id ="output"></div><script>constmyFunc=function(){return"Hello ";};
    
      document.getElementById("output").innerHTML =myFunc()+"Users.";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    We have covered two important concepts in separate chapters.

    • JavaScript Nested Functions
    • JavaScript Function Literals
  • User Defined Iterators

    In JavaScript, an iterable is an object which has Symbol.iterator() method in the object prototype. Some examples of iterable are array, set, map, string, etc. The Symbol.iterator() method returns an object containing the next() method is called iterator. Here, the next() method returns the elements of iterable in each call.

    The next() Method

    The next() method of the iterator object returns an object containing two key-value pairs given below.

    • value − The value key contains the element as a value.
    • done − The done key contains the boolean value. It contains true if all iterations of iterable are finished. Otherwise, it contains false.

    Example

    In the example below, we have created the array and stored the array iterator in the ‘iter’ variable. After that, we use the next() method of the iterator object to get the next value.

    The output shows that the next() method returns the object containing ‘value’ and ‘done’ properties. The last iteration returns the object containing the ‘done’ property only.

    <html><head><title> JavaScript - Iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");const nums =[10,72,45];const iter = nums[Symbol.iterator]();
    
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"value":10,"done":false}
    {"value":72,"done":false}
    {"value":45,"done":false}
    {"done":true}
    

    User-defined Iterators

    In the above part, we have looked at how an iterator works in JavaScript. The Symbol.iterator() method returns the object containing the next() method, and whenever we execute the next() method, it returns an object.

    So, in the same way, we can implement the user-defined iterators.

    Example

    In the example below, we have created the custom iterator using the function. The function returns the object containing the next() method. The next() method returns the object containing the array element and the false boolean value from the nth index if n is less than the array length. If the n is greater than or equal to the array's length, it returns the object containing only the 'done' property with a 'true' boolean value.

    After that, we use the iter.next() syntax to get the next array element.

    <html><head><title> JavaScript - User defined iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functioncustomIterator(chars){// To track indexlet n =0;return{// next() methodnext(){if(n < chars.length){return{
    
                     value: chars[n++],
                     done:false}}return{
                  done:true}}}}const chars =['A','C','E'];const iter =customIterator(chars);
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(iter.next())+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"value":"A","done":false}
    {"value":"C","done":false}
    {"value":"E","done":false}
    {"done":true}
    {"done":true}
    

    The above code uses the function to define the iterator. So, you can't use the forof loop with the iterator. Let's learn to define the iterator using the object in the example below.

    Example

    In the example below, we add a function as a value of the 'Symbol.iterator' key. The function returns the next() method. The next() method returns the odd numbers. If the value of the odd number is 9, it finishes the iteration by returning the {done: true} object.

    Here, we created the iterator using the object. So, you can use the forof loop. The loop will automatically execute the next() method of the iterator and returns a value of the 'value' property of the object returned by the next() method.

    <html><head><title> JavaScript - User defined iterators </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");// Empty object
    
       oddNum ={};// Add iterator 
       oddNum[Symbol.iterator]=function(){let p =-1;
          done =false;return{next(){
                p +=2;if(p ==9)return{ done:true}return{ value: p, done: done };}};}for(const odd of oddNum){
          output.innerHTML += odd +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    1
    3
    5
    7
    

    You should create user-defined iterators when they need customization in the traversal of iterable. For example, to traverse alternative array elements, to get even or odd numbers from an iterator, etc.

  • Switch Case

    The JavaScript switch case is a conditional statement is used to execute different blocks of code depending on the value of an expression. The expression is evaluated, and if it matches the value of one of the case labels, the code block associated with that case is executed. If none of the case labels match the value of the expression, the code block associated with the default label is executed.

    You can use multiple if…elseif 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.

    Flow Chart

    The following flow chart explains a switch-case statement works.

    Switch case

    Syntax

    The objective of a 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)}
    • break − The statement keyword indicates the end of a particular case. If the ‘break’ statement were omitted, the interpreter would continue executing each statement in each of the following cases.
    • default − The default keyword is used to define the default expression. When any case doesn’t match the expression of the switch-case statement, it executes the default code block.

    Examples

    Let’s understand the switch case statement in details with the help of some examples.

    Example

    In the example below, we have a grade variable and use it as an expression of the switch case statement. The switch case statement is used to execute the different code blocks according to the value of the grade variable.

    For the grade ‘A’, it prints the ‘Good job’ in the output and terminates the switch case statement as we use the break statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let grade ='A';
    
      output.innerHTML +="Entering switch block &lt;br /&gt;";switch(grade){case'A': output.innerHTML +="Good job &lt;br /&gt;";break;case'B': output.innerHTML +="Passed &lt;br /&gt;";break;case'C': output.innerHTML +="Failed &lt;br /&gt;";break;default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Good job
    Exiting switch block
    

    Break statements play a major role in switch-case statements. Try the following example that uses switch-case statement without any break statement.

    Example: Without break Statement

    When we don't use the 'break' statement with any case of the switch case statement, it continues executing the next case without terminating it.

    In the below code, we haven't used the break statement with the case 'A' and 'B'. So, for the grade 'A', it will execute the statement of cases A, B, and C, and then it will terminate the execution of the switch case statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let grade ='A';
    
      output.innerHTML +="Entering switch block&lt;br /&gt;";switch(grade){case'A': output.innerHTML +="Good job &lt;br /&gt;";case'B': output.innerHTML +="Passed &lt;br /&gt;";case'C': output.innerHTML +="Failed &lt;br /&gt;";default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Good job
    Passed
    Failed
    Unknown grade
    Exiting switch block
    

    Example: Common Code Blocks

    Sometimes, developers require to execute the common code block for the multiple values of the expression. It is very similar to the OR condition in the if-else statement.

    In the below code, we execute the same code block for cases A and B, and C and D. You may try to change the value of the grade variables and observe the output.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var grade ='C';
    
      output.innerHTML +="Entering switch block &lt;br /&gt;";switch(grade){case'A':case'B': output.innerHTML +="Passed &lt;br /&gt;";break;case'C':case'D': output.innerHTML +="Failed! &lt;br /&gt;";break;default: output.innerHTML +="Unknown grade &lt;br /&gt;";}
      output.innerHTML +="Exiting switch block";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering switch block
    Failed!
    Exiting switch block
    

    Example: Strict Comparison

    The switch case statement compares the expression value with the case value using the strict equality operator.

    The 'num' variable contains the integer value in the code below. In the switch case statement, all cases are in the string. So, the code executes the default statement.

    <html><head><title> JavaScript - Switch case statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let num =10;switch(num){case'10': output.innerHTML +="10 Marks!";break;case'11': output.innerHTML +="11 Marks!";break;default: output.innerHTML +="Input is not a string!";}</script></body></html>

    Output

    Input is not a string!
    
  • Continue Statement

    The continue statement in JavaScript is used to skip the current iteration of a loop and continue with the next iteration. It is often used in conjunction with an if statement to check for a condition and skip the iteration if the condition is met.

    The JavaScript continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

    Syntax

    The syntax of continue statement in JavaScript is as follows −

    continue;ORcontinue label;

    We can use the continue statement inside the loops like for loop, while loop, dowhile loop, etc.

    We will learn to use the continue statement with the label statement in the upcoming chapter.

    Continue statement with for loop

    The example below uses the continue statement with the for loop. In the loop, when the value of the x is 3, it will execute the continue statement to skip the current iteration and move to the next iteration.

    In the output, you can see that the loop doesnt print 3.

    Example

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;5; x++){if(x ==3){continue;// skip rest of the loop body}
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1
    2
    4
    Exiting the loop!
    

    Continue statement with while loop

    We used the while loop with the continue statement in the example below. In each iteration of the while loop, we increment the x's value by 1. If the value of the x is equal to 2 or 3, it skips the current iteration and moves to the next iteration.

    In the output, you can see that the code doesnt print 2 or 3.

    Example

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var x =1;
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";while(x &lt;5){
         x = x +1;if(x ==2|| x ==3){continue;// skip rest of the loop body}
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    4
    5
    Exiting the loop!
    

    Continue statement with the nested loop

    You can use the continue statement with nested loops and skip the iteration of the parent loop or child loop.

    Example

    The parent loop traverses the 1 to 5 elements in the code below. In the parent loop, we used the continue statement to skip the iteration when the value of x is 2 or 3. Also, we have defined the nested loop. In the nested loop, we skip the loop iteration when the value of y is 3.

    In the output, you can observe the value of x and y. You wont see 2 or 3 values for x and 3 for y.

    <html><head><title> JavaScript - Continue statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;5; x++){if(x ==2|| x ==3){continue;// skip rest of the loop body}for(let y =1; y &lt;5; y++){if(y ==3){continue;}
            output.innerHTML += x +" - "+ y +"&lt;br /&gt;";}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1 - 1
    1 - 2
    1 - 4
    4 - 1
    4 - 2
    4 - 4
    Exiting the loop!
    
  • Break Statement

    The break statement in JavaScript terminates the loop or switch case statement. When you use the break statement with the loop, the control flow jumps out of the loop and continues to execute the other code.

    The break statement can also be used to jump a labeled statement when used within that labeled statement. It is a useful tool for controlling the flow of execution in your JavaScript code.

    Syntax

    The syntax of break statement in JavaScript is as follows −

    break;ORbreak[label];

    The label is optional with a break statement.Note In the next chapter, we will learn to use the break statement with the label inside the loop.

    Flow Chart

    The flow chart of a break statement would look as follows −

    Break Statement

    Example (break statement with for loop)

    In the example below, we used the for loop to make iterations. We added the conditional expression in the loop using the ‘if’ statement. When the value of ‘x’ is 5, it will ‘break’ the loop using the break statement.

    The below code prints only 1 to 4 values in the output.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;10; x++){if(x ==5){break;// breaks out of loop completely}
            output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1
    2
    3
    4
    Exiting the loop!
    

    Example (break statement with the while loop)

    The code below demonstrates the while loop with the 'break' statement. In the while loop, whenever the value of x is either 3 or 7, it will terminate the loop using the 'break' statement.

    In the code, we update the value after checking the condition. So, it will print 3 first and then terminate the loop in the next iteration.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");var x =1;
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";while(x &lt;10){if(x ==3|| x ==7){break;// breaks out of loop completely}
         x = x +1;
         output.innerHTML += x +"&lt;br /&gt;";}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    2
    3
    Exiting the loop!
    

    Break statement with nested loops

    You can use the 'break' statement to jump out of any loop when you have nested loops. For example, if you use the 'break' statement with the parent loop, the code will also terminate all iterations of the nested loop. Using the 'break' statement with the nested loop will terminate only the nested loop.

    Example

    In the example below, x is a looping variable for the parent loop, and y is a looping variable for a child loop.

    In the nested loop, whenever y becomes 3, it will break the loop; in the outer loop, whenever x becomes 3, it will break the loop. You won't see x > 3 or y > 2 in the output.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop. &lt;br /&gt; ";for(let x =1; x &lt;10; x++){for(let y =1; y &lt;10; y++){if(y ==3){break;// breaks inner loop}
            output.innerHTML += x +" "+ y +"&lt;br /&gt;";}if(x ==3){break;// break outer loop}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop.
    1 1
    1 2
    2 1
    2 2
    3 1
    3 2
    Exiting the loop!
    

    Break statement with switch case statement

    The switch case statement executes one of the code blocks from multiple based on the conditional expression. The 'break' statement terminates the switch case statement after matching one or more cases with the conditional expression's value.

    Example

    In the below code, we used the 'break' statement with each case. Here, the value of variable p works as a conditional expression for the switch case statement. It matches with 'case 10'. So, the code will execute that particular code block and terminate the switch case statement using the 'break' statement.

    <html><head><title> JavaScript - Break statement </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");var p =10;switch(p){case10:
    
            output.innerHTML ="p is 10";break;case20:
            output.innerHTML ="p is 20";break;case30:
            output.innerHTML ="p is 30";break;default:
            output.innerHTML ="p is not 10, 20 or 30";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    p is 10
    

  • Loop Control

    JavaScript Loop Control

    JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.

    To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. Also, JavaScript allows developers to use labels to name the loop.

    We have explained the keywords in the below table, which can be used to control the loop.

    KeywordExplanation
    breakThe ‘break’ keyword is used to come out of the loop.
    continueThe ‘continue’ keyword is used to skip the current iteration of the loop.
    labelThe ‘label’ is not a keyword, but you can use any identifier followed by a colon (:) to give a label to the loop. After that, you can use the label to target the particular loop with the break and continue keyword.

    In the upcoming chapters, we will learn in detail about the break, continue and label statements.

    The break Statement

    The JavaScript break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

    Flow Chart

    The flow chart of a break statement would look as follows −

    Break Statement

    Example

    The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches −

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");let x =1;
    
      coutput.innerHTML ="Entering the loop&lt;br&gt; ";while(x &lt;20){if(x ==5){break;// breaks out of loop completely}
         x = x +1;
         coutput.innerHTML +=  x +"&lt;br&gt;";}         
      coutput.innerHTML +="Exiting the loop!&lt;br&gt; ";&lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop
    2
    3
    4
    5
    Exiting the loop!
    Set the variable to different value and then try...
    

    The continue Statement

    The JavaScript continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

    Example

    This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 −

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");let x =1;
    
      coutput.innerHTML ="Entering the loop&lt;br&gt; ";while(x &lt;10){
         x = x +1;if(x ==5){continue;// skip rest of the loop body}
         coutput.innerHTML +=  x +"&lt;br&gt;";}         
      coutput.innerHTML +="Exiting the loop!&lt;br&gt; ";&lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop
    2
    3
    4
    6
    7
    8
    9
    10
    Exiting the loop!
    Set the variable to different value and then try...
    

    Using Labels to Control the Flow

    Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.

    Line breaks are not allowed between the 'continue' or 'break' statement and its label name. Also, there should not be any other statement in between a label name and associated loop.

    Try the following two examples for a better understanding of Labels.

    Example 1

    The following example shows how to implement Label with a break statement.

    In the example below, we have given the 'outerloop' and 'innerloop' labels to the loop.

    We used the 'break' statement in the nested loop with the label. In the output, you can see that it breaks the outer loop from the inner loop.

    <html><body><div id ="output"></div><script>const coutput = document.getElementById("output");
    
      output.innerHTML ="Entering the loop!&lt;br /&gt; ";
      outerloop:// This is the label name         for(let i =0; i &lt;5; i++){
         output.innerHTML +="Outerloop: "+ i +"&lt;br /&gt;";
         innerloop:for(let j =0; j &lt;5; j++){if(j &gt;3)break;// Quit the innermost loopif(i ==2)break innerloop;// Do the same thingif(i ==4)break outerloop;// Quit the outer loop
            output.innerHTML +="Innerloop: "+ j +" &lt;br /&gt;";}}        
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop!
    Outerloop: 0
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 1
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 2
    Outerloop: 3
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Outerloop: 4
    Exiting the loop!
    

    Example 2

    In the below code, we use the continue statement with a label inside the nested loop to skip the current iteration of the outer loop. Whenever the value of q becomes 3, it skips the execution of the remaining code of the current iteration and starts a new iteration.

    <html><head><title> JavaScript - Label statement </title></head><body><p id ="output"></p><script>let output = document.getElementById("output");
    
      output.innerHTML +="Entering the loop!&lt;br /&gt; ";
      outerloop:// This is the label namefor(let p =0; p &lt;3; p++){
         output.innerHTML +="Outerloop: "+ p +"&lt;br /&gt;";for(let q =0; q &lt;5; q++){if(q ==3){continue outerloop;}
            output.innerHTML +="Innerloop: "+ q +"&lt;br /&gt;";}}
      output.innerHTML +="Exiting the loop!&lt;br /&gt; ";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering the loop!
    Outerloop: 0
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Outerloop: 1
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Outerloop: 2
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Exiting the loop!