Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. ## Type Conversion - Number and String
  2.  
  3. 1. The `+` operator when used as a unary operator always converts its operand to a `number`.
  4. 2. 2. Using the unary `+` operator on a value is functionally equivalent to casting the value using the `Number()` function.
  5. 1. `+new Date === Number(new Date); // true`
  6.  
  7. ```javascript
  8. console.log(+'100'); // 100
  9. console.log(+null); // 0
  10. console.log(+void 0); // NaN
  11. console.log(+true); // 1
  12. console.log(+false); // 0
  13. console.log(+[]); // 0
  14. console.log(+[100]); // 100
  15. console.log(+[100, 50]); // NaN
  16. console.log(+{}); // NaN
  17. console.log(+new Date); // 1527790306576
  18. ```
  19.  
  20. 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`.
  21. 2. Using the `+` operator to convert values to `string` is functionally equivalent to casting values to string using the `String()` function.
  22. 1. `([100, 50] + '') === String([100, 50]); // true`
  23.  
  24. ```javascript
  25. console.log(100 + ''); // "100"
  26. console.log(null + ''); // "null"
  27. console.log(void 0 + ''); // "undefined"
  28. console.log(true + ''); // "true"
  29. console.log(false + ''); // "false"
  30. console.log([] + ''); // ""
  31. console.log([100] + ''); // "100"
  32. console.log([100, 50] + ''); // "100,50"
  33. console.log({} + ''); // "[object Object]"
  34. console.log(new Date + ''); // "Thu May 31 2018 19:28:09 GMT+0100 (WAT)"
  35. ```
  36.  
  37. ## Short-Circuiting
  38.  
  39. 1. The logical `&&` short-circuiting is commonly used as a replacement for very simple `if` statements
  40. 2. *The logical `&&` operator returns the first operand if it is falsy, otherwise it returns the second operand.*
  41.  
  42. ```javascript
  43. if (person) {
  44. fetchProfile(person);
  45. }
  46.  
  47. // METHOD 2: Using short-circuiting
  48. person && fetchProfile(person);
  49. ```
  50.  
  51. 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.
  52.  
  53. ```javascript
  54. var personProfile = person && fetchProfile(person);
  55. ```
  56.  
  57. 1. The logical `||` operator returns the first operand if it is `truthy`, otherwise it returns the second operand.
  58. 2. The logical `||` short-circuiting is commonly used when assigning fallback values to local variables
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement