Is it possible to set default values for parameters in a JavaScript function, such as in the example below?
function exampleFunction(param1, param2 = 0) { // param2 serves as the optional parameter }
Can this be done in JavaScript?
Is it possible to set default values for parameters in a JavaScript function, such as in the example below?
function exampleFunction(param1, param2 = 0) { // param2 serves as the optional parameter }
Can this be done in JavaScript?
In JavaScript, you can define optional parameters in functions using default parameters. This method allows you to set default values for parameters if no value or undefined
is passed when the function is called.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Outputs: Hello, Guest!
greet('David'); // Outputs: Hello, David!
In this example, the name
parameter is optional because it has a default value of 'Guest'. If greet()
is called without an argument, it uses 'Guest' as the default.
This approach ensures efficiency and simplicity in your code by reducing the need for multiple checks and conditional logic to handle optional parameters.