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 sum(x = 1, y = x, z = x + y) {
console.log( x + y + z );
}
sum(); // 4
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 greeting (name = 'stranger') {
console.log(`Hello, ${name}!`)
}
greeting('Nick') // Output: Hello, Nick!
greeting() // Output: Hello, stranger!
xxxxxxxxxx
function sum(x, y = 5) {
// take sum
// the value of y is 5 if not passed
console.log(x + y);
}
sum(5); // 10
sum(5, 15); // 20
xxxxxxxxxx
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1
return a * b
}
xxxxxxxxxx
// Default parameters let you assign a default value to a parameter when you define a function. For example:
function greeting(name, message = ”Hello”){
console. log(`${messgae} ${name}`)
}
greeting(‘John’); //output: Hello John
//you can also assign a new value to the default parameter
//when you call the function
greeting(‘Doe’, ‘Hi’); //output: Hi Doe
xxxxxxxxxx
function sum(x = 3, y = 5) {
// return sum
return x + y;
}
console.log(sum(5, 15)); // 20
console.log(sum(7)); // 12
console.log(sum()); // 8