+
operator when used as a unary operator always converts its operand to a number
.+
operator on a value is functionally equivalent to casting the value using the Number()
function.+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
+
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
.+
operator to convert values to string
is functionally equivalent to casting values to string using the String()
function.
([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 is commonly used as a replacement for very simple if
statements&&
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);
var personProfile = person && fetchProfile(person);
||
operator returns the first operand if it is truthy
, otherwise it returns the second operand.||
short-circuiting is commonly used when assigning fallback values to local variables