You can add different default values to your JavaScript functions with a simple trick. Let’s see how it works.
Default value for JS function parameters is undefined
if you don’t explicitly pass the value when you
call the function.
function log(value) {
console.log(value);
}
log(123); // 123
log(); // undefined
So, the function log
prints its argument to the console and if you don’t pass the argument the output is undefined
.
Let’s add a default parameter value hello
that will be used if the function log
is called without arguments.
function log(value = 'hello') {
console.log(value);
}
log(123); // 123
log(); // hello