Function Arguments

We have seen Math.random() with an empty set of parenthesis returning a result. If a function can do stuff without being told anything, we leave the parenthesis empty when we define it. On the other hand we have also seen Math.floor(2.54) returning 2. This function needs to know what to floor. The 2.54, or a variable with some value may be given as an input argument to the function. Let us see how this is done:

'use strict';
function sum(a, b) {
    return a + b;
}

The variables a, and b constitute an argument list for the function. The argument variables in the function are assigned values when the function is called:

var s1 = sum(40, 2);
console.log(s1);

In this example a is assigned the value 40, and b the value 2. Sum will then return the value 42, and that will be printed by the program. If the function call was

var s1 = sum(100, 17);
console.log(s1);

The variables a, and b would get the values 100, and 17 respectively, bringing the program to print the value 117.

You do not use the JavaScript keywords let, var, or const to define the argument variables. If a function call does not provide values for all the arguments, those not given values will remain undefined.

'use strict';
function hi(name, name2, name3) {
console.log(`hello, ${name}, ${name2}, ${name3}`);
}
hi('abel', 'beatrice');
hello, abel, beatrice, undefined