Blog

  • Function call() Method

    Function call() Method

    The Function call() method allows us to invoke a function given a specific value for this and arguments provided individually. When a normal function is called, the value of this inside the function is the object that the function was accessed on. We can manipulate the this value and can assign an arbitrary object to this by using the call() method. In other word, we can call existing function as a method of an object without attaching the function to the object as a method.

    In JavaScript, every function is a Function object. The Function object provides properties and methods for functions. These properties and methods are defined on Function.prototype and shared by all Function instances. Some of the important methods provided by the Function object are call(), apply() and bind() methods.

    Let us understand the syntax of the Function call() method.

    Syntax

    The syntax of Function call() method in JavaScript is as follows −

    funcName.call(thisArg, arg1, arg2,... argN);

    In the above syntax, the ‘funcName’ is the name of the function to be called.

    Parameters

    • thisArg − It represents the context for the function. It is an object whose properties or methods we need to access using the ‘this’ keyword inside the function.
    • arg1, arg2, … argN − It is N arguments to pass to the function. They are optional arguments.

    By default, the context of the function is a global (window) object. So, the ‘this’ keyword refers to the ‘window’ object.

    Return value

    The call() method returns the value returned from the function.

    Examples

    Let’s understand JavaScript Function call() method with the help of some examples.

    Function call() method without specifying arguments

    In the example below, we have defined the test() function. We have invoked the function using the function name and call() method. In both cases, the function prints the same output. So, when you don’t pass any arguments, the call() method gives the same output as a normal function call.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>functiontest(){return"The function is invoked!";}
    
        
      document.getElementById("output1").innerHTML =test();
      document.getElementById("output2").innerHTML =test.call();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function is invoked!
    The function is invoked!
    

    Function call() method with 'this' argument only

    As we discussed above, 'this' argument is used to specify the context of the function. Here, we have defined the person1 and person2 objects containing the name and age properties.

    We passed the object as an argument of the call() method. In the printMessage() function, we access the object's properties, which is passed as a function argument using the 'this' keyword.

    In the output, you can observe that it prints the object properties' value according to the object passed as an argument of the call() method.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>functionprintMessage(){return"The age of the "+this.name +" is "+this.age;}const person1 ={
    
      name:"John Doe",
      age:22,}const person2 ={
      name:"Jane Doe",
      age:40,}
    document.getElementById("output1").innerHTML =printMessage.call(person1); document.getElementById("output2").innerHTML =printMessage.call(person2);</script></body></html>

    Output

    The age of the John Doe is 22
    The age of the Jane Doe is 40
    

    Function call() method with multiple arguments

    The example below demonstrates passing multiple arguments to the call() method. The printSum() function returns the sum of function parameters and object properties in the below code.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output"></p><script>functionprintSum(p1, p2){return(this.num1 +this.num2 + p1 + p2);}const nums ={
    
      num1:5,
      num2:10,}const ans =printSum.call(nums,40,32);
    document.getElementById("output").innerHTML ="Total sum is "+ ans;</script></body></html>

    Output

    Total sum is 87
    

    When you pass the 'this' keyword as the first argument of the call() method instead of an object, it specifies the function itself as a function context.

    Using a method of different object

    Using Function call() method, an object can use a method that is defined in other object. In the below example, we create three objects student, student1 and student2. We define a method getAge() of the object student. This getAge() method is used by the other two objects (student1 and student2) to access the age. The objects student1 and student2 are passed as arguments to the call() method.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>const student ={getAge:function(){returnthis.age;}}const student1 ={
    
      name:"John",
      age:22}const student2 ={
      name:"Doe",
      age:18}
    document.getElementById("output1").innerHTML =student.getAge.call(student1); document.getElementById("output2").innerHTML =student.getAge.call(student2);</script></body></html>

    The Function call() and apply() methods are the same but with minor difference as call() method accepts a list of arguments but the apply() method accepts an array of arguments. Let's understand the Function apply() method in detail in the next chapter this tutorial.

  • Function Invocation

    Function Invocation

    The function invocation in JavaScript is the process of executing a function. A JavaScript function can be invoked using the function name followed by a pair of parentheses. When you write a function code in JavaScript, it defines the function with expressions and statements. Now, to evaluate these expressions, it is necessary to invoke the function. The function invocation is the synonym of the function call or function execution.

    A JavaScript function can be defined using function declaration or function expression. The code inside the curly braces in the function definition are not executed when function is defined. To execute the code, we need to invoke the function.

    The call a function and invoke a function are two interchangeable terms are commonly used. But we can invoke a function without calling it. For example, self-invoking functions are invoked without calling them.

    Syntax

    The syntax of function invocation in JavaScript is as follows

    functionName()ORfunctionName(arg1, arg2,... argN);

    Here ‘functionName’ is the function to be invoked. We can pass as many arguments as the number of parameters listed in function definition.

    Example

    In the example below, we have defined the merge() function taking two parameters. After that, we used the function name to invoke the function by passing the arguments.

    <html><body><p id ="output"></p><script>functionmerge(str1, str2){return str1 + str2;}
    
      document.getElementById("output").innerHTML =merge("Hello"," World!");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello World!
    

    Invocation of Function Constructor

    When you invoke a function with the 'new' keyword, it works as a function constructor. The function constructor is used to create an object from the function definition.

    Syntax

    Following is the syntax to invoke the function as a constructor.

    const varName =newfuncName(arguments);

    In the above syntax, we invoked the function with a 'new' keyword and passed the arguments.

    Example

    In the example below, we use the function as an object template. Here, the 'this' keyword represents the function object, and we use it to initialize the variables.

    After that, we invoke the function car with the 'new' keyword to create an object using the function template.

    <html><body><p id ="output"> The ODCar object is:</p><script>functionCar(name, model, year){this.name = name;this.model = model;this.year = year;}const ODCar =newCar("OD","Q6",2020);
    
      document.getElementById("output").innerHTML +=JSON.stringify(ODCar);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The ODCar object is: {"name":"OD","model":"Q6","year":2020}
    

    Object Method Invocation

    We haven't covered JavaScript objects yet in this tutorial but we will cover it in upcoming chapters. Here, let's learn the object method invocation in short.

    The JavaScript object can also contain the function, and it is called the method.

    Syntax

    Following is the syntax below to invoke the JavaScript object method.

    obj.func();

    In the above syntax, the 'obj' is an object containing the method, and 'func' is a method name to execute.

    Example

    In the example below, we have defined the 'obj' object containing the 'name' property and the 'getAge()' method.

    Outside the object, we access the method by the object reference and invoke the method. In the output, the method prints 10.

    <html><body><p id ="output">The age of John is:</p><script>const obj ={
    
         name:"John",getAge:()=&gt;{return10;}}
      document.getElementById("output").innerHTML +=  obj.getAge();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The age of John is: 10
    

    Self-Invoking Functions

    The self-invoking functions in JavaScript are executed just after they are defined. There is no need to call these types of function to invoke them. The self-invoking functions are always defined using anonymous function expression. These types of functions are also called immediately invoked function expressions (IIFEs). To invoke these function, we wrap the function expression within a grouping operator (parentheses) and then add a pair of parentheses.

    Example

    Try the following example. In this example, we define a function to show a "Hello world" message in alert box.

    <html><head><script>(function(){alert("Hello World")})();</script></head><body></body></html>

    Other methods to invoke the function

    JavaScript contains two special methods to invoke the function differently. Here, we have explained each method in the table below.

    MethodFunction invocationArguments
    Call()Immediate invocationSeparate arguments
    Apply()Immediate invocationArray of arguments

    The difference between the call() and apply() method is how it takes the function arguments. We will learn each of the above methods with examples in the next chapters one by one.

  • Arrow Functions

    Arrow Functions

    The arrow functions in JavaScript allow us to create a shorter and anonymous function. Arrow functions are written without “function” keyword. The JavaScript arrow functions are introduced in ES6.

    Before ES6, we can define a JavaScript function with function declaration or function expression. The function expressions are used to define anonymous functions. The arrow functions allow us to write the function expressions with shorter syntax.

    Let’s look at the below syntax to write a function expression −

    constvarName=function(parameters){// function body};

    The above function expression can be written as an arrow function −

    constvarName=(parameters)=>{// function body};

    Here the “function” keyword is removed and after parenthesis we added “=>”.

    Syntax

    The syntax to use the arrow function in JavaScript is as follows.

    constvarName=(p1, p2, ... pN)=> Expression;ORconstvarName=(p1, p2, ...pN)=>{// function body};

    Here the parameters p1, p2, , pN are optional. We can use the variable name followed by pair of parentheses to invoke the arrow function.

    Arrow Function with Single Statement

    When the arrow function contains a single statement, we don’t need to write the ‘return’ keyword and braces (curly brackets).

    constadd=(x, y)=> x +y;

    Please note, we can always write an arrow function with return keyword and braces.

    constadd=(x, y)=>{return x + y};

    Example

    In the example below, the arrow function contains a single statement, so we don’t need to use the curly braces or return statement.

    <html><body><p id ="output"></p><script>constdivide=(x, y)=> x / y;
    
      document.getElementById("output").innerHTML =divide(10,5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    2
    

    Arrow Function with Multiple Statements

    When the function body contains multiple statements, we should always use the 'return' statement to return a value. Also we should use the curly brackets.

    Example

    In the example below, the arrow function contains multiple statements, so we need to use the braces or return statement.

    <html><body><p id ="output"></p><script>constdivide=(x, y)=>{let res = x / y;return res;};
    
      document.getElementById("output").innerHTML =divide(10,5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    2
    

    Note when we use block body using braces, we must use return statement.

    Arrow Functions Without Parameters

    The parameters p1, p2, , pN, in the above syntaxes are options. We can write an arrow function without any parameters.

    constgreet=()=>"Hello World!";

    We can also write using block body using braces and return keyword −

    constgreet=()=>{return"Hello World!";};

    Example

    <html><body><p id ="output"></p><script>constgreet=()=>"Hello World!";
    
      document.getElementById("output").innerHTML =greet();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello World!
    

    Arrow Function with Parameters

    Example: Arrow function with a single parameter

    The below code demonstrates that when you need to pass a single parameter to the function, you don't need to write parameters in the pair of parenthesis.

    <html><body><p id ="output"></p><script>constdivide=x=>20/ x;let res =divide(2);
    
      document.getElementById("output").innerHTML ="The value returned from the arrow function is: "+ res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value returned from the arrow function is: 10
    

    Example: Arrow function with multiple parameters

    We pass the multiple parameters to the arrow function expression in the code below. When the body of the arrow function contains multiple statements, we need to write it inside the curly braces and use the return statement to return the value.

    <html><body><p id ="output"></p><script>constsum=(a, b, c, d)=>{let sum = a + b + c + d;return sum;};let res =sum(10,30,45,60);
    
      document.getElementById("output").innerHTML ="The sum of 10, 30, 45, and 60 is: "+ res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 10, 30, 45, and 60 is: 145
    

    Arrow Function as an Expression

    The arrow function can easily be used as an expression due to its shorter syntax.

    Example

    In the below code, we use the ternary operator, and based on the boolean value of the 'isMul' variable, we assign the arrow function expression to the 'func' variable.

    After that, we use the 'func' variable to call the arrow function stored in that.

    <html><body><p id="output"></p><script>let isMul =true;const func = isMul ?()=>{let res =5*5;
    
         document.getElementById("output").innerHTML +="The multiplication value is: "+ res +"&lt;br&gt;";}:()=&gt;{let res =5+5;
         document.getElementById("output").innerHTML +="The sum value is: "+ res +"&lt;br&gt;";};func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication value is: 25
    

    Arrow Function with Default Parameters

    Example

    The below code explains how programmers can pass the default parameters to the arrow function. It is similar as we pass default parameters to the standard function definition.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");let isMul =true;constmul=(a = 10, b = 15)=> a * b;
    
      output.innerHTML +="mul(5, 8) = "+mul(5,8)+"&lt;br&gt;";
      output.innerHTML +="mul(6) = "+mul(6)+"&lt;br&gt;";
      output.innerHTML +="mul() = "+mul()+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    mul(5, 8) = 40
    mul(6) = 90
    mul() = 150
    

    Benefits of Using Arrow Functions

    Here, we have explained the benefits of using the arrow functions.

    • Shorter syntax − The arrow function decreases the code size to define the function.
    • Implicit return − To return the resultant value of the expression from the arrow function containing only a single statement, developers don't need to use the return keyword.
    • Ease to use as expression − The arrow function can be easily used as an expression.

    Limitations of Using Arrow Function

    There are some limitations of arrow functions, which we have explained below.

    • No Arguments − The arrow function can't have an arguments object.
    • No prototype − The arrow function can't have a prototype property as it is stored in the variable as an expression.
    • No new keyword − The arrow function can't be used with the new keyword to create its object.
  •  Self Invoking Functions

    Self-Invoking Functions

    The self-invoking functions are JavaScript functions that execute immediately as they are defined. To define a self-invoking function, you can enclose an anonymous function within parentheses followed by another set of parentheses. These are also called self-executing anonymous functions.

    The anonymous function inside the first pair of parentheses is basically a function defined with function expression. So a self-invoking function is also called immediately invoked function expression (IIFE).

    Syntax

    The syntax to define the self-invoking functions in JavaScript is as follows −

    (function(){// function body})();

    The function definition is enclosed inside the pair of parentheses. The second pair of parentheses at the end executes the function.

    An alternative syntax is as follows −

    (function(){// function body}());

    The first syntax is more clear.

    Example

    In the example below, we print the message in the output using the self-executing function.

    <html><body><p id ="output"></p><script>(function(){
    
         document.getElementById("output").innerHTML ="Self-invoked function is executed!";}());&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Self-invoked function is executed!
    

    Self-Invoking Functions with Parameters

    You can create a self-invoking function with parameters and pass arguments to it. It is common practice to pass references to global objects such as window, etc.

    (function(paras){// function body})(args);

    The paras are the list of parameters in the definition of the anonymous function and the args are arguments passed.

    Example

    In the below example, we created an anonymous function with a parameter name. We have passed an argument to it.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");(function(name){
    
         output.innerHTML =Welcome to ${name};})("Tutorials Point !");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Welcome to Tutorials Point !
    

    Private Scope of Self-Invoking Functions

    Whatever code is defined inside the self-executing function remains in the private scope and doesn't pollute the global scope. So, developers can make code clear and remove the errors like naming conflicts, etc. Also, the code of the self-invoking function remains hidden and can't be accessible by other parts of the code.

    Example

    In the example below, we have defined the variable 'a' outside or inside the function. The variable defined outside is a global variable, and the variable defined inside the function is a private variable, limited to the self-executing function's scope.

    Also, we have printed the value of the variable from inside and outside of the function. Users can observe the variable's value in the output.

    In this way, we can avoid the naming conflicts.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");let a =10;(function(){
    
            output.innerHTML +="Entering to the function &lt;br/&gt;";var a =20;
            output.innerHTML +="The value of a is "+ a +"&lt;br&gt;";
            output.innerHTML +="Exiting to the function &lt;br/&gt;";}());
         output.innerHTML +="The value of the outside the function is "+ a;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Entering to the function
    The value of a is 20
    Exiting to the function
    The value of the outside the function is 10
    

    Example

    In some cases, it is required to access the variable of the self-executing function outside of the function. In this case, we can make that variable global using the 'window' object as shown below and access the variable in the global scope.

    <html><body><div id ="output"></div><script>(function(){var string ="JavaScript";
    
         window.string = string;})();
      document.getElementById("output").innerHTML ="The value of the string variable is: "+ string;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the string variable is: JavaScript
    

    Private scope of a self-invoking function can be accessed by using the call() or apply() methods.

    Benefits of Using the Self-Invoking Functions

    • Avoiding the global scope − Developers can avoid the global scope for variables and functions using the self-invoking function, helping to avoid naming conflict and making code more readable.
    • Initialization − The self-executing functions can be used for the initialization of variables.
    • Code privacy − Programmers can avoid accessing the code of the self-executing function by other parts of the code.
  • Function Hoisting

    Function Hoisting

    The function hoisting in JavaScript is a default behavior in which function declarations are moved at the top of their local scope before execution of the code. So, you can call the function in its scope before it is declared. It’s important to notice that only declaration is hoisted not the initialization. So the variables or functions should have been initialized before they are used.

    Similar to the function hoisting, the variable hoisting is also a default behavior in which the variable declarations are moved at the top of their local scope. We can use the function before it has been declared.

    Let’s consider the following JavaScript code.

    add(5,10);// 15functionadd(x, y){return x + y;}

    In the above JavaScript code, the function add is called before it’s declaration. This is possible because JavaScript interpreter hoists the function declaration to the top of the scope. So the above code is equivalent to

    functionadd(x, y){return x + y;}add(5,10);// 15

    The function hoisting only works with function declaration not with function expression. So, if the function is defined using the function expression,., it is not hoisted at the top.

    add(5,10);// ReferenceError: Cannot access 'add' before initializationconstadd=function(x, y){return x + y;}

    Let’s write some complete JavaScript examples of function hoisting.

    Example: Function Hoisting

    In the example below, we have defined the printMessage() function, printing the position from where it is called.

    Also, we call the printMessage() function before and after the function definition. It prints the output without any error as the function is hoisted at the top of its scope.

    <html><body><p id ="output"></p><script>printMessage("Top");functionprintMessage(pos){
    
         document.getElementById("output").innerHTML +="The function is called from the "+ pos +"&lt;br/&gt;";}printMessage("Bottom");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function is called from the Top
    The function is called from the Bottom
    

    Example

    In the example below, we have defined the function inside the 'if' block. So, the function is hoisted at the top of the 'if' block, and you can execute the function only inside the 'if' block before its initialization.

    You can't access the function outside the 'if' block.

    <html><body><p id ="output"></p><script>// test("Top"); // Out of scopeif(1){test("Top");// In the same scopefunctiontest(pos){
    
            document.getElementById("output").innerHTML +="The function is called from the "+ pos +"&lt;br/&gt;";}test("Bottom");// In the same scope}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function is called from the Top
    The function is called from the Bottom
    

    The hoisting is very important behavior in JavaScript. But it is always advisable to declare the function or variable at the beginning of the code. Since JavaScript always interprets the code in sequence of declaration, then initialization and then usage.

    JavaScript Variable Hoisting

    The hoisting behaviors of JavaScript move the variables declaration to the top of the variable's scope by default. In JavaScript, variables declared with the 'var' keyword are hoisted at the top of its scope, but variables declared with the 'let' and 'const' keyword is not hoisted at the top.

    For example,

    var x = y;var y;

    The above code is similar to the below code, as the variables declaration is hoisted at the top.

    var y;var x = y;

    Let's understand the variable hoisting by following examples.

    Example: Variable Hoisting

    In the example below, we have initialized the variable y, printed its value in the output, and declared it at the end. The below code prints a value without any error, as variable y is hoisted at the top in the global scope.

    <html><head><title> JavaScript - Variable Hoisting </title></head><body><p id ="output"></p><script>
    
      y =10;
      document.getElementById("output").innerHTML ="The value of the y is : "+ y;var y;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the y is : 10
    

    Example: Variable Hoisting with Function

    In the example below, we have defined the printNum() function. In the printNum() function, we have initialized the variable y, printed its value, and declared it afterward.

    The variable y is hoisted at the top of the function so you can access it before its declaration, but you can't access it outside the function.

    <html><head><title> JavaScript - Variable Hoisting withfunction</title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionprintNum(){
    
         y =20;
         output.innerHTML +="The value of the variable y is : "+ y;var y;// Function scope}printNum();// Variable Y can't be accessible here&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the variable y is : 20
    

    However, variable initialization is not hoisted at the top of the block.

    Example: variable initialization is not hoisted

    The example below demonstrates that the variable is hoisted at the top, but the variable initialization is not. Here, we print the variable x without initialization of it. So, it prints the 'undefined' in the output.

    <html><body><p id ="output"></p><script>var x;
    
      document.getElementById("output").innerHTML ="x is -&gt; "+ x;
      x =10;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x is -> undefined
    

    Example: Hoisting with let and const keywords

    The below example demonstrates that the variable declared with the 'let' and 'const' keywords are not hoisted at the top. So, you always need to define it before using it.

    We used the 'trycatch' block to handle the error. In the output, users can observe the error the below code gives when we access the variable declared with the 'let' keyword.

    <html><head><title> Hoisting withlet and const</title></head><body><p id ="output"></p><script>const output = document.getElementById("output");try{
    
         x =10;
         output.innerHTML +="The value of x is -&gt; "+ x;let x;}catch(error){
         output.innerHTML += error.message;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Cannot access 'x' before initialization
    

  • 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