Hacks in ES5
Explore the handling of optional function parameters in ES5 by using logical OR shortcuts for default arguments. Understand how this technique works and its limitations when dealing with falsey values like 0, empty strings, and false. This lesson helps you grasp how ES5 manages default arguments compared to ES6 improvements.
We'll cover the following...
In some cases, function arguments are optional. For instance, let’s check the following code:
Three arguments of addCalendarEntry are optional.
A popular shorthand for optional parameters in ES5 uses the || (logical or) operator. You can make use of the shortcuts for logical operations.
The value value || defaultValue is value, whenever value is true. If the first operand of a || expression is true, the second operand is not even evaluated. This phenomenon is called a logical shortcut.
When value is false, value || defaultValue becomes defaultValue.
While this approach looks nice on paper, shortcuts are sometimes not flexible enough. All false values are treated in the same way, including 0, '', false. Sometimes, we may want to treat a 0 differently than an undefined indicating the absence of a value.