Category: Functions

  • Smart Function Parameters

    The concept of smart function parameters in JavaScript is a way to make a function adaptable to different use cases. It allows the function to handle the different kinds of arguments passed to it while invoking it.

    In JavaScript, the function is an important concept for reusing the code. In many situations, we need to ensure the function is flexible to handle different use cases.

    Here are different ways to define a function with smart parameters.

    Default Function Parameters

    In JavaScript, the use of default function parameters is a way to handle the undefined argument values or arguments that haven’t passed to the function during invocation of the function.

    In the below code snippet, we set default values of the parameters, a and b to 100 and 50.

    functiondivision(a = 100, b = 50){// Function body}

    Example

    In the below code, the division() function returns the division of the parameters a and b. The default value of parameter a is 100, and parameter b is 50 whenever you want to pass any argument or pass an undefined argument, parameters with initialized with their default value which you can observe from the values printed in the output.

    <html><head><title> JavaScript - Default parameters </title></head><body><p id ="output"></p><script>functiondivision(a = 100, b = 50){return a / b;}
    
      document.getElementById("output").innerHTML =division(10,2)+"&lt;br&gt;"+division(10,undefined)+"&lt;br&gt;"+division();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    5
    0.2
    2
    

    JavaScript Rest Parameter

    When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters. The JavaScript rest parameters allow us to collect all the reaming (rest) arguments in a single array. The rest parameter is represented with three dots (...) followed by a parameter. Here this parameter works as the array inside the function.

    Syntax

    Follow the below syntax to use the rest parameters in the function declaration.

    functionfuncName(p1, p2, ...args){// Function Body;}

    In the above syntax, 'args' is rest parameter, and all remaining arguments will be stored in the array named args.

    Example

    In the example below, the sum() function returns the sum of all values passed as an argument. We can pass an unknown number of arguments to the sum() function. The function definition will collect all arguments in the 'nums' array. After that, we can traverse the 'nums' array in the function body and calculate the sum of all argument values.

    The sum() function will also handle the 0 arguments also.

    <html><head><title> JavaScript - Rest parameters </title></head><body><p id ="demo"></p><script>functionsum(...nums){let totalSum =0;for(let p =0; p < nums.length; p++){
    
            totalSum += nums[p];}return totalSum;}
      document.getElementById("demo").innerHTML =sum(1,5,8,20,23,45)+"&lt;br&gt;"+sum(10,20,30)+"&lt;br&gt;"+sum()+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    102
    60
    0
    

    Note You should always use the rest parameter as a last parameter.

    JavaScript Destructuring or Named parameters

    You can pass the single object as a function argument and destructuring the object in the function definition to get only the required values from the object. It is also called the named parameters, as we get parameters based on the named properties of the object.

    Syntax

    Follow the below syntax to use the destructuring parameters with the function.

    functionfuncName({ prop1, prop2, ... }){}

    In the above syntax, prop1 and prop2 are properties of the object passed as an argument of the function funcName.

    Example

    In the example below, we have defined the 'watch' object containing three properties and passed it to the printWatch() function.

    The printWatch() function destructuring the object passed as an argument and takes the 'brand' and 'price' properties as a parameter. In this way, you can ignore the arguments in the function parameter which are not necessary.

    <html><head><title> JavaScript - Parameter Destructuring </title></head><body><p id ="output"></p><script>functionprintWatch({ brand, price }){return"The price of the "+ brand +"\'s watch is "+ price;}const watch ={
    
         brand:"Titan",
         price:10000,
         currency:"INR",}
      document.getElementById("output").innerHTML =printWatch(watch);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the Titan's watch is 10000
    

    The above three concepts give us flexibility to pass the function arguments.

  • Global Variables

    JavaScript Global Variables

    The global variables in JavaScript are the variables that are defined outside of the function or any particular block. They are accessible from anywhere in JavaScript code. All scripts and functions can access the global variables.

    You can define the global variables using the varlet, or const keyword. The variables defined without using any of the var, let or const keywords automatically becomes global variables.

    JavaScript Global Scope

    The global variables have global scope. So a variable declared outside of a function or block has global scope. The global scope is visible or accessible in all other scope. In client side JavaScript the global scope is the web page in which all the code is being executed. A global variable declared with var keyword belongs to window object.

    var x =10;// Global Scopelet y =20;// Global Scope	const z =30;// Global Scope

    Here the variables, x, y and z are declared outside of any function and block, so they have global scope and are called global variable.

    Global Variable Examples

    Let’s learn more about global variables using the example below.

    Example

    We have defined the x, y, and z global variables in the code below. You can observe that variables can be accessed anywhere inside the code.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="output"></p><script>var x =10;let y =20;const z =30;
    
      document.getElementById("output").innerHTML ="x = "+ x +"&lt;br&gt;"+"y = "+ y +"&lt;br&gt;"+"z = "+ z;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x = 10
    y = 20
    z = 30
    

    Example

    In the example below, we have defined the variables a and b using the var and let keywords. You can see that a and b variables can be accessible inside the function or outside the function as they are global variables.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");var a =10;let b =20;functiontest(){
    
         output.innerHTML +="a -&gt; Inside the function = "+ a +"&lt;br&gt;";
         output.innerHTML +="b -&gt; Inside the function = "+ b +"&lt;br&gt;";}test();
      output.innerHTML +="a -&gt; Outside the function = "+ a +"&lt;br&gt;";
      output.innerHTML +="b -&gt; Outside the function = "+ b +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a -> Inside the function = 10
    b -> Inside the function = 20
    a -> Outside the function = 10
    b -> Outside the function = 20
    

    Automatic Global Variables

    When you define the variables anywhere inside the code without using the varlet, or const keywords, the variable automatically becomes the global variable and can be accessible anywhere inside the code.

    Example

    In the below code, we have defined the variable 'a' without using any keyword inside the function. Even if we have defined the variable in the function, it becomes global as we haven't used any keyword to define the function.

    The output shows that variable 'a' can be accessible inside or outside the function.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functiontest(){
    
      a =90;
            output.innerHTML +="a -&gt; Inside the function = "+ a +"&lt;br&gt;";}test();
        output.innerHTML +="a -&gt; Outside the function = "+ a +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a -> Inside the function = 90
    a -> Outside the function = 90
    

    Defining the global variables inside the function or particular block is not a good practice, as naming conflict can occur in the code.

  • Variable Scope

    JavaScript Variable Scope

    The variable scope in JavaScript determines to the accessibility and visibility of the variable in different part of the code. The scope is the current context of the code execution. This means the variable scope is determined by where it is executed not by where it is declared.

    In JavaScript, the objects and functions are also variables. So the JavaScript variable scope also determines the accessibility or visibility of objects and functions also in the program.

    It is essential to learn the variable scope in JavaScript to write clear code and avoid naming conflicts.

    There are following types of variable scope in JavaScript.

    • Block scope
    • Function scope
    • Local scope
    • Global scope

    Here, we will cover the block, function, and local scope. We will discuss Global scope in detain in JavaScript Global variable chapter.

    JavaScript Block Scope

    Before JavaScript ES6, there were only Global and Function scopes. ES6 introduced the let and const keywords. These keywords provide the Block Scope in JavaScript.

    The JavaScript variables defined using the ‘let‘ and ‘const‘ keyword inside a { } block can be accessible only inside the block in which they are defined.

    {let x =10;// x is accessible here}//x is not accessible here

    A variable defined with var keyword is does not provide block scope.

    {var x =10;// x is accessible here}//x is accessible here also

    Example

    In the example below, we defined the variable ‘a’ inside the ‘if’ block. In the output, you can see that variable ‘a’ is accessible only inside the ‘if’ block. If you try to access the variable ‘a’ outside the ‘if’ block, it will throw a reference error like ‘variable a is not defined’.

    <html><head><title> JavaScript - Block scope </title></head><body><p id ="output"></p><script>if(true){let a =10;
    
         document.getElementById("output").innerHTML ="a = "+ a;}// a can't be accessed here&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 10
    

    Example

    In the below code, we have defined the test() function. In the function, we have added a { } block using the curly braces, and inside the { } block, we have defined the variable 'x'. The variable 'x' can't be accessible outside the { } block as it has a block scope.

    <html><head><title> JavaScript - Block scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functiontest(){{let x =30;
    
            output.innerHTML ="x = "+ x;}// variable x is not accessible here}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x = 30
    

    Whenever you define the variable using the 'let' or 'const' keyword inside the block, like loop block, if-else block, etc., it can't be accessible outside the block.

    JavaScript Function Scope

    In JavaScript, each function creates a scope. The variables defined inside a function have function scope. The variable defined in a function are accessible from within the same function only. These variable are not accessible from the outside of the function.

    Whenever you define the variable inside the function using the 'var' keyword, the variable can be accessible throughout the function, even if it is defined inside the particular block.

    For example,

    functionfunc(){{var x;// function scopelet y;// Block scopeconst z =20;// Block scope}// x is accessible here, but not y & z}

    Example

    In the example below, we have defined the variable 'x', 'y', and 'z' using the var, let, and const keywords, respectively. The variable 'x' can be accessible inside the function anywhere as it has a function scope, but 'y' and 'z' can only be accessible inside the block in which it is defined.

    <html><head><title> JavaScript - Function scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionfunc(){{var x =30;let y =20;const z =10;
    
            output.innerHTML +="x -&gt; Inside the block = "+ x +"&lt;br&gt;";
            output.innerHTML +="y -&gt; Inside the block = "+ y +"&lt;br&gt;";
            output.innerHTML +="z -&gt; Inside the block = "+ z +"&lt;br&gt;";}
         output.innerHTML +="x -&gt; Outside the block = "+ x +"&lt;br&gt;";// y and z can't be accessible here}func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x -> Inside the block = 30
    y -> Inside the block = 20
    z -> Inside the block = 10
    x -> Outside the block = 30
    

    JavaScript Local Scope

    The JavaScript local scope is a combination of the function and block scope. The JavaScript compiler creates a local variable when the function is invoked and deletes it when the function invocation completes.

    In short, variables defined inside the function or block are local to that particular scope. The function parameters are treated as local variables inside the function.

    Example

    In the below code, we have defined the variables inside the function using the var, let, and const keywords. All variables are local to the function. It can't be accessible outside the function.

    Similarly, we can define the looping variables in the local scope.

    <html><head><title> JavaScript - Local scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionfunc(){let first =34;var second =45;const third =60;
    
    
         output.innerHTML +="First -&gt; "+ first +"&lt;br&gt;";
         output.innerHTML +="Second -&gt; "+ second +"&lt;br&gt;";
         output.innerHTML +="Third -&gt; "+ third +"&lt;br&gt;";}func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    First -> 34
    Second -> 45
    Third -> 60
    

    We notice that the when a variable is defined inside a function, the variable become Local to the function. In this situation, the variable has function scope. When a variable is defined inside a particular block, it becomes local to that block and has block scope.

  • Closures

    What is Closure?

    The concept of closures in JavaScript allows nested functions to access variables defined in the scope of the parent function, even if the execution of the parent function is finished. In short, you can make global variables local or private using the closures.

    A JavaScript closure is basically a combination of the function and its lexical environment. This allows an inner function to access the outer function scope. A closure is created every time a function is created at the function creation time.

    Before you start learning the concept of closures, you need to know the concept of lexical scoping, nested functions, and returning functions.

    Lexical Scoping

    In JavaScript, the lexical scoping is a concept in which the scope of the variables is determined at the code compilation time based on the structure of the code. For example, the nested function can access the variables from the parent function’s scope is called lexical scoping.

    Nested Function

    You can define the function inside the function, and the inner function is called the nested function. Let’s learn it via the example below.

    Example

    In the example below, we have defined the inner() function inside the outer() function. Also, the inner() function is executed inside the outer() function.

    When we execute the outer() function, it also executes the inner() function, a nested function.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionouter(){
    
         output.innerHTML +="The outer function is executed! &lt;br&gt;";functioninner(){
            output.innerHTML +="The inner function is executed! &lt;br&gt;";}inner();}outer();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The outer function is executed!
    The inner function is executed!
    

    Returning Function

    When any function returns the function instead of a value or variable, it is called the returning function. Let's look at the example below.

    Example

    In the below code, the outer() function returns the function definition, and we store it in the 'func' variable. After that, we use the 'func' variable to invoke a function stored in that.

    <html><head><title> JavaScript - Returning function</title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionouter(){
    
         output.innerHTML +="The outer function is executed! &lt;br&gt;";returnfunctioninner(){
            output.innerHTML +="The inner function is executed! &lt;br&gt;";}}const func =outer();func();func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The outer function is executed!
    The inner function is executed!
    The inner function is executed!
    

    Now, you learned the prerequisite required to learn the closures.

    The definition of JavaScript closure is a bit confusing, but we will learn the closure concept step by step so it will be clear to you.

    A Counter Dilemma

    For example, you create the counter to increment and decrement the variable. As shown below, you need to use the global variable for the counter.

    Example

    In the example below, the 'cnt', a global variable is initialized with 100. Whenever the decrement() function is executed, it decreases the value of the 'cnt' variable by 1.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");var cnt =100;functiondecrement(){
    
         cnt = cnt -1;
         output.innerHTML +="The value of the cnt is: "+ cnt +"&lt;br&gt;";}decrement();decrement();decrement();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the cnt is: 99
    The value of the cnt is: 98
    The value of the cnt is: 97
    

    The above code perfectly works as a decrement counter, but the problem is 'cnt' variable can be accessed in the code anywhere, and any part of the code can change it without executing the decrement() function.

    Here, JavaScript closure comes into the picture.

    Example: JavaScript Closures

    The counter() function returns the decrement() function in the example below. The 'cnt' variable is defined inside the counter() function rather than in the global scope.

    The decrement() function decreases the value of the 'cnt' by 1 and prints in the output.

    The 'func' variable contains the decrement() function expression. Whenever you execute the func(), it calls the decrement() function.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");functioncounter(){let cnt =100;// Works as a global variable for the decrement function.returnfunctiondecrement(){
    
            cnt = cnt -1;
            output.innerHTML +="The value of the cnt is: "+ cnt +"&lt;br&gt;";}}const func =counter();// Returns the decrement() function expressionfunc();func();func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the cnt is: 99
    The value of the cnt is: 98
    The value of the cnt is: 97
    

    Now, let's remember the definition of closure again. It says that the nested function can access the variables from the outer function's scope even if the execution of the outer function is finished.

    Here, the execution of the counter() function is finished. Still, you can call the decrement() function and access the 'cnt' variable with an updated value.

    Let's look at another example of closure.

    Example

    In the example below, the name() function returns the getFullName() function. The getFullName() function merges the string with the 'name' variable, defined in the outer function's scope.

    <html><head><title> JavaScript - Closure </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionname(){let name ="John";returnfunctiongetFullName(){return name +" Doe";}}const fullName =name();
    
      output.innerHTML +="The full name is "+fullName();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The full name is John Doe
    

    Benefits of Closure

    Followings are some benefits of the closures in JavaScript −

    • Encapsulation − The closure allows developers to hide or encapsulate the data. It makes data private and inaccessible from the global scope. So, you can expose only the required variables and functions and hide other internal details of the code.
    • Preserving State − The function remembers its lexical scope even if the execution of the outer function is completed. So, developers can maintain the state as we were maintaining the state of the counter in the above examples.
    • Improved memory efficiency − The closure allows you to manage memory efficiently, as you can only retain access to the necessary variables and don't need to define the variables globally.
  • Function bind

    Function bind() Method

    The function bind() method in JavaScript creates a new function with a specified this value and optional arguments, without invoking the original function immediately. It is commonly used to set the context (this) for a function and partially apply arguments. This method is used to bind a particular object to a common function.

    To understand the function bind() method, we should first understand the “this” keyword. In JavaScript (and other programming languages also), this is a special keyword that is used within functions to refer to the object on which the function is invoked. The value of this is depended on how a function is being called and behaviour of this can vary in different contexts.

    Syntax

    The syntax of JavaScript function bind() method is as follows −

    functionToBind.bind(thisValue, arg1, arg2,...);

    Here functionToBind is the original function whose this value and arguments you want to set.

    Parameters

    • thisValue − The value that should be passed as the this parameter when the new function is called.
    • arg1, arg2, … − Optional arguments that will be fixed (partially applied) when the new function is called. These arguments will be prepended to the arguments provided to the new function.

    Lets now understand the Function bind() method with the help of some program examples.

    Without Function bind() Method

    Here we will create a general and common function greet() which simply prints to the console. We create a constant object named person and give it some property i.e. name and we then invoke the function greet by passing it a message “Hello”.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");functiongreet(message){
    
         output.innerHTML = message +', '+this.name;}const person ={ name:'John Doe'};greet('Hello');&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello, 
    

    In this example, when the greet function is called directly without using bind, the this value is not explicitly set, leading to an undefined or global object (window in a browser environment) being used as this.

    With Function bind() method

    To overcome the issue in the previous code where it could not fetch any associated name, we make use of the bind function to bind the object person to the function greet.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");// Original functionfunctiongreet(message){
    
         output.innerHTML = message +', '+this.name;}// Object with a 'name' propertyconst person ={ name:'John Doe'};const greetPerson =greet.bind(person,'Hello');greetPerson();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello, John Doe
    

    The bind method was able to create a new function greetPerson wherein the this value has been explicitly set to the person object and argument "Hello" is partially applied as in the previous code as well.

    Using bind() ensures that the function is executed in the desired context, preventing issues related to the default behaviour of this in JavaScript functions.

    Example: Binding different objects to same function

    We have created three objects with x and y coordinates of a point, a function printVal is created to print to the console the coordinates of the point. The bind method binds the points to the printVal function and prints the x, y coordinates of each of the points.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const points1 ={X:100,Y:100}const points2 ={X:200,Y:100}const points3 ={X:350,Y:400}functionprintVal(){ 
    
         output.innerHTML +="Coordinates: "+this.X+","+this.Y+"&lt;br&gt;";}const printFunc2 =printVal.bind(points1);printFunc2();const printFunc3 =printVal.bind(points2);printFunc3();const printFunc4 =printVal.bind(points3);printFunc4();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Coordinates: 100,100
    Coordinates: 200,100
    Coordinates: 350,400
    

    Example: Setting the default values of function parameters

    This is a new scenario wherein we make use of the bind function to predefine the parameter. The multiply() function simply takes 2 inputs and returns their product. By using the bind() method we can set any of the parameters to a default value as needed.

    In the below example, it sets the variable y to 2 and hence upon calling the function by passing just 1 parameter i.e. x as 5 it gets multiplies by the preset 2 and returns the output of 5x2=10.

    <html><body><div id ="output"></div><script>// Original function with parametersfunctionmultiply(x, y){return x * y;}// Using bind to preset the first parameterconst multiplyByTwo =multiply.bind(null,2);// Calling the bound function with only the second parameter
    
      document.getElementById("output").innerHTML=multiplyByTwo(5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    10
    

    It is important to note that the bind method creates and returns a new function and does not modify the original function. The same function can be reused and yet made to match different use cases without actually modifying.

  • Function apply

    Function apply() Method

    The Function apply() method in JavaScript allows us to invoke a function given a specific value for this and arguments provided as an array.

    The Function call() and apply() methods are very similar, but the main difference between them is function apply() method takes a single array containing all function arguments, and the function call() method takes individual arguments.

    Same as the Function call() method, we can use the apply() method to manipulate the this value and can assign an orbitrary object to this.

    Syntax

    The syntax of the Function apply() method in JavaScriot is as follows −

    func.apply(thisArg,[arg1, arg2,... argN]);

    Parameters

    • thisArg − The ‘thisArg’ grument represents the function context. It is an object whose properties are needed to access the reference function using the ‘this’ keyword.
    • [arg1, arg2, … argN] − They are arguments to pass to the function.

    Return value

    It returns the resultant value returned from the function.

    Examples

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

    Using apply() method without passing argument

    In the below code, we have defined the test() function printing the message in the output.

    We invoked the function in a standard way and used the apply() method without passing any argument to invoke the function. The output shows that the apply() method gives the same output as a normal function call.

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

    Output

    The function test is invoked!
    The function test is invoked!
    

    Using apply() method with this argument only

    In the below code, the 'car' object contains three different properties. We passed the car object as a 'thisArg' argument of the apply() method.

    In the showCar() function, we access the properties of the car object using the 'this' keyword and print it into the output.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output"></p><script>functionshowCar(){return"The price of the "+this.name +" "+this.model +" is: "+this.price;}let car ={
    
      name:"OD",
      model:"Q6",
      price:10000000,}
    document.getElementById("output").innerHTML =showCar.apply(car);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the OD Q6 is: 10000000
    

    Using apply() method with an array of function arguments

    In the example below, we pass the nums object as the first argument of the apply() method. After that, we pass the array of arguments as an apply() method's argument.

    In the printSum() function, we access the object properties using the 'this' keyword and function arguments using the function parameters.

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

    Output

    Total sum is 87
    

    Using apply() method with built-in functions

    You can also use the apply() method with built-in object methods. We can invoke the built-in object methods (such as Math.max or Math.min) using apply() method.

    In the example below, we use apply() method with built-in JavaScript functions - Math.max and Math.min. We can't directly use these methods for the arrays. We invoke the Math.max and Math.min methods using apply() method. We pass null as thisArg and the array of five integers as the function argument.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output-max"> Max element in the array:</p><p id ="output-min"> Max element in the array:</p><script>const numbers =[7,6,4,3,9];
    
      document.getElementById("output-max").innerHTML += Math.max.apply(null, numbers);
    
      document.getElementById("output-min").innerHTML += Math.min.apply(null, numbers);</script></body></html>

    Output

    Max element in the array: 9
    Max element in the array:3
    

    Notice if you use Math.max() or Math.min() methods directly for arrays to find max or min element in the array, the result will be NaN.

  • 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.