You can easily introduce default values for the arguments passed to a function.
Consider this function -
function sayHello(name) {
return `hello ${name}`;
}
Calling this function without arguments will provide a not-so-pretty string.
console.log(sayHello()); // hello undefined
Even if someone had an existential crisis, I doubt they will like to be called ‘undefined’. So - let us change that.
function sayHello(name) {
name = name || "world";
return `hello ${name}`;
}
The ‘or’ statement will -
- retain
namevalue if provided - assign ‘world’ to
nameifnameis falsy
The results are more pleasing.
console.log(sayHello()); // hello world
console.log(sayHello("Neo")); // hello Neo
You can also use a ternary operator or a full-fledged if statement, but the above code looks more to the point but at the same time readable.