theonlychase
5/12/2019 - 5:42 PM

JS Tips and Tricks

Type Conversion - Number and String

  1. The + operator when used as a unary operator always converts its operand to a number.
    1. Using the unary + operator on a value is functionally equivalent to casting the value using the Number() function.
    2. +new Date === Number(new Date); // true
console.log(+'100'); // 100
console.log(+null); // 0
console.log(+void 0); // NaN
console.log(+true); // 1
console.log(+false); // 0
console.log(+[]); // 0
console.log(+[100]); // 100
console.log(+[100, 50]); // NaN
console.log(+{}); // NaN
console.log(+new Date); // 1527790306576
  1. The + operator can also be used to convert values to string. Concatenate an empty string('') to any value using the + operator to convert the value to a string.
  2. Using the + operator to convert values to string is functionally equivalent to casting values to string using the String() function.
    1. ([100, 50] + '') === String([100, 50]); // true
console.log(100 + ''); // "100"
console.log(null + ''); // "null"
console.log(void 0 + ''); // "undefined"
console.log(true + ''); // "true"
console.log(false + ''); // "false"
console.log([] + ''); // ""
console.log([100] + ''); // "100"
console.log([100, 50] + ''); // "100,50"
console.log({} + ''); // "[object Object]"
console.log(new Date + ''); // "Thu May 31 2018 19:28:09 GMT+0100 (WAT)"

Short-Circuiting

  1. The logical && short-circuiting is commonly used as a replacement for very simple if statements
  2. The logical && operator returns the first operand if it is falsy, otherwise it returns the second operand.
if (person) {
  fetchProfile(person);
}

// METHOD 2: Using short-circuiting
person && fetchProfile(person);
  1. Note that using short-circuiting actually returns a value since it is a JavaScript expression. Hence, the result of a short-circuiting operation can be stored in a variable or used anywhere JavaScript expects a value.
var personProfile = person && fetchProfile(person);
  1. The logical || operator returns the first operand if it is truthy, otherwise it returns the second operand.
  2. The logical || short-circuiting is commonly used when assigning fallback values to local variables