How To Call A Function In JavaScript

To call a function in JavaScript is a lot more adaptable than in other programming languages. This is because there are multiple options for you to follow.

Knowing this, you can use the function that suits your needs or fit easily into place. Scripts become so much easier when the language works with you!

Advertising links are marked with *. We receive a small commission on sales, nothing changes for you.

What Is A Function

Before we start, we should explain what a function actually is. A function, in programming language, is a piece of coding information that you can use multiple times.

How To Call A Function In JavaScript

Instead of writing or copying the same code over and over again, you can create it through a function.

Then when you need to use the code, simply type in the name of the function, and it will bring forth the coding you had created ahead of time.

You can turn pages worth of coding into a one-word function instead.

The Four Ways To Call A Function

Calling, or activating, a function in Javascript will create two arguments – the arguments parameter and the task the function is meant to perform.

A parameter is a variable found in the function. For example, the function might complete different tasks based on the word used to activate it.

If you say “hello” the parameter suggests replying in English. If you say “ola” the parameter suggests talking in Portuguese. 

It is important to keep this concept in mind, as the variable element could affect your choice of method. 

In Javascript, the first option you have is to call your function through a function. Seems simple enough.

The rest are a little more out of the box. Next, you can call it through a method.

Thirdly, try calling the function with reference to a constructor. And lastly, you can opt to call and then apply the function instead.

We will explain each option, so you can figure out which one works best for your project.

The Most Common Method – Calling Through A Function 

This method is so simple that some people might have forgotten they are actually commanding a function call. 

To call a function through a function, you need to place a bit of JavaScript code onto a script and click on a button to call it.

In this process, you would have been calling the “JavaScript function” through a function.

If that doesn’t make sense to you, don’t worry. We will explain it again through an example of code.

<button onclick=”sayOla()”>say ola</button>

  <script>

    function sayOla() {

      console.log(this);

      console.log(arguments);

      console.log(‘ola’);

    }

  </script>

From this snippet, you’ll notice that there is a button. Once the button is clicked a function will be called forward, this function is named “sayOla”. The output then becomes “ola”.

Calling Through A Method 

To understand how the method option works, you need to know what an object is. Objects are an abstract type of data, which normally contains data sets.

For example, a website might have an object named “useraccount”. This object could contain information such as the user’s name, address, password, age, photos, and so on.

A method is when the program works through methods.

To use the method approach can use the data of the object to create more parameters.

As an example, see this sample:

<button onclick=”greeter.sayOla()”>say ola</button>

  <script>

    greeter = {

      sayOla: function () {

        console.log(this);

        console.log(arguments);

        console.log(‘ola’);

      }

    }

The additional “greeter” is the object we are calling, and it also becomes the parameter.

Calling As A Constructor

A constructor is similar to a method in the sense that they both use objects as the main part of their ability. However, a constructor can also create (or construct) an object.

To use one in a function means you are creating an object through the function, preparing the parameters and arguments as you go.

If you need the function to create a new object, this is the method for you.

You can do this, by starting like:

function Greeter(name) {

console.info(‘begin constructor’);

Then add in your function requirements and end with 

console.info(‘end constructor’)

The capitalized G indicates that the function was called as a constructor.

Calling Through Apply And Call

JavaScript has another unique ability. It can allow its functions to have its own methods.

This is called the “call and apply” method, and it means that you can call upon a function, and using the parameters, it can apply and call upon its own functions as needed.

The coding can become complex, but we will explain it as best as we can.

First, you start off by defining the variables. Then you use an empty array to create objects, as we described before.

And the next stage you create a constructor to create its own function, but all it will do at this moment is name the function based on the information it already has.

Once a name has been generated, we can perform the function.

If you want to “call” you need the list of values to be accepted completely. If you want to “apply”, you need an array to be accepted instead.

For example:

<button onclick=”go()”>GO</button>

  <script>

    var people = [];

    var name = ‘alex’;

    function Person(idx) {

      idx % 2 === 0 ? 

        this.name = ‘alex ‘ + idx : 

        this.name = ‘bob ‘ + idx;

    }

    function printName() {

      console.log(this.name);

    }

    function go() {

      //call printName to print the name variable defined on the window object

      printName();

      //populate the people array with a couple of people

      for (let idx = 0; idx < 5; idx++) {

        people.push(new Person(idx));

      }

      // lets call the printName for each object that we just created 

      // setting this dynamically

      people.forEach(p => {

        printName.call(p);

      });

      // printName.call(valueOfThis, 1, 2, 3);

      // printName.apply(valueOfThis, [1, 2, 3])

    }

  </script>

Summary

If you are just starting off, you should begin by calling a function through a function.

Once you get the hang of that method, you can try the more complex scripts which will give you more flexibility in the long run.

The best way to learn is by playing around with the scripts and figuring out how to create the outcomes you’re after.

Advertising links are marked with *. We receive a small commission on sales, nothing changes for you.