Default parameters and Spread Operator in JavaScript
Default parameters and Spread Operator
36
Default parameters and Spread Operator are two important features of JavaScript that allow developers to write cleaner and more efficient code.
Default parameters are useful when defining functions in JavaScript. They provide a way to define a default value for a parameter in case the function is called without that parameter being passed in by the caller. This can be helpful in situations where you want to avoid error messages or unexpected results.
For example:
function greet(name = "stranger") { console.log(`Hello, ${name}!`); } greet(); // Output: "Hello, stranger!" greet("John"); // Output: "Hello, John!"
In the above example, the greet
function has a default value of "stranger" for the name
parameter, which will be used if the parameter is not passed in when the function is called.
The Spread Operator is used to spread the elements of an array or an object into individual elements. This operator is denoted by three dots: ...
. The spread operator can be used to perform various tasks such as copying an array or object, merging objects, and flattening nested arrays.
Here's an example:
const numbers = [1, 2, 3]; const newNumbers = [...numbers, 4, 5, 6]; console.log(numbers); // Output: [1, 2, 3] console.log(newNumbers); // Output: [1, 2, 3, 4, 5, 6]
In the above example, the Spread Operator is used to spread the elements of the numbers
array into individual elements and append them to a new array along with the elements 4, 5, and 6.
Overall, Default parameters and Spread Operator are useful features of JavaScript that can make your code more concise and easier to read.
March 25, 2023