How to Call Function in JavaScript using Arguments

In the previous tutorial, we learned how to call a function in JavaScript without using parameters.

In all programs, we have created functions without parameters in the script. We have declared no parameters in the parameter list and it is empty.

Now, we will learn how to call a function in JavaScript with passing argument values. We declare functions with any number of parameters, but commas must separate them.

Once the JavaScript function with parameters is declared, we need to pass argument values into a function to change the function’s behavior when it gets called.

In other words, when we call a function, we can pass along some values to it. These values are parameters or arguments. Let’s understand in more detail.

How to call function in JavaScript by passing arguments

Formal Parameters in JavaScript


Function parameters in JavaScript are the local variables declared inside the function definition. They are also called formal parameters.

Each function definition contains a parameter list enclosed in parentheses. Function parameters receive the real values passed when the function gets called.

The general syntax to declare a function along with a parameter list is as:

function functionName(parameter1, parameter2, parameter3...) {
// code to be executed
}

Key points of Formal Parameters in JavaScript:

1. Parameters in the list are optional. So, the parameter list may be empty or it may contain any combination of data types, such as integer, float, character, etc.

2. Since JavaScript is loosely typed, so we do not need to specify data type of parameters, as in C++, Java, and other strictly typed programming languages.

3. Since parameters are local variables for the function, so they exist only inside the function where they defined.

4. JavaScript functions do not perform type checking on the passed argument values.

5. They do not check the number of arguments received.

Consider the following examples.

// Formal parameters in function definition.
<script>
  function welcome(myName) // Here, myName is a formal parameter. 
  {
    document.write("Welcome " +myName+ " to Scientech Easy!");
  }
</script>

Let us consider another example to understand more clearly.

<script>
function maxTwo(x, y)
{
  if(x > y)
     return x;
  else
     return y;
}
</script>

In the above function, x and y are formal parameters.

Arguments in JavaScript


Arguments in JavaScript are the actual values or data passed to variables (i.e. parameters) defined in the function definition. Sometimes, argument are also called actual parameters.


A function uses argument values when it gets called. Argument values always go between the function parentheses, and replace those parameters defined during function definition. Then, the body of method executes with these values.

Consider the following examples.

var x = sum(40, 50);
var y = sub(12, 10);

The values 40 and 50 are the arguments with which we will call a function by passing these values.


Note: Argument values passed to the function must list in the same order as the parameters in the function definition.

How to call Function in JavaScript by passing Arguments/Parameters


1. Let’s create a simple JavaScript program in which we will call a function by passing argument values.

Program code 1:

<script>
// Function declaration with two parameters.
  function sum(x, y) // formal parameters
  {
    let s = x + y;
    document.write("Sum of two numbers: " +s);
   }
  sum(20, 30); // Calling function with passing arguments.
</script>
Output:
     Sum of two numbers: 50

In this example, we have defined a function named sum() with two parameters in the head section of HTML document. When we will call this function by passing argument values, the code inside the function will execute with these values.


2. Let’s create a JavaScript program to calculate an average of three numbers. We will call a function by passing actual parameters.

Program code 2:

<script>
  function avg(x, y, z) // formal parameters
  {
    let s = (x + y + z) / 3;
    document.write("Avg of three numbers: " +s);
   }
// Actual parameters.
  avg(20, 30, 40); // Calling function with passing arguments.
</script>
Output:
     Avg of three numbers: 30

How to call Function in JavaScript Onclick


To call a function in the html document, we have to make a simple button and using onclick event attribute (which is an event handler) along with it, we will invoke the function by clicking on the button.


1. Let’s create a JavaScript program where we will pass argument values to a function parameter list during the function call. When a user clicks on button, the function will invoke.

Program code 3:

<html>
<head>
   <title>Calling function in JavaScript onclick</title>
<script>
// Function declaration.
   function display(name, age, gender){
      document.write("Name: " +name+ " Age: " +age+ " Gender: " +gender);
    }
</script>
</head>
<body>
   <p>Please, click on the given button to call a function</p>
   <input type = "button" onclick = "display('John', 25, 'Male')" value = "Click me">
</body>
</html>

In this program, we have defined a function named “display()” with three parameters: name, age, and gender, and defined it in the head section of the HTML document.

To call this function from head, we have used a button in HTML’s body section. When the user clicks that button, the function is called with passing argument values to function parameters and gets executed. The output of this program is as:

Output:
    Name: John Age: 25 Gender: Male

2. Let’s create another HTML program where we will define a function inside the script of head section and call it from inside the script and from the body section using button.

Program code 4:

<html>
<head>
  <title>Calling function by passing parameters</title>
<script>
// Function declaration.
  function calculate(speed, time) {
    var distance = speed * time;
   document.write("Distance travelled: " +distance+ "<br>");
  }
  calculate(25, 5); // Calling function from the head section.
</script>
</head>
<body>
   <input type = "button" onclick = "calculate(30, 4)" value= "click me">
</body>
</html>
Output:
     Distance travelled: 125
     Distance travelled: 120 (on clicking button)

Calling Functions by Passing Arguments from inside another Function


Let’s create a JavaScript program in which we will call functions by passing arguments from inside another function. We will calculate addition, subtraction, multiplication and division of two numbers.

Program code 5:

<script>
// Functions declaration.
  function addition(x, y)
  {
    let p = x + y;
    document.write("Sum: " +p, "<br>");
  }
  function subtraction(x, y)
  {
    let q = x - y;
    document.write("Sub: " +q, "<br>");
   }
  function multiplication(x, y)
  {
    let r = x * y;
    document.write("Multiply: " +r, "<br>");
  }
  function division(x, y)
  {
   let s = x / y;
   document.write("Division: " + s);
  }
  function main()
  {
// Calling function inside another function by passing argument values.
   addition(20, 30);
   subtraction(30, 10);
   multiplication(10, 20);
   division(20, 5);
  }
  main();
</script>
Output:
     Sum: 50
     Sub: 20
     Multiply: 200
     Division: 4

Calling Functions with Default Argument Values


If we call a function by passing fewer arguments than the number of named parameters, the extra parameters turn up as undefined.

For example, if a function definition contains three parameters, but we call it with two arguments, the third parameter will set with a value of undefined in the function.

Similarly, if we call a function by passing more arguments than the number of parameters, then they ignored.

Consider the following the example program.

Program code 6:

<script>
// Function 1 declaration.
  function m1(x, y, z)
  {
    document.write("Value of x = " +x, "<br>");
    document.write("Value of y = " +y, "<br>");
    document.write("Value of z = " +z, "<br>");
  }
  m1(25, 20); // Calling function by passing only two arguments.
// Function 2 declaration.
  function m2(a, b)
  {
   document.write("Value of a = " +a, "<br>");
   document.write("Value of b = " +b);
  }
 m2(2, 4, 8); // JavaScript will ignore third argument.
</script>
</head>
Output:
     Value of x = 25
     Value of y = 20
     Value of z = undefined
     Value of a = 2
     Value of b = 4

As you can observe in the program, the first function contains three parameters, but we call it by passing only two arguments. As a result, the third parameter sets with the value of undefined.


How to Set Default Parameter Values?

JavaScript also allows us to set default values something other than undefined. The most widely supported and accepted way is that first check whether the argument is undefined.

If so, then set the default value. For example, consider the below program where the function has one parameter. Inside the function, we will check whether the argument is undefined. If so, we will set a default value.

Program code 7:

<html>
<head>
   <title>Setting default parameter values</title>
<script>
  function welcome(yourName)
  {
// Checking whether the argumenet is undefined or not. 
   if(typeof yourName == 'undefined') {
    yourName = "friend"; // Setting defualt value to the parameter.
   }
document.write(yourName);
}
welcome();
</script>
</head>
<body>
</body>
</html>
Output:
      friend

ECMAScript 6 also allows to set the default values for parameters inside the function head, as shown in the below code.

Program code 8:

<html>
<head>
   <title>Setting a default value in the function head</title>
<script>
  function welcome(yourName = "John")
  {
    document.write("Welcome ", yourName);
  }
  welcome();
</script>
</head>
<body>
</body>
</html>
Output:
    Welcome John

Arguments Keyword in JavaScript


We can also define a function to accept a variable number of arguments. JavaScript provides an arguments keyword that is a special variable.

This variable allows for a function to accept arguments that dynamically change each time the function is called. For example, the first argument is functionName.arguments[0], the second one is functionName.arguments[1], the third one is functionName.arguments[2], and so on.

JavaScript stores the number of arguments handed to the function in the length property of arguments object. The arguments object contains an array of all arguments passed to the function. The syntax is as:

functionName.arguments.length

Consider the following script code that illustrates this concept:

Program code 9:

<html>
<head>
  <title>Arguments keyword in JavaScript</title>
<script>
  function display()
  {
    document.write("First argument is " +display.arguments[0], "<br>");
    document.write("Second argument is " +display.arguments[1], "<br>");
    document.write("Third argument is " +display.arguments[2], "<br>");
    document.write("Number of arguments = " +display.arguments.length, "<br>");
  }
  display(2, 4, 6);
</script>
</head>
<body>
</body>
</html>
Output:
     First argument is 2
     Second argument is 4
     Third argument is 6
     Number of arguments = 3

In this program, arguments.length counts the number of arguments in the array.

We can use for loop or for…in loop to print a list of arguments handed to the function. Let us consider an example based on this concept.

Program code 10:

<html>
<head>
   <title>Iterating Arguments in JavaScript</title>
<script>
  function cityList()
  {
    var result = ""; // initial empty string variable.
    for(let x = 0; x < cityList.arguments.length; x++)
    {
  // Adding each argument supplied to result variable.
     result += cityList.arguments[x]+ "<br>";
    }
   document.write(result);
  }
  cityList("Dhanbad", "New York", "Mumbai", "Sydney", "Tokyo");
</script>
</head>
<body>
</body>
</html>
Output:
     Dhanbad
     New York
     Mumbai
     Sydney
     Tokyo

Let’s create a JavaScript program in which we will sum of all input values.

Program code 11:

<html>
<head>
  <title>Calculating sum of all input values</title>
<script>
  function sumAll()
  {
    let sum = 0;
    for (let x = 0; x < arguments.length; x++)
    {
      sum += arguments[x];
    }
   document.write("Sum of all numbers = " +sum);
  }
  sumAll(10, 20, 30, 40, 50, 60);
</script>
</head>
<body>
</body>
</html>
Output:
     Sum of all numbers = 210

In this tutorial, you learned how to call a function in JavaScript by passing arguments. Hope that you will have understood the concepts of calling a function when a user clicks on a button.
Thanks for reading!!!
Next ⇒ Pass by Value in JavaScript⇐ PrevNext ⇒

Please share your love