Created
April 7, 2020 10:15
-
-
Save solancer/7c54d2842812e53f9d9bc0f56d7b14a0 to your computer and use it in GitHub Desktop.
funcPatterns for JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let getDimentions = (length, height) => ({length, height}); | |
| // It is same as | |
| getDimentions = (length, height) => { | |
| return {length: length, height: height}; | |
| }; | |
| // function arguments defaults: Old way | |
| getDimentions = (length, height) => { | |
| if (!length) { | |
| length = 0; | |
| } | |
| if (!height) { | |
| height = 0; | |
| } | |
| return {length, height}; | |
| }; | |
| // Better Way: function default parameters | |
| getDimentions = (length = 0, height = 0) => ({length, height}); | |
| // destructuring | |
| let {height} = getDimentions(23, 56); | |
| // default functions object parameters | |
| let getRGB = ({r,g,b}) => `color: (${r}, ${g}, ${b});`; | |
| // It is same as | |
| getRGB = (color) => { | |
| const r = color.r; | |
| const g = color.g; | |
| const b = color.b; | |
| return `color: (${r}, ${g}, ${b});`; // or 'color: (' + r + '), (' + g + '), (' + b ');'; | |
| }; | |
| // Default for Object | |
| getRGB = ({r,g,b} = {r: '', g: '', b: ''}) => `color: (${r}, ${g}, ${b});`; | |
| // What if I want default for Object parameters | |
| getRGB = ({r = '',g = '',b = ''} = {r: '', g: '', b: ''}) => `color: (${r}, ${g}, ${b});`; | |
| // Tag function (with template literals) | |
| let greet = (...arguments) => { | |
| console.log(arguments); | |
| } | |
| let name = 'Joe'; | |
| let age = 22; | |
| greet`I'm ${name}. I'm ${age} years old.`; | |
| greet = (strings, ...values) => { | |
| console.log(strings, values); | |
| } | |
| // We would get following | |
| // strings = ['I'm ', '. I'm ', ' years old.'] | |
| // values = ['Joe', 22] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment