JavaScript

How to Call a Function in JavaScript

Functions are chunks of blocks that come with reusable functionality and reduce the complexity of the code. If an action needs to be done several times then functions are used to reduce the repetition of code in the program. These functions can be user defined or built-in that perform a specific action.

Whenever we need the code within the function to execute we make a call and certain actions are performed. In JavaScript there are four ways through which you can call a function and perform the action. In this article we’ll discuss how to call a function in JavaScript and various ways to call it along with examples for better demonstration.

Calling a Function in JavaScript

In JavaScript whenever we call a function, regardless of the way it’s called, two arguments “this” and the arguments parameters are passed to it which are implicit. “this” represents the condition or the context which will allow the function to execute whereas the arguments parameter consists of all the arguments that are being passed to the function. Following are the four ways in which functions in JavaScript are called along with examples for your better understanding.

Calling a Function as “Function”

The most used and common way of calling any function in any programming language is calling it as a function itself. This can be done when you place some lines of code and execute those lines whenever a button is clicked then the function is called as a “function”.

In the below mentioned example on the click of button the function is called directly and action is performed:

  <p>Click the button to say Hello</p>


    <button onclick="GreetingFunc()">Say Hello!!</button>

    <p id="div"></p>


    <script>

      function GreetingFunc() {

        document.getElementById("div").innerHTML = "Hello there?"

      }

    </script>

Output:

Calling a Function as Method

Another way to call a function is as a method and in this the function is defined as property on an object which is done by wrapping the function inside an object.

In the example provided below the function “GreetingFunc()” is wrapped inside the object “hello” and we used the object dot syntax method to call the function whenever the button is clicked:

<p>Click the button for greetings</p>


    <button onclick="hello.GreetingFunc()">Here for greetings?</button>

    <p id="div"></p>


    <script>

        hello = {

        GreetingFunc : function() {

        document.getElementById("div").innerHTML = "Hello Everyone"

      }

    }

    </script>

Output:

Calling a Function as Constructor

Constructors are used for initializing a state and setting it in an object or constructing an object. Calling a function as a constructor is a specialized way through which we send some inputs and receive a different output for each input.

In the below example users enter their name in an input box and when they click the button the function “GreetingFunc()” is called and within that function the value of the input text box is obtained through the id assigned to the input text field. A new instance of the hello object is created by calling the function hello().

<input type="text" id="name"></input>


    <p>Click the button for greetings</p>


    <button onclick="GreetingFunc()">Here for greetings?</button>

    <p id="div"></p>


    <script>

        function hello(name) {

            this.name = name;

    }
       

        function GreetingFunc() {

            var name = document.getElementById('name').value;

            var greet = new hello(name);

            document.getElementById("div").innerHTML = "Hello "+ greet.name

    }
   

    </script>

The keyword “new” shows that the function is being called as a constructor and the value is being saved in the variable greet which is later being used to print out the name on screen.

Output:

Calling a Function through call() and apply()

While working with JavaScript functions you’ve to keep in mind that the functions can have their own properties and methods and call() and apply() being the two of such methods. Both these methods allow the user to set the content in which they want to execute the function through “this” value.

In the below example two people’s information is stored and is displayed when the value is passed inside the call() method. Here the fullName method is called to display the firstPerson name.

<p id="div"></p>


    <script>

    const personFunc = {

    fullName: function() {

    return this.firstName + " " + this.lastName;

  }

}

    const firstPerson = {

    firstName:"Max",

    lastName: "Andrew"

}

    const secondPerson = {

    firstName:"Sam",

    lastName: "Andrew"

}

    document.getElementById("div").innerHTML = personFunc.fullName.call(firstPerson);
 
    </script>

Output:

The apply() method is used similarly to call a function but it accepts an array whereas the call() method accepts a list of values.

const num = [2, 6, 11, 33, 4];

const max = Math.max.apply(null, num);

console.log(max);

const min = Math.min.apply(null, num);

console.log(min);

Output:

Conclusion

Functions consist of code that is being reused throughout with different inputs. In JavaScript, functions can have their own properties and methods and can be called in four different ways. In this article we discussed how to call a function in JavaScript and discussed the four ways along with example and code. All these four ways are useful for any developer and while working with functions you should be aware about “this” keyword reference and its working.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.