Skip to content

Latest commit

 

History

History
94 lines (70 loc) · 2.57 KB

File metadata and controls

94 lines (70 loc) · 2.57 KB

#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 Bogart

This 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:

  • false
  • undefined
  • null
  • NaN
  • 0
  • ""

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 of name is truthy.

  • If name is truthy then it returns the passed value name.

  • If name is 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.

Javascript shortcuts

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 driversLicense is truthy and if it is it then calls registerDriver with driversLicense passed as a paramater.
  • If driversLicense is falsy it moves to the right and calls the declineDriver function with driversLicense passed as a paramater.