Parameters and Arguments in Javascript Functions

Parameters are the values given inside the parentheses when you define the function.

Arguments are the values that are passed to the function when the function is called/invoked.

For example:

If you want to calculate the sum of two numbers and you want to pass the value of those two numbers while calling the function, that’s where parameters and arguments come into action.

Let us make it more clear with an example:

let number1 = 45;
let number2 = 56;
function sum(num1,num2)// Variables num1,num2 are parameters 
    {
      let sum = num1 + num2;
      alert("The sum of two numbers is " + sum);
    }
sum(number1,number2);//number1 and number2 are the arguments 

Output : The sum of two numbers is 101

As we can see in the example above:

num1 and num2 are the parameters whose values are not known. Variables number1 and number2 store the two numbers whose sum is to be calculated. These values are passed as arguments to the sum() function during the function call. This way num1 will get the value of the number1 i.e. 45 and num2 will get the value of the number2 i.e. 56 and the sum is calculated and alerted to the user as defined in the function.

Important notes:

  • Data types of parameters are not specified in the function definition like num1 and num2 are declared without the data type.
  • Javascript functions do not check the number of arguments received, i.e. if I have two parameters in the function definition and I pass just one argument to the function, no error will be shown, the value of the second parameter will be considered as undefined. For example:
let number1 = 45;
let number2 = 56;
function sum(num1,num2)// Variables num1,num2 are parameters 
    {
      let sum = num1 + num2;
      alert("The sum of two number is " + sum);
    }
sum(number1);// Passing just one argument instead of two. 

Output: The sum of two numbers is NaN .

NaN stands for Not A Number.

  • Javascript functions do not perform type checking on the passed arguments. For example:
let name1 = "John";
let number1 = 56;
function sum(num1,num2)// Variables num1,num2 are parameters 
    {
      let sum = num1 + num2;
      alert(sum);
    }
sum(name1,number1);//Passing a string value and an integer.        

Output :John56

Both values will be treated as a string and will be concatenated, as ‘+’ is a concatenation operator that joins two strings.

If there would have been ‘-‘ ,’/’ ‘*’ operators , then the output would have been :

Output : NaN

Leave a Reply

Your email address will not be published.