#JavaScript shortcuts
In this topic we're going to cover a few simple JavaScript shortcuts. Consider this code:
function userName(name) {
if (!name) {
name = "Not applicable";
}
return name;
}
console.log(userName("")); // Not applicale
console.log(userName("Humphrey Bogart")); // Humphrey BogartThis function checks to see if the value of name is falsy. If it is, it then assigns the value Not applicable before it returns. If it isn't, we return the passed value name.
Here's a recap of truthy and falsy values:
Falsy values:
falseundefinednullNaN0""
Truthy values:
true{}[]89-5"string"new Date()
Shortcut:
This much shorter code does the same as the example above:
function userName(name) {
name = name || "Not applicable";
return name;
}
console.log(userName("")); // Not applicable
console.log(userName("James Stewart")); // James Stewart-
The
||operator first checks the left to see wether the value ofnameis truthy. -
If
nameis truthy then it returns the passed valuename. -
If
nameis falsy it gets assigned the value to the right (Not applicable) and returns that value.
Even Shorter Shortcut using default values/parameters
function userName(name = "Not applicable") {
return name;
}
//Attention!
console.log(userName("")); // returns ""
console.log(userName()); // returns "Not applicable"
console.log(userName("James Stewart")); // James Stewart- Default function parameters allow formal parameters to be initialized with default values if no value (at all) or undefined is passed.
In this if statement we check if driversLicense is truthy, if it is it calls the registerDriver function and passes driversLicense as a parameter. If driversLicense does not evaluate to truthy, it calls the declineDriver function and passes in the driverLicense parameter.
if (driversLicense) {
registerDriver(driversLicense);
}
else {
declineDriver(driversLicense);
}Shortcut:
driversLicense && registerDriver(driversLicense) || declineDriver(driversLicense);- It first checks the left to see if
driversLicenseis truthy and if it is it then callsregisterDriverwithdriversLicensepassed as a paramater. - If
driversLicenseis falsy it moves to the right and calls thedeclineDriverfunction withdriversLicensepassed as a paramater.
