How to Call a Function in JavaScript?

Functions play a very crucial role in any programming language. They help us divide bigger problems into smaller pieces by grouping similar code together which is more manageable and can be called anywhere throughout the program whenever needed.

In this article, I’ll show you how to create such reusable functions and call them in your program using JavaScript. So, let’s get started.

What is a Function in JavaScript?

A function in JavaScript is a piece of code that performs a particular task. The task that the function performs can be anything like: adding two numbers, calculating the distance between two points in a 2-D plane, displaying a person’s information, etc.

In JavaScript, you can use the following syntax to create a function:

function functionName(){
  // function body
}

However, this is not the only way to create a function in JavaScript. There are other ways too. But this is the most commonly used syntax.

The simplest function which we can think of can be something which prints “Hello World!” to the console.

Which can be created something like this:

function sayHello(){
    console.log("Hello World!");
}

In the above example, we have created a function named sayHello, which should print “Hello World!” to the console.

But if you copy this function to your JS file and try to run it, it will not do anything. Why this is so?

Actually, if you want a function to be executed, you have to call it somewhere. That’s what we are going to discuss in the next few sections.


How to Call a Function in JavaScript?

If you define a function in your JavaScript program but do not call it, it will not do anything.

A function in JavaScript and also in most of the programming languages is executed only when it is called somewhere in your program.

But how do we call a function?

In JavaScript, you can use the function name followed by the parentheses to call a function. For example, myFun(), add(), etc.

See the following example:

// Function definition
function sayHello(){
    console.log("Hello World!");
}

// Call the function
sayHello();

Output:

Hello World!

There is no restriction on where you are calling the function. However, it should be present in the file where you are calling it, if not then it must be imported from another file.

Similarly, you can call a function any number of times. It’s totally up to you, how you want to use it.

// Function definition
function sayHello(){
    console.log("Hello World!");
}

// Call the function 2 times
sayHello();
sayHello();

Output:

Hello World!
Hello World!

Calling a Function with Parameters

Function parameters also known as function arguments are the variables that we pass to the function when we call it.

These parameters allow you to pass additional information to the function. The function can perform some calculations based on these parameters and return or print the result. This makes a function more reusable and flexible.

You can simply pass these parameters to the function during the function call. When you call a function, you should provide values for its parameters in the same order in which the parameters are declared in the function definition. This is known as positional or ordered parameter passing.

In the following example, we have created a function add which takes two parameters num1 and num2, calculates their sum and prints the result to the console.

// Function definition
function add(num1, num2){
    
    // Calculate the sum
    const sum = num1 + num2;
    
    // Print the result
    console.log("The sum of two numbers is: " + sum);
}

// Pass 10 & 20 as argument and call the function
add(10, 20);

Output:

The sum of two numbers is: 30

You can pass any number of arguments to a function as per your need. However, it is recommended not to pass more than 7 parameters to a function.

Like other programming languages(C/C++), you don’t have to explicitly specify whether the parameters should be passed by value or by reference. JavaScript itself takes care of this for you.

When you pass a primitive value to a function such as a number, string, boolean, etc., it is passed by value i.e. a copy of the value is passed to the function as argument.

On the other hand, when you pass a non-primitive value like an object or array, it is passed by reference i.e. the memory address of the value is passed to the function. Therefore, If you modify the object inside the function, the changes will also be visible outside the function.

Consider the following example, where we are modifying the array inside the function, but its changes are also reflected on the array outside the function.

// Function definition
function doubler(arrNew){
    
    // Double each item of the array
    for(let i = 0; i < arrNew.length; i++){
        
        arrNew[i] = arrNew[i]*2;
        
    }
}

// Original array
const arr = [1, 2, 3, 4, 5];

// Pass arr as argument and call the function
doubler(arr);

// Print the array items after function call
for(let i = 0; i < arr.length; i++){
    console.log(arr[i]);
}

Output:

2
4
6
8
10

As you can see from the above output, we doubled each item of the array inside the function, but the same changes are reflected on the array outside the function. This proves that the non-primitive values like objects and arrays are passed by reference in JavaScript.


Calling a Function with Parameters and Returning a Value from it

When you call a function, it generally performs some calculation on the parameters you passed to it. You can then print the result of the calculation inside the function.

But what if you don’t want to print the result inside the function, instead you want to get it back from the function and do the further calculation. Well, we can achieve this by returning the value from the function.

In JavaScript, you can return a value from a function using the return statement followed by the value you want to return. The value can be of any data type such as number, string, boolean, object, array, or even another function.

Here’s the basic syntax:

function functionName(parameters) {
  // Function logic
  // ...

  // Return the result
  return result; 
}

Consider the following example, which adds two numbers and returns the result. You can then use this result to do some further calculations if you want.

// Function definition
function add(num1, num2){
    
    // Calculate the sum
    const sum = num1 + num2;
    
    // Return the sum
    return sum;
}

const a = 10, b = 20;

// Call the function
const result = add(a, b);

// Print the result
console.log('The sum of '+ a + ' and '+ b + ' is: ' + result);

Output:

The sum of 10 and 20 is: 30

In the above example, we passed two parameters a, b to the add() function when we are calling it.

The add() function calculates the sum of both numbers, stores the result in the sum variable and returns it back when the function call finishes. The value returned by the add() function is stored in the result variable.

Let’s take one more example, where we pass an array as a parameter to a function. The function filters all even numbers from the array and returns a new array as a result.

// Function to filter even numbers
function even(arr){
    
    // Create an empty array
    const evenItems = [];
    
    // Filter even numbers
    for(let i = 0; i < arr.length; i++){
        if(arr[i] % 2 == 0){
            evenItems.push(arr[i]);
        }
    }
    
    // Return the new array
    return evenItems;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Call the function
const evenArr = even(arr);

// Print te result
console.log(evenArr);

Output:

[2, 4, 6, 8, 10]

Can We Call a Function Before its Declaration?

In programming languages like C/C++, a function must be declared before it is called. If you call a function before its declaration, you will get a compilation error.

But in JavaScript, functions can be called before their declaration without any compilation error. This behavior is known as "hoisting" in JavaScript and it is implicitly done by the JavaScript engine.

In hoisting, all variables and function declarations are moved to the top of their containing scope during the compilation phase. It means that you can use functions and variables before they are declared in your code.

See the following example:

// Call the function before its declaration
sayHi();

// Function declaration
function sayHi(){
    console.log('Hii there!');
}    

Output:

Hii there!

As you can see in the above example, the function sayHi() is called before its declaration still the program runs without any errors. This works because of hoisting.

That’s all for this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment