Javascript Parameters and arguments
As placeholders for the values that will be supplied to a function when it is called, JavaScript functions can accept arguments. Arguments are the actual values that are sent to the function.
Syntax:
function functionName(param1, param2, ...) {
// function body
}
Example:
function addNumbers(num1, num2) {
var sum = num1 + num2;
return sum;
}
var result = addNumbers(5, 7); // calling the function with arguments
console.log(result); // Output: 12
The function addNumbers in the preceding illustration takes the two arguments num1 and num2 as inputs. The function adds the two integers when it is called with arguments 5 and 7, then returns the result, which is then saved in the result variable.
In cases when no value is supplied for a parameter when the function is called, default values for that parameter may also be utilized.
Syntax for defining a function with default parameter values:
function functionName(param1 = defaultValue1, param2 = defaultValue2, ...) {
// function body
}
Example:
function greet(name = 'Guest') {
console.log('Hello, ' + name + '!');
}
greet(); // Output: Hello, Guest!
greet('John'); // Output: Hello, John!
The greet function in the example above receives a parameter name with the default value of “Guest.” Without any parameters, the function will output Hello, Guest! and use the default value. The function will utilise that argument instead and produce Hello, John! if it is invoked with an argument like ‘John’.