WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Set Default Parameter Value for a JavaScript Function

Topic: JavaScript / jQueryPrev|Next

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

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties