Default Parameters in JavaScript (ES6)
Default parameters in JavaScript are a great addition introduced in ES6. They make it easy to set a default value for function parameters, making your code more readable and maintainable. This blog post is all about understanding and making the most of default parameters.
What are Default Parameters?
In JavaScript, default function parameters allow you to initialize formal parameters with default values. This means if no values or undefined
is passed for a function argument, the default value is used.
Here’s a simple example:
function greet(name = 'World') {
return `Hello, ${name}!`;
}
console.log(greet()); // 'Hello, World!'
console.log(greet('Alice')); // 'Hello, Alice!'
In this case, if no argument is passed to the greet
function, 'World' will be used as the default value for name
.
Using Default Parameters
Default parameters can be any valid JavaScript expressions. They are not limited to strings, numbers, or booleans. You can use arrays, objects, or even functions:
function createGrid([width = 5, height = 5] = []) {
return { width, height };
}
console.log(createGrid()); // { width: 5, height: 5 }
console.log(createGrid([10])); // { width: 10, height: 5 }
console.log(createGrid([10, 20])); // { width: 10, height: 20 }
In this example, the createGrid
function uses both array destructuring and default parameters to create an object.
Note on undefined
and null
It’s important to note that default parameters only kick in for undefined
values. null
, false
, 0
, or ''
(empty string) are all considered valid values. If you pass null
or any other "falsy" value as the argument, the default parameter will not be used:
function greet(name = 'World') {
return `Hello, ${name}!`;
}
console.log(greet(null)); // 'Hello, null!'
Conclusion
Default parameters in JavaScript are a powerful tool that can make your functions more flexible and easier to use. They can greatly simplify your code and make it more readable.
In the next post, we’ll move to the enhanced object literals in ES6 which makes working with objects more efficient. Stay tuned!