Default Parameters In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Default Parameters In JavaScript.
Default Parameters In JavaScript
In JavaScript, you can specify default values for function parameters by assigning a default value directly in the function signature. If the argument is not provided or is undefined
, the default value will be used. Here’s an example:
function greet(name = "John Doe") {
console.log("Hello, " + name);
}
greet();
greet("Jane");
Output
"Hello, John Doe"
Hello, Jane"
In the example above, if no argument is provided to the greet
function, it will use the default value of “John Doe”. If an argument is provided, it will use the provided value instead.
You can also specify default values for multiple parameters, like this:
function greet(name = "John Doe", greeting = "Hello") {
console.log(greeting + ", " + name);
}
greet();
greet("Jane");
greet("Jane", "Hi");
Output
"Hello, John Doe"
Hello, Jane"
"Hi, Jane"
It’s also possible to use expressions or reference previous parameters as default values. Here’s an example:
function greet(greeting = "Hello", name = greeting + " John Doe") {
console.log(greeting + ", " + name);
}
greet();
greet("Hi");
greet("Hi", "Jane");
Output
"Hello, Hello John Doe"
"Hi, Hi John Doe"
"Hi, Jane"
In the example above, if no greeting
argument is provided, it will default to “Hello”. If no name
argument is provided, it will default to greeting + " John Doe"
.
Conclusion
If you liked this post Default Parameters In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.