Default Parameters
Give function parameters fallback values so callers can leave them out — the clean modern replacement for the old `x = x || fallback` trick.
Fallback values, built into the function
Functions often need a sensible default when an argument is left out. Before 2015, you faked it inside the function body:
function greet(name) {
name = name || "friend"; // old workaround
return "Hi, " + name;
}That || "friend" trick is noisy and has a subtle bug (it also replaces valid values like 0 or ""). Modern JavaScript lets you declare the default right in the parameter list:
function greet(name = "friend") {
return "Hi, " + name;
}If the caller passes a value, it's used; if they leave it out (or pass undefined), the default kicks in. You'll see this constantly in React components and configuration functions.
Defaults apply only when the argument is undefined (including when it's omitted). Passing null, 0, or "" does not trigger the default — those are real values. That's exactly why defaults are safer than the old || trick.