default parameter in javascript function code example

Example 1: js default parameter

function greeting (name = 'stranger') {
  console.log(`Hello, ${name}!`)
}

greeting('Nick') // Output: Hello, Nick!
greeting() // Output: Hello, stranger!

Example 2: javascript parameter default parameter

function say(message='Hi') {
    console.log(message);
}
say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello'); // 'Hello'


function date(d = today()) {
    console.log(d);
}
function today() {
    return (new Date()).toLocaleDateString("en-US");
}
date();


function add(x = 1, y = x, z = x + y) {
    return x + y + z;
}
console.log(add()); // 4