Member-only story
As a JavaScript developer, understanding function parameters is crucial for writing efficient and maintainable code. In this article, we’ll dive into three powerful parameter contexts: default, rest, and spread. These concepts will help you streamline your code, handle varying numbers of arguments, and work with arrays and objects more effectively.
Default Parameters
Before ES6 (ECMAScript 2015), developers had to write additional code to handle missing arguments or provide default values. With the introduction of default parameters, this process became much simpler.
Default parameters allow you to specify a default value for a function parameter if no value is provided when the function is called.
function greetUser(name = 'Friend') {
console.log(`Hello, ${name}!`);
}
greetUser('Alice'); // Output: Hello, Alice!
greetUser(); // Output: Hello, Friend!
In the example above, if no argument is provided when calling the greetUser
function, the name
parameter defaults to 'Friend'
. This feature helps prevent errors caused by missing arguments and makes your code more readable and maintainable.