Q:

How to Set Default Parameter Value for a JavaScript Function

0

How to Set Default Parameter Value for a JavaScript Function

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Assign (=) Operator

We all know that in JavaScript, function parameters default to undefined. However, it is often useful to specify a different default value for the parameter. Since ES6, you can simply use the assign (=) operator to set a default value for a function parameter in JavaScript.

In the following example the default parameter value "There" will be used if the function sayHi() is called without an argument. Let's try it out to understand how it basically works:

// Defining a function
function sayHi(name = 'There') {
    alert('Hi, ' + name);
}

sayHi();  // 0utputs: Hi, There
sayHi('Peter');  // 0utputs: Hi, Peter

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Add Days to Current Date in JavaScript... >>
<< How to Check If a Variable is a String in JavaScri...