How to pass default parameters to a function in JavaScript
Setting default values for function parameters is essential when building robust JavaScript applications that handle optional arguments gracefully. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented default parameters in countless functions across our component library over my 25 years of development experience. The most reliable and modern approach is using ES6 default parameter syntax, which provides clean, readable code and automatic fallback values. This method is well-supported across all modern browsers and eliminates the need for manual undefined checks.
Use ES6 default parameter syntax by assigning values directly in the function signature.
function greet(name = 'World', greeting = 'Hello') {
return `${greeting}, ${name}!`
}
// Usage
greet() // 'Hello, World!'
greet('John') // 'Hello, John!'
greet('John', 'Hi') // 'Hi, John!'
The function signature defines default values using the assignment operator = after each parameter name. When the function is called without arguments or with undefined values, JavaScript automatically uses the default values. If arguments are provided, they override the defaults from left to right. This creates a clean, self-documenting function that handles missing parameters gracefully.
Best Practice Note:
This is the same approach we use in CoreUI components to ensure reliable parameter handling. Default parameters work with any data type including objects, arrays, and function calls, but avoid using mutable objects as defaults to prevent shared state issues.



