Setting Default Parameters

Samantha Ming
DailyJS
Published in
4 min readFeb 4, 2020

--

CodeTidbit by SamanthaMing.com

Super simple to set Default Parameters with ES6 👏‬ The old way was to use a ternary operator to assign the default value if it was undefined. With ES6, you can set the default value right inside the function parameters 🎉

// Old Way
function beverage(drink) {
drink = drink !== undefined ? drink : '🍵';
}
// ✅ ES6 Way
function beverage(drink = '🍵') {}

When the default value kicks in 🥾

The default value only kicks if no value or undefined is passed. Let's take a look:

function beverage(drink = '🍵') {
return drink;
}
beverage(); // '🍵'
beverage(undefined); // '🍵'

undefined vs other falsy values

Does the default value kick in for other falsy values? Great question! Let’s take a look:

function beverage(drink = '🍵') {
return drink;
}
beverage(false); // false
beverage(null); // null
beverage(NaN); // NaN
beverage(0); // 0
beverage(''); // ""

☝️The answer is NO. The default value only kicks in for undefined. All other times, the value that you passed through will take effect 🙂

Setting Default Parameter for ALL falsy values

--

--

Samantha Ming
DailyJS

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛