Default Parameters and Enhanced Object Literals
Default Parameters and Enhanced Object Literals
Default Parameters
Objective: Learn how to set default values for function parameters to make
functions more robust and avoid errors.
a. Setting Default Values for Function Arguments
In ES6, you can provide default values for function parameters. If no value is
passed when calling the function, the default value is used.
Example:
javascript
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
console.log(multiply(5)); // Output: 5
● Explanation:
o Default parameters ensure that functions behave predictably, even
when arguments are missing.
const user = {
name: name,
age: age,
};
console.log(user); // Output: { name: 'Alice', age: 25 }
With ES6:
javascript
const name = "Alice";
const age = 25;
const user = {
name,
age,
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age}
years old.`);
},
};
console.log(user);
// Output: { name: 'Alice', age: 25, greet: [Function: greet] }
logNumbers(1, 2, 3, 4, 5);
// Output: [1, 2, 3, 4, 5]
Explanation:
o The ...numbers (rest operator) collects all arguments passed to the
function into an array.
o You can process an unknown number of inputs dynamically.
2. Calculate the Sum of Numbers Using Rest Operator:
javascript
function calculateSum(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
console.log(calculateSum(1, 2, 3));
// Output: 6
Explanation:
o reduce() processes the array created by the rest operator and
calculates the sum.
o The rest operator simplifies handling multiple arguments without
explicitly defining them.