Default Parameters

This was one of the ES6 features which were added to set a default value to the function in case no argument is passed.

Example:

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

greeting('John');   // Output: Hello John!
greeting();         // Output: Hello stranger!

Another example:

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs') {
  console.log(`Remember to buy ${item1}`);
  console.log(`Remember to buy ${item2}`);
  console.log(`Remember to buy ${item3}`);
}

Last updated