Problem Statement
What happens if you call a function with fewer arguments than parameters?
Explanation
If you call a function with fewer arguments than parameters, the missing parameters are automatically set to undefined.
JavaScript does not enforce the number of arguments and allows you to pass more or fewer arguments than the function expects.
This flexibility can be useful but also requires defensive coding to handle missing arguments.
You can use default parameters introduced in ES6 to provide fallback values for missing arguments.
Code Solution
SolutionRead Only
function greet(firstName, lastName) {
console.log(firstName); // 'John'
console.log(lastName); // undefined
}
greet('John'); // Called with only 1 argument
// Default parameters (ES6)
function sayHello(name = 'Guest') {
console.log('Hello ' + name);
}
sayHello(); // 'Hello Guest'
sayHello('John'); // 'Hello John'
// Old way to handle defaults
function oldWay(name) {
name = name || 'Guest';
console.log('Hello ' + name);
}
// Multiple defaults
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // 5 (5 * 1)
console.log(multiply(5, 2)); // 10
// Undefined triggers default
function test(x = 10) {
console.log(x);
}
test(undefined); // 10 (default used)
test(null); // null (default NOT used)