JavaScript Program to Set a Default Parameter Value For a Function
Learn JavaScript Program to Set a Default Parameter Value For a Function step by step with clear examples and exercises.
Why This Matters
Learning how to set default parameter values in JavaScript is crucial as it allows you to write flexible and robust functions that can handle missing or unexpected arguments effectively. By providing default values for function parameters, your code will be more resilient to errors and easier to use for others.
Prerequisites
Before diving into setting default parameter values in JavaScript, it is essential to have a solid understanding of the following topics:
- Basic JavaScript syntax (variables, data types, operators)
- Functions in JavaScript (defining, calling, and returning values)
- Control structures like
ifandswitchstatements - Loops such as
for,while, anddo-while
Core Concept
In JavaScript, you can set default parameter values when defining a function using the = operator. The syntax for setting default parameter values is as follows:
function functionName(param1 = default1, param2 = default2, ...) {
// function body
}
When calling this function, if no argument is provided for a parameter with a default value, JavaScript will automatically use the specified default value.
Example 1: Set Default Parameter Value For a Function
Let's create an example to illustrate setting default parameter values in JavaScript:
function sum(x = 3, y = 5) {
// return sum
return x + y;
}
console.log(sum(5, 15)); // Output: 20
console.log(sum(7)); // Output: 12
console.log(sum()); // Output: 8
In the above example, we have a function called sum. The parameters x and y are set with default values of 3 and 5, respectively. When calling the function, if both arguments are provided (as in the first call), they will be used instead of the defaults. If only one argument is provided (second call), the missing argument will take its default value, while the provided argument will replace the other one. Lastly, when no arguments are provided (third call), both parameters will use their respective default values.
Example 2: Using Default Parameter Values with Rest Parameters
function sumAll(...numbers) {
let total = numbers[0] || 0;
for (let i = 1; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
console.log(sumAll([5, 15])); // Output: 20
console.log(sumAll([])); // Output: 0
In this example, we have a function called sumAll that takes any number of arguments using the rest parameter syntax (...numbers). We also set a default value for the total variable (0) to ensure that the function works correctly even when no arguments are provided.
Worked Example
Let's create a more complex example that demonstrates setting default parameter values in a real-world scenario:
function getArea(base = 1, height = 1, shape = "Triangle") {
switch (shape) {
case "Triangle":
const area = (base * height) / 2;
return area;
case "Rectangle":
const width = base;
const length = height;
const area = width * length;
return area;
default:
throw new Error("Invalid shape");
}
}
console.log(getArea(5, 4)); // Output: 10 (Triangle)
console.log(getArea(7, 6, "Rectangle")); // Output: 42 (Rectangle)
console.log(getArea()); // Output: 0.5 (Triangle)
In this example, we have a function called getArea that calculates the area of either a triangle or rectangle based on the provided parameters. By setting default values for all three parameters and using a switch statement, we can call the function with different numbers of arguments or even no arguments at all while still getting the correct result.
Common Mistakes
1. Forgetting to set default values for all parameters
When defining a function with multiple parameters, make sure to set default values for each one if necessary. If you forget to set a default value for a parameter and don't provide an argument when calling the function, JavaScript will throw an error.
2. Incorrectly setting default values
Ensure that the default values you set are appropriate for your function. For example, if you have a function that expects a positive number as an argument but sets its default value to zero, you might encounter unexpected results when calling the function without providing an argument.
3. Using undefined instead of default values
Avoid using undefined as a placeholder for default values. Instead, use the actual default values you want your function to have. This can help you avoid confusion and make your code easier to understand.
Practice Questions
- Write a JavaScript function called
greetthat takes two parameters (name and greeting) with default values "John" and "Hello". The function should return a personalized greeting like "Hello, John!" or "Hello, [Name]!", depending on the provided arguments.
function greet(name = "John", greeting = "Hello") {
const personalizedGreeting = `${greeting}, ${name}!`;
return personalizedGreeting;
}
console.log(greet()); // Output: Hello, John!
console.log(greet("Alice")); // Output: Hello, Alice!
- Write a JavaScript function called
factorialthat calculates the factorial of a number using recursion. The function should have a default value for the input number (n) of 1.
function factorial(n = 1) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // Output: 120
- Write a JavaScript function called
calculateAveragethat calculates the average of an array of numbers. The function should have default values for the input array (numbers) and count (length of the array) as an empty array and 0, respectively.
function calculateAverage(numbers = [], count = 0) {
const total = numbers.reduce((accumulator, currentNumber) => accumulator + currentNumber, 0);
return total / count;
}
console.log(calculateAverage([1, 2, 3])); // Output: 2
console.log(calculateAverage([])); // Output: NaN
FAQ
Q1: Can I set default values for function arguments in JavaScript ES6 and earlier versions?
A1: Yes, setting default values for function arguments is supported in both ES6 and earlier versions of JavaScript. The syntax has been the same since ES6 was introduced.
Q2: What happens if a function with default parameter values is called with more arguments than defined parameters?
A2: If you call a function with more arguments than defined parameters, JavaScript will ignore any extra arguments and only use the specified ones. The remaining arguments will be discarded.
Q3: Can I set default values for rest parameters in JavaScript?
A3: Yes, you can set default values for rest parameters in JavaScript using the spread operator (...) combined with the = operator. Here's an example:
function sumAll(...numbers) {
let total = numbers[0] || 0;
for (let i = 1; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
console.log(sumAll([5, 15])); // Output: 20
console.log(sumAll([])); // Output: 0
In this example, we have a function called sumAll that takes any number of arguments using the rest parameter syntax (...numbers). We also set a default value for the total variable (0) to ensure that the function works correctly even when no arguments are provided.