Topic 54 of 87
Parameters & Arguments
Overview
These terms are often used interchangeably, but they are different. - Parameters are the named variables listed in the function definition. - Arguments are the actual, real values passed into the function when it is executed.
ES6 introduced Default Parameters, allowing you to set a fallback value if an argument is missing or undefined.
Syntax
Default Parameters
javascript
// 'name' and 'age' are Parameters
// We set 18 as the Default Parameter for age
function welcome(name, age = 18) {
console.log(`Hi ${name}, age ${age}`);
}
// 'Kartik' is the Argument
welcome("Kartik"); // "Hi Kartik, age 18"
welcome("Aman", 25); // "Hi Aman, age 25"Common Pitfalls
- Passing
nullto a default parameter. If you callwelcome('John', null), theagewill actually benull, not the default18. Default parameters ONLY trigger if the argument is strictlyundefinedor omitted entirely.
Interview Questions
Q:
What happens if you pass more arguments than there are parameters defined?
A:
JavaScript doesn't throw an error. It simply ignores the extra arguments. However, you can still access them using the arguments object or the Rest parameter (...args).
Real-World Example
Providing fallback values for configuration objects or network requests to prevent crashes.
example
javascript
function connectDB(url, timeout = 3000) {
// timeout is safely 3000 if not provided
}Check Your Knowledge
Test your understanding of Parameters & Arguments with these quick questions.