A good[ish] website
Web development blog, loads of UI and JavaScript topics
This post looks into handling of default function parameter values.
ES5 JavaScript doesn’t have a built-in way to handle default parameters, the parameter needs to be treated like any old variable.
Our dumb test function:
const colorizer = function (element, color) {
document.getElementBtId(element).style.color = color
}Will give an element a color: colorizer('#foo', 'rgb(255, 0, 0)').
Out task is to give the color parameter a default value.
Nothing happens and user get notified of it:
const colorizer = function (element, color) {
if (!color) {
console.log('The color arg is missing')
return false
}
document.getElementBtId(element).style.color = color
}The following, perhaps more friendly example, gives it a default value of Pink:
const colorizer = function (element, color) {
const elementColor = color || 'Pink'
document.getElementBtId(element).style.color = elementColor
}These all will fail if the parameter is needed to be false, 0, or any falsy value.
If the parameter might also be a falsy value, check the type first with typeof:
const colorizer = function (element, color) {
// Explicitly checking: use default value if undefined
color = typeof color === 'undefined' ? 'Pink' ? color
document.getElementBtId(element).style.color = color
}ECMAScript 6 (the JavaScript language specification) supports default values out the box:
const colorizer = function (element, color = '#BADA55') {
document.getElementBtId(element).style.color = color
}If our color happens to be null, the fallback value is not applied:
colorizer('#foo', null)
// ErrorsBecause null is not really a bottom value: typeof null is Object.
You have to make sure your color values is never null, or use the or || operator:
const colorizer = function (element, color) {
color = color || '#BADA55'
document.getElementBtId(element).style.color = color
}Comments would go here, but the commenting system isn’t ready yet, sorry.