Explain Codes LogoExplain Codes Logo

Set a default parameter value for a JavaScript function

javascript
default-parameters
function-signatures
destructuring
Anton ShumikhinbyAnton Shumikhin·Nov 6, 2024
TLDR

Modern JavaScript accommodates default parameters by equipping functions with pre-set values:

const add = (a, b = 5) => a + b; // Hey 'b', ready to fall back to 5? console.log(add(3)); // Gotcha! It's 8!

If b is absent, JavaScript automatically defaults to 5. It's a powerful mechanic for crafting cleaner functions with predictable outcomes.

Core concept: Only undefined triggers defaults

Default values kick in solely when arguments are either undefined or simply not provided. This creates a distinction from the older || assembly, which could result in misleading outcomes:

function add(a, b) { b = b || 4; // No dice when b = 0 return a + b; } // Enter the ES6 superhero const add = (a, b = 4) => a + b; // 'b' got its coat when it's cold (undefined)

Default parameters with destructuring

Ride the ES6 wave even further with destructuring. Below is a combination of destructuring and default values:

function planVacation({ destination = "Hawaii", budget = 3000, travelMode = "Flight" } = {}) { // Prepare your bags, we're going off in style. }

Indeed, we've got named parameters that not only enhance churned out code's readability, but also clarify function signatures.

Diverse default expressions

ES6 avails a luscious buffet of expressive possibilities, incorporating any expression (including function calls!) as default parameters:

function processRequest(payload, sanitizer = () => {}) { // If request payloads were kids, sanitizers would be the candy stranger! 🍬 }

Such flexibility can gracefully navigate around absent callbacks, enhancing robustness.

Traditional JavaScript strategy

For those still brooding around in legacy nests, typeof can be employed to assign defaults without upsetting valid yet falsey values:

function broadcast(message) { message = typeof message !== 'undefined' ? message : "Breaking news!"; // Too shy to give me a message? Let's create a scandal! }

Default wrangling with destructuring

When default parameters meet, mate, and meld with destructuring, we've got a recipe for tackling complex scenarios with ease and aplomb:

const CraftMessage = ({ text, decoration = '✨' }) => `${decoration} ${text} ${decoration}`;

This bolsters code reusability and unclutters prop management.

Null values: The notorious exception

A notable peculiarity emerges when a null value is passed as it does not trigger the default, deemed as a valid value:

function triggerScript(script, trigger = "auto") { // Everything is automatic, unless you want to go manual... with null. return trigger === "auto" ? executeAutomatically(script) : executeManually(script); }

For such cases, an explicit check for null is always a safe bet.

Shorthand utilities for managing defaults

For complex defaulting conditions, shorthand utilities like Object.assign() or lodash's _.defaults() come handy to merge defaults and provided parameters seamlessly:

let defaultConfig = { color: "red", width: 100, height: 200 }; let userConfig = { color: "blue", width: 150 }; let finalConfig = Object.assign({}, defaultConfig, userConfig); // finalConfig is now { color: "blue", width: 150, height: 200 }