xxxxxxxxxx
function greet(name = 'Anonymous') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Anonymous!
greet('Alice'); // Output: Hello, Alice!
xxxxxxxxxx
// Example 1: Setting default value for a single parameter
function greet(name = 'friend') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, friend!
greet('Alice'); // Output: Hello, Alice!
// Example 2: Setting default values for multiple parameters
function calculateArea(length = 5, width = 5) {
const area = length * width;
console.log(`The area is ${area} square units.`);
}
calculateArea(); // Output: The area is 25 square units.
calculateArea(3, 7); // Output: The area is 21 square units.
xxxxxxxxxx
function multiply(a, b = 1) {
return a * b
}
multiply(5, 2) // 10
multiply(5) // 5
multiply(5, undefined) // 5
xxxxxxxxxx
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1
return a * b
}
xxxxxxxxxx
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1
return a * b
}
multiply(5, 2) // 10
multiply(5) // 5
xxxxxxxxxx
const greet = (message = 'Hello World!') => console.log(message);
greet(); // prints 'Hello World!'
greet('Hello! Does this answer your question?') // prints 'Hello! Does this answer your question?'
xxxxxxxxxx
// Default Parameter Values in javascript
// Longhand:
function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
console.log(volume(2)); //output: 24
// Shorthand:
volume_ = (l, w = 3, h = 4 ) => (l * w * h);
console.log(volume_(2)) //output: 24
xxxxxxxxxx
function say(message='Hi') {
console.log(message);
}
say(); // 'Hi'
say('Hello') // 'Hello'