Set a default value for the argument to cover undefined errors while calling a function in JavaScript


If you won’t pass value to a function(), it will print the default value otherwise given parameter will be printed.

Following is the code. We are setting a default here i.e. “Jack” in this case to avoid any undefined error when a function is called without any parameter −

Example

function display({ name = 'Jack' } = {}) {
   console.log(`Hi My Name is ${name}!`);
}
display();
display({name:"Taylor Swift"});

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo171.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo171.js
Hi My Name is Jack!
Hi My Name is Taylor Swift!

Updated on: 12-Sep-2020

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements