-
Notifications
You must be signed in to change notification settings - Fork 0
/
localStorage_en.json
1 lines (1 loc) · 206 KB
/
localStorage_en.json
1
{"2016-01-20-return-objects-to-enable-chaining-of-functions.md":{"name":"2016-01-20-return-objects-to-enable-chaining-of-functions.md","sha":"4887cdbc95a75d0685de661ef86adbd7b51f3769","content":"---\nlayout: post\n\ntitle: Return objects to enable chaining of functions\ntip-number: 20\ntip-username: WakeskaterX\ntip-username-profile: https://twitter.com/WakeStudio\ntip-tldr: When creating functions on an object in Object Oriented Javascript, returning the object in the function will enable you to chain functions together.\n\nredirect_from:\n - /en/return-objects-to-enable-chaining-of-functions/\n\ncategories:\n - en\n - javascript\n---\n\nWhen creating functions on an object in Object Oriented Javascript, returning the object in the function will enable you to chain functions together.\n\n```js\nfunction Person(name) {\n this.name = name;\n\n this.sayName = function() {\n console.log(\"Hello my name is: \", this.name);\n return this;\n };\n\n this.changeName = function(name) {\n this.name = name;\n return this;\n };\n}\n\nvar person = new Person(\"John\");\nperson.sayName().changeName(\"Timmy\").sayName();\n```"},"2016-01-16-passing-arguments-to-callback-functions.md":{"name":"2016-01-16-passing-arguments-to-callback-functions.md","sha":"25ef8cc1b6173f1da30ab3ed1eef2024a917ee76","content":"---\nlayout: post\n\ntitle: Passing arguments to callback functions\ntip-number: 16\ntip-username: minhazav\ntip-username-profile: https://twitter.com/minhazav\ntip-tldr: By default you cannot pass arguments to a callback function, but you can take advantage of the closure scope in Javascript to pass arguments to callback functions.\n\nredirect_from:\n - /en/passing-arguments-to-callback-functions/\n\ncategories:\n - en\n - javascript\n---\n\nBy default you cannot pass arguments to a callback function. For example:\n\n```js\nfunction callback() {\n console.log('Hi human');\n}\n\ndocument.getElementById('someelem').addEventListener('click', callback);\n\n```\n\nYou can take advantage of the closure scope in Javascript to pass arguments to callback functions. Check this example:\n\n```js\nfunction callback(a, b) {\n return function() {\n console.log('sum = ', (a+b));\n }\n}\n\nvar x = 1, y = 2;\ndocument.getElementById('someelem').addEventListener('click', callback(x, y));\n\n```\n\n### What are closures?\n\nClosures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. [Check MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) to learn more.\n\nSo this way the arguments `x` and `y` are in scope of the callback function when it is called.\n\nAnother method to do this is using the `bind` method. For example:\n\n```js\nvar alertText = function(text) {\n alert(text);\n};\n\ndocument.getElementById('someelem').addEventListener('click', alertText.bind(this, 'hello'));\n```\nThere is a very slight difference in performance of both methods, checkout [jsperf](http://jsperf.com/bind-vs-closure-23).\n"},"2016-01-13-tip-to-measure-performance-of-a-javascript-block.md":{"name":"2016-01-13-tip-to-measure-performance-of-a-javascript-block.md","sha":"f9f84a9770fecf40117952c0adcbf2b86887265d","content":"---\nlayout: post\n\ntitle: Tip to measure performance of a javascript block\ntip-number: 13\ntip-username: manmadareddy\ntip-username-profile: https://twitter.com/manmadareddy\ntip-tldr: For quickly measuring performance of a javascript block, we can use the console functions like `console.time(label)` and `console.timeEnd(label)`\n\nredirect_from:\n - /en/tip-to-measure-performance-of-a-javascript-block/\n\ncategories:\n - en\n - javascript\n---\n\nFor quickly measuring performance of a javascript block, we can use the console functions like\n[`console.time(label)`](https://developer.chrome.com/devtools/docs/console-api#consoletimelabel) and [`console.timeEnd(label)`](https://developer.chrome.com/devtools/docs/console-api#consoletimeendlabel)\n\n```javascript\nconsole.time(\"Array initialize\");\nvar arr = new Array(100),\n len = arr.length,\n i;\n\nfor (i = 0; i < len; i++) {\n arr[i] = new Object();\n};\nconsole.timeEnd(\"Array initialize\"); // Outputs: Array initialize: 0.711ms\n```\n\nMore info:\n[Console object](https://github.com/DeveloperToolsWG/console-object),\n[Javascript benchmarking](https://mathiasbynens.be/notes/javascript-benchmarking)\n\nDemo: [jsfiddle](https://jsfiddle.net/meottb62/) - [codepen](http://codepen.io/anon/pen/JGJPoa) (outputs in browser console)\n\n> Note: As [Mozilla](https://developer.mozilla.org/en-US/docs/Web/API/Console/time) suggested don't use this for production sites, use it for development purposes only."},"2016-01-11-hoisting.md":{"name":"2016-01-11-hoisting.md","sha":"2a9e888c45df7f6fe05ea35705fb68c76dd7b863","content":"---\nlayout: post\n\ntitle: Hoisting\ntip-number: 11\ntip-username: squizzleflip\ntip-username-profile: https://twitter.com/squizzleflip\ntip-tldr: Understanding hoisting will help you organize your function scope.\n\nredirect_from:\n - /en/hoisting/\n\ncategories:\n - en\n - javascript\n---\n\nUnderstanding [hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) will help you organize your function scope. Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line. Also, a variable **declaration** lets the system know that the variable exists while **definition** assigns it a value.\n\n```javascript\nfunction doTheThing() {\n // ReferenceError: notDeclared is not defined\n console.log(notDeclared);\n\n // Outputs: undefined\n console.log(definedLater);\n var definedLater;\n\n definedLater = 'I am defined!'\n // Outputs: 'I am defined!'\n console.log(definedLater)\n\n // Outputs: undefined\n console.log(definedSimulateneously);\n var definedSimulateneously = 'I am defined!'\n // Outputs: 'I am defined!'\n console.log(definedSimulateneously)\n\n // Outputs: 'I did it!'\n doSomethingElse();\n\n function doSomethingElse(){\n console.log('I did it!');\n }\n\n // TypeError: undefined is not a function\n functionVar();\n\n var functionVar = function(){\n console.log('I did it!');\n }\n}\n```\n\nTo make things easier to read, declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from. Define your variables before you need to use them. Define your functions at the bottom of your scope to keep them out of your way.\n"},"2016-02-04-assignment-shorthands.md":{"name":"2016-02-04-assignment-shorthands.md","sha":"4e6a521fdcacf4c9459121b9a120928602989915","content":"---\nlayout: post\n\ntitle: Assignment Operators\ntip-number: 35\ntip-username: hsleonis\ntip-username-profile: https://github.com/hsleonis\ntip-tldr: Assigning is very common. Sometimes typing becomes time consuming for us 'Lazy programmers'. So, we can use some tricks to help us and make our code cleaner and simpler.\n\nredirect_from:\n - /en/assignment-shorthands/\n\ncategories:\n - en\n - javascript\n---\n\nAssigning is very common. Sometimes typing becomes time consuming for us 'Lazy programmers'.\nSo, we can use some tricks to help us and make our code cleaner and simpler.\n\nThis is the similar use of\n\n````javascript\nx += 23; // x = x + 23;\ny -= 15; // y = y - 15;\nz *= 10; // z = z * 10;\nk /= 7; // k = k / 7;\np %= 3; // p = p % 3;\nd **= 2; // d = d ** 2;\nm >>= 2; // m = m >> 2;\nn <<= 2; // n = n << 2;\nn ++; // n = n + 1;\nn --; n = n - 1;\n\n````\n\n### `++` and `--` operators\n\nThere is a special `++` operator. It's best to explain it with an example:\n\n````javascript\nvar a = 2;\nvar b = a++;\n// Now a is 3 and b is 2\n````\n\nThe `a++` statement does this:\n 1. return the value of `a`\n 2. increment `a` by 1\n\nBut what if we wanted to increment the value first? It's simple:\n\n````javascript\nvar a = 2;\nvar b = ++a;\n// Now both a and b are 3\n````\n\nSee? I put the operator _before_ the variable.\n\nThe `--` operator is similar, except it decrements the value.\n\n### If-else (Using ternary operator)\n\nThis is what we write on regular basis.\n\n````javascript\nvar newValue;\nif(value > 10) \n newValue = 5;\nelse\n newValue = 2;\n````\n\nWe can user ternary operator to make it awesome:\n\n````javascript\nvar newValue = (value > 10) ? 5 : 2;\n````\n\n### Null, Undefined, Empty Checks\n\n````javascript\nif (variable1 !== null || variable1 !== undefined || variable1 !== '') {\n var variable2 = variable1;\n}\n````\n\nShorthand here:\n\n````javascript\nvar variable2 = variable1 || '';\n````\nP.S.: If variable1 is a number, then first check if it is 0.\n\n### Object Array Notation\n\nInstead of using:\n\n````javascript\nvar a = new Array();\na[0] = \"myString1\";\na[1] = \"myString2\";\n````\nUse this:\n\n````javascript\nvar a = [\"myString1\", \"myString2\"];\n````\n\n### Associative array\n\nInstead of using:\n\n````javascript\nvar skillSet = new Array();\nskillSet['Document language'] = 'HTML5';\nskillSet['Styling language'] = 'CSS3';\n````\n\nUse this:\n\n````javascript\nvar skillSet = {\n 'Document language' : 'HTML5', \n 'Styling language' : 'CSS3'\n};\n````\n"},"2016-01-28-curry-vs-partial-application.md":{"name":"2016-01-28-curry-vs-partial-application.md","sha":"fbb0f57678abce6adfafd737a961d910acabc426","content":"---\nlayout: post\n\ntitle: Currying vs partial application\ntip-number: 28\ntip-username: bhaskarmelkani\ntip-username-profile: https://www.twitter.com/bhaskarmelkani\ntip-tldr: Currying and partial application are two ways of transforming a function into another function with a generally smaller arity.\n\n\nredirect_from:\n - /en/curry-vs-partial-application/\n\ncategories:\n - en\n - javascript\n---\n\n**Currying**\n\nCurrying takes a function \n\nf: X * Y -> R\n\nand turns it into a function\n\nf': X -> (Y -> R)\n\nInstead of calling f with two arguments, we invoke f' with the first argument. The result is a function that we then call with the second argument to produce the result. \n\nThus, if the uncurried f is invoked as\n\nf(3,5)\n\nthen the curried f' is invoked as\n\nf(3)(5)\n\nFor example:\nUncurried add()\n\n```javascript\n\nfunction add(x, y) {\n return x + y;\n}\n\nadd(3, 5); // returns 8\n```\n\nCurried add()\n\n```javascript\nfunction addC(x) {\n return function (y) {\n return x + y;\n }\n}\n\naddC(3)(5); // returns 8\n```\n\n**The algorithm for currying.** \n\nCurry takes a binary function and returns a unary function that returns a unary function.\n\ncurry: (X × Y → R) → (X → (Y → R))\n\nJavascript Code:\n\n```javascript\nfunction curry(f) {\n return function(x) {\n return function(y) {\n return f(x, y);\n }\n }\n}\n```\n\n**Partial application**\n\nPartial application takes a function\n\nf: X * Y -> R\n\nand a fixed value for the first argument to produce a new function\n\nf`: Y -> R\n\nf' does the same as f, but only has to fill in the second parameter which is why its arity is one less than the arity of f.\n\nFor example: Binding the first argument of function add to 5 produces the function plus5.\n\n```javascript\nfunction plus5(y) {\n return 5 + y;\n}\n\nplus5(3); // returns 8\n```\n\n**The algorithm of partial application.*** \n\npartApply takes a binary function and a value and produces a unary function. \n\npartApply : ((X × Y → R) × X) → (Y → R)\n\nJavascript Code:\n\n```javascript\nfunction partApply(f, x) {\n return function(y) {\n return f(x, y);\n }\n}\n```\n"},"2016-02-02-create-range-0...n-easily-using-one-line.md":{"name":"2016-02-02-create-range-0...n-easily-using-one-line.md","sha":"ae89ffe397d20515f7f97a10f3ebd9d3b78ae780","content":"---\nlayout: post\n\ntitle: Create array sequence `[0, 1, ..., N-1]` in one line\ntip-number: 33\ntip-username: SarjuHansaliya\ntip-username-profile: https://github.com/SarjuHansaliya\ntip-tldr: Compact one-liners that generate ordinal sequence arrays\n\nredirect_from:\n - /en/create-range-0...n-easily-using-one-line/\n\ncategories:\n - en\n - javascript\n---\n\nHere are two compact code sequences to generate the `N`-element array `[0, 1, ..., N-1]`:\n\n### Solution 1 (requires ES5)\n\n```js\nArray.apply(null, {length: N}).map(Function.call, Number);\n```\n\n#### Brief explanation\n\n1. `Array.apply(null, {length: N})` returns an `N`-element array filled with `undefined` (i.e. `A = [undefined, undefined, ...]`).\n2. `A.map(Function.call, Number)` returns an `N`-element array, whose index `I` gets the result of `Function.call.call(Number, undefined, I, A)`\n3. `Function.call.call(Number, undefined, I, A)` collapses into `Number(I)`, which is naturally `I`.\n4. Result: `[0, 1, ..., N-1]`.\n\nFor a more thorough explanation, go [here](https://github.com/gromgit/jstips-xe/blob/master/tips/33.md).\n\n### Solution 2 (requires ES6)\nIt uses `Array.from` [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from)\n```js\nArray.from(new Array(N),(val,index)=>index);\n```\n\n### Solution 3 (requires ES6)\n\n```js\nArray.from(Array(N).keys());\n```\n\n#### Brief explanation\n\n1. `A = new Array(N)` returns an array with `N` _holes_ (i.e. `A = [,,,...]`, but `A[x] = undefined` for `x` in `0...N-1`).\n2. `F = (val,index)=>index` is simply `function F (val, index) { return index; }`\n3. `Array.from(A, F)` returns an `N`-element array, whose index `I` gets the results of `F(A[I], I)`, which is simply `I`.\n4. Result: `[0, 1, ..., N-1]`.\n\n### One More Thing\n\nIf you actually want the sequence [1, 2, ..., N], **Solution 1** becomes:\n\n```js\nArray.apply(null, {length: N}).map(function(value, index){\n return index + 1;\n});\n```\n\nand **Solution 2**:\n\n```js\nArray.from(new Array(N),(val,index)=>index+1);\n```\n"},"2016-01-15-even-simpler-way-of-using-indexof-as-a-contains-clause.md":{"name":"2016-01-15-even-simpler-way-of-using-indexof-as-a-contains-clause.md","sha":"8e7a3456f57faaef6676dae3825df82a7c96256b","content":"---\nlayout: post\n\ntitle: Even simpler way of using `indexOf` as a contains clause\ntip-number: 15\ntip-username: jhogoforbroke\ntip-username-profile: https://twitter.com/jhogoforbroke\ntip-tldr: JavaScript by default does not have a contains method. And for checking existence of a substring in a string or an item in an array you may do this.\n\nredirect_from:\n - /en/even-simpler-way-of-using-indexof-as-a-contains-clause/\n\ncategories:\n - en\n - javascript\n---\n\nJavaScript by default does not have a contains method. And for checking existence of a substring in a string or an item in an array you may do this:\n\n```javascript\nvar someText = 'javascript rules';\nif (someText.indexOf('javascript') !== -1) {\n}\n\n// or\nif (someText.indexOf('javascript') >= 0) {\n}\n```\n\nBut let's look at these [Expressjs](https://github.com/strongloop/express) code snippets.\n\n[examples/mvc/lib/boot.js](https://github.com/strongloop/express/blob/2f8ac6726fa20ab5b4a05c112c886752868ac8ce/examples/mvc/lib/boot.js#L26)\n\n\n```javascript\nfor (var key in obj) {\n // \"reserved\" exports\n if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;\n```\n\n[lib/utils.js](https://github.com/strongloop/express/blob/2f8ac6726fa20ab5b4a05c112c886752868ac8ce/lib/utils.js#L93)\n\n\n```javascript\nexports.normalizeType = function(type){\n return ~type.indexOf('/')\n ? acceptParams(type)\n : { value: mime.lookup(type), params: {} };\n};\n```\n\n[examples/web-service/index.js](https://github.com/strongloop/express/blob/2f8ac6726fa20ab5b4a05c112c886752868ac8ce/examples/web-service/index.js#L35)\n\n\n```javascript\n// key is invalid\nif (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'));\n```\n\nThe gotcha is the [bitwise operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) **~**, \"Bitwise operators perform their operations on binary representations, but they return standard JavaScript numerical values.\"\n\nIt transforms `-1` into `0`, and `0` evaluates to `false` in JavaScript:\n\n```javascript\nvar someText = 'text';\n!!~someText.indexOf('tex'); // someText contains \"tex\" - true\n!~someText.indexOf('tex'); // someText NOT contains \"tex\" - false\n~someText.indexOf('asd'); // someText doesn't contain \"asd\" - false\n~someText.indexOf('ext'); // someText contains \"ext\" - true\n```\n\n### String.prototype.includes()\n\nES6 introduced the [includes() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) and you can use it to determine whether or not a string includes another string:\n\n```javascript\n'something'.includes('thing'); // true\n```\n\nWith ECMAScript 2016 (ES7) it is even possible to use these techniques with Arrays:\n\n```javascript\n!!~[1, 2, 3].indexOf(1); // true\n[1, 2, 3].includes(1); // true\n```\n\n**Unfortunately, it is only supported in Chrome, Firefox, Safari 9 or above and Edge; not IE11 or lower.**\n**It's better used in controlled environments.**"},"2016-02-13-know-the-passing-mechanism.md":{"name":"2016-02-13-know-the-passing-mechanism.md","sha":"a92408a078452836124fe6f30b55d6eb3d59571c","content":"---\nlayout: post\n\ntitle: Know the passing mechanism\ntip-number: 44\ntip-username: bmkmanoj\ntip-username-profile: https://github.com/bmkmanoj\ntip-tldr: JavaScript technically only passes by value for both primitives and object (or reference) types. In case of reference types the reference value itself is passed by value.\n\nredirect_from:\n - /en/know-the-passing-mechanism/\n\ncategories:\n - en\n - javascript\n---\n\nJavaScript is pass-by-value, technically. It is neither pass-by-value nor pass-by-reference, going by the truest sense of these terms. To understand this passing mechanism, take a look at the following two example code snippets and the explanations.\n\n### Example 1\n\n```js\n\nvar me = {\t\t\t\t\t// 1\n\t'partOf' : 'A Team'\n}; \n\nfunction myTeam(me) {\t\t// 2\n\n\tme = {\t\t\t\t\t// 3\n\t\t'belongsTo' : 'A Group'\n\t}; \n} \t\n\nmyTeam(me);\t\t\nconsole.log(me);\t\t\t// 4 : {'partOf' : 'A Team'}\n\n```\n\nIn above example, when the `myTeam` gets invoked, JavaScript is *passing the reference to* `me` *object as value, as it is an object* and invocation itself creates two independent references to the same object, (though the name being same here i.e. `me`, is misleading and gives us an impression that it is the single reference) and hence, the reference variable themselves are independent.\n\nWhen we assigned a new object at #`3`, we are changing this reference value entirely within the `myTeam` function, and it will not have any impact on the original object outside this function scope, from where it was passed and the reference in the outside scope is going to retain the original object and hence the output from #`4`. \n\n\n### Example 2\n\n```js\n\nvar me = {\t\t\t\t\t// 1\n\t'partOf' : 'A Team'\n}; \n\nfunction myGroup(me) { \t\t// 2\n\tme.partOf = 'A Group'; // 3\n} \n\nmyGroup(me);\nconsole.log(me);\t\t\t// 4 : {'partOf' : 'A Group'}\n\t\n```\n\nIn the case of `myGroup` invocation, we are passing the object `me`. But unlike the example 1 scenario, we are not assigning this `me` variable to any new object, effectively meaning the object reference value within the `myGroup` function scope still is the original object's reference value and when we are modifying the property within this scope, it is effectively modifying the original object's property. Hence, you get the output from #`4`.\n\nSo does this later case not prove that javascript is pass-by-reference? No, it does not. Remember, *JavaScript passes the reference as value, in case of objects*. The confusion arises as we tend not to understand fully what pass by reference is. This is the exact reason, some prefer to call this as *call-by-sharing*.\n\n\n*Initially posted by the author on [js-by-examples](https://github.com/bmkmanoj/js-by-examples/blob/master/examples/js_pass_by_value_or_reference.md)*\n"},"2016-02-09-using-json-stringify.md":{"name":"2016-02-09-using-json-stringify.md","sha":"db72a505d0e870ab53b2aa898c4b1d0c9f5635e9","content":"---\nlayout: post\n\ntitle: Using JSON.Stringify\ntip-number: 40\ntip-username: vamshisuram\ntip-username-profile: https://github.com/vamshisuram\ntip-tldr: Create string from selected properties of JSON object.\n\n\nredirect_from:\n - /en/using-json-stringify/\n\ncategories:\n - en\n - javascript\n---\n\nLet's say there is an object with properties \"prop1\", \"prop2\", \"prop3\".\nWe can pass __additional params__ to __JSON.stringify__ to selectively write properties of the object to string like:\n\n```javascript\nvar obj = {\n 'prop1': 'value1',\n 'prop2': 'value2',\n 'prop3': 'value3'\n};\n\nvar selectedProperties = ['prop1', 'prop2'];\n\nvar str = JSON.stringify(obj, selectedProperties);\n\n// str\n// {\"prop1\":\"value1\",\"prop2\":\"value2\"}\n\n```\n\nThe __\"str\"__ will contain only info on selected properties only.\n\nInstead of array we can pass a function also.\n\n```javascript\n\nfunction selectedProperties(key, val) {\n // the first val will be the entire object, key is empty string\n if (!key) {\n return val;\n }\n\n if (key === 'prop1' || key === 'prop2') {\n return val;\n }\n\n return;\n}\n```\n\nThe last optional param it takes is to modify the way it writes the object to string.\n\n```javascript\nvar str = JSON.stringify(obj, selectedProperties, '\\t\\t');\n\n/* str output with double tabs in every line.\n{\n \"prop1\": \"value1\",\n \"prop2\": \"value2\"\n}\n*/\n\n```\n\n"},"2016-01-22-two-ways-to-empty-an-array.md":{"name":"2016-01-22-two-ways-to-empty-an-array.md","sha":"0060a1aaf34bd31e31a3b36893f2712bbe59f51a","content":"---\nlayout: post\n\ntitle: Two ways to empty an array\ntip-number: 22\ntip-username: microlv\ntip-username-profile: https://github.com/microlv\ntip-tldr: In JavaScript when you want to empty an array, there are a lot ways, but this is the most performant.\n\nredirect_from:\n - /en/two-ways-to-empty-an-array/\n\ncategories:\n - en\n - javascript\n---\n\nYou define an array and want to empty its contents.\nUsually, you would do it like this:\n\n```javascript\n// define Array\nvar list = [1, 2, 3, 4];\nfunction empty() {\n //empty your array\n list = [];\n}\nempty();\n```\nBut there is another way to empty an array that is more performant.\n\nYou should use code like this:\n\n```javascript\nvar list = [1, 2, 3, 4];\nfunction empty() {\n //empty your array\n list.length = 0;\n}\nempty();\n```\n\n* `list = []` assigns a reference to a new array to a variable, while any other references are unaffected.\nwhich means that references to the contents of the previous array are still kept in memory, leading to memory leaks.\n\n* `list.length = 0` deletes everything in the array, which does hit other references.\n\nIn other words, if you have two references to the same array (`a = [1,2,3]; a2 = a;`), and you delete the array's contents using `list.length = 0`, both references (a and a2) will now point to the same empty array. (So don't use this technique if you don't want a2 to hold an empty array!)\n\nThink about what this will output:\n\n```js\nvar foo = [1,2,3];\nvar bar = [1,2,3];\nvar foo2 = foo;\nvar bar2 = bar;\nfoo = [];\nbar.length = 0;\nconsole.log(foo, bar, foo2, bar2);\n\n// [] [] [1, 2, 3] []\n```\n\nStackoverflow more detail:\n[difference-between-array-length-0-and-array](http://stackoverflow.com/questions/4804235/difference-between-array-length-0-and-array)\n"},"2016-01-02-keys-in-children-components-are-important.md":{"name":"2016-01-02-keys-in-children-components-are-important.md","sha":"7671c5cbb75cac20fbd7473bd5085da9e5b0ad70","content":"---\nlayout: post\n\ntitle: Keys in children components are important\ntip-number: 02\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: The key is an attribute that you must pass to all components created dynamically from an array. It's a unique and constant id that React uses to identify each component in the DOM and to know whether it's a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/keys-in-children-components-are-important/\n\ncategories:\n - en\n - react\n---\n\nThe [key](https://facebook.github.io/react/docs/multiple-components.html#dynamic-children) is an attribute that you must pass to all components created dynamically from an array. It's a unique and constant id that React uses to identify each component in the DOM and to know whether it's a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.\n\n> Key is not really about performance, it's more about identity (which in turn leads to better performance). Randomly assigned and changing values do not form an identity [Paul O’Shannessy](https://github.com/facebook/react/issues/1342#issuecomment-39230939)\n\n- Use an existing unique value of the object.\n- Define the keys in the parent components, not in child components\n\n```javascript\n//bad\n...\nrender() {\n\t<div key={% raw %}{{item.key}}{% endraw %}>{% raw %}{{item.name}}{% endraw %}</div>\n}\n...\n\n//good\n<MyComponent key={% raw %}{{item.key}}{% endraw %}/>\n```\n- [Using array index is a bad practice.](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318#.76co046o9)\n- `random()` will not work\n\n```javascript\n//bad\n<MyComponent key={% raw %}{{Math.random()}}{% endraw %}/>\n```\n\n- You can create your own unique id. Be sure that the method is fast and attach it to your object.\n- When the number of children is large or contains expensive components, use keys to improve performance.\n- [You must provide the key attribute for all children of ReactCSSTransitionGroup.](http://docs.reactjs-china.com/react/docs/animation.html)"},"2016-01-27-short-circuit-evaluation-in-js.md":{"name":"2016-01-27-short-circuit-evaluation-in-js.md","sha":"723134a38ddd54f7c7ed2b1923d7590c40f79012","content":"---\nlayout: post\n\ntitle: Short circuit evaluation in JS.\ntip-number: 27\ntip-username: bhaskarmelkani\ntip-username-profile: https://www.twitter.com/bhaskarmelkani\ntip-tldr: Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression, when the first argument of the AND `&&` function evaluates to false, the overall value must be false, and when the first argument of the OR `||` function evaluates to true, the overall value must be true.\n\nredirect_from:\n - /en/short-circuit-evaluation-in-js/\n\ncategories:\n - en\n - javascript\n---\n\n[Short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND (`&&`) function evaluates to false, the overall value must be false; and when the first argument of the OR (`||`) function evaluates to true, the overall value must be true.\n\nFor the following `test` condition and `isTrue` and `isFalse` function.\n\n```js\nvar test = true;\nvar isTrue = function(){\n console.log('Test is true.');\n};\nvar isFalse = function(){\n console.log('Test is false.');\n};\n\n```\nUsing logical AND - `&&`.\n\n```js\n// A normal if statement.\nif(test){\n isTrue(); // Test is true\n}\n\n// Above can be done using '&&' as -\n\n( test && isTrue() ); // Test is true\n```\nUsing logical OR - `||`.\n\n```js\ntest = false;\nif(!test){\n isFalse(); // Test is false.\n}\n\n( test || isFalse()); // Test is false.\n```\nThe logical OR could also be used to set a default value for function argument.\n\n```js\nfunction theSameOldFoo(name){ \n name = name || 'Bar' ;\n console.log(\"My best friend's name is \" + name);\n}\ntheSameOldFoo(); // My best friend's name is Bar\ntheSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar\n```\nThe logical AND could be used to avoid exceptions when using properties of undefined.\nExample:\n\n```js\nvar dog = { \n bark: function(){\n console.log('Woof Woof');\n }\n};\n\n// Calling dog.bark();\ndog.bark(); // Woof Woof.\n\n// But if dog is not defined, dog.bark() will raise an error \"Cannot read property 'bark' of undefined.\"\n// To prevent this, we can use &&.\n\ndog&&dog.bark(); // This will only call dog.bark(), if dog is defined.\n\n```\n"},"2016-01-26-filtering-and-sorting-a-list-of-strings.md":{"name":"2016-01-26-filtering-and-sorting-a-list-of-strings.md","sha":"8287a2d4dea260af3b479636cb2e76439852deed","content":"---\nlayout: post\n\ntitle: Filtering and Sorting a List of Strings\ntip-number: 26\ntip-username: davegomez\ntip-username-profile: https://github.com/davegomez\ntip-tldr: You may have a big list of names you need to filter in order to remove duplicates and sort them alphabetically.\n\ncredirect_from:\n - /en/filtering-and-sorting-a-list-of-strings/\n\ncategories:\n - en\n - javascript\n---\n\nYou may have a big list of names you need to filter in order to remove duplicates and sort them alphabetically.\n\nIn our example we are going to use the list of **JavaScript reserved keywords** we can find across the different versions of the language, but as you can notice, there is a lot of duplicated keywords and they are not alphabetically organized. So this is a perfect list ([Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)) of strings to test out this JavaScript tip.\n\n```js\nvar keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];\n```\n\nSince we don't want to change our original list, we are going to use a high order function named [`filter`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), which will return a new filter array based in a predicate (*function*) we pass to it. The predicate will compare the index of the current keyword in the original list with its `index` in the new list and will push it to the new array only if the indexes match.\n\nFinally we are going to sort the filtered list using the [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) function which takes a comparison function as the only argument, returning a alphabetically sorted list.\n\n```js\nvar filteredAndSortedKeywords = keywords\n .filter(function (keyword, index) {\n return keywords.lastIndexOf(keyword) === index;\n })\n .sort(function (a, b) {\n return a < b ? -1 : 1;\n });\n```\n\nThe **ES6** (ECMAScript 2015) version using [arrow functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) looks a little simpler:\n\n```js\nconst filteredAndSortedKeywords = keywords\n .filter((keyword, index) => keywords.lastIndexOf(keyword) === index)\n .sort((a, b) => a < b ? -1 : 1);\n```\n\nAnd this is the final filtered and sorted list of JavaScript reserved keywords:\n\n```js\nconsole.log(filteredAndSortedKeywords);\n\n// ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']\n```\n\n*Thanks to [@nikshulipa](https://github.com/nikshulipa), [@kirilloid](https://twitter.com/kirilloid), [@lesterzone](https://twitter.com/lesterzone), [@tracker1](https://twitter.com/tracker1), [@manuel_del_pozo](https://twitter.com/manuel_del_pozo) for all the comments and suggestions!*\n"},"2016-02-14-calculate-the-max-min-value-from-an-array.md":{"name":"2016-02-14-calculate-the-max-min-value-from-an-array.md","sha":"8ad13e714d14287cc03e042a902060e00236716a","content":"---\nlayout: post\n\ntitle: Calculate the Max/Min value from an array\ntip-number: 45\ntip-username: loverajoel\ntip-username-profile: https://www.twitter.com/loverajoel\ntip-tldr: Ways to use the built-in functions Math.max() and Math.min() with arrays of numbers\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/calculate-the-max-min-value-from-an-array/\n\ncategories:\n - en\n - javascript\n---\n\nThe built-in functions [Math.max()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and [Math.min()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) find the maximum and minimum value of the arguments, respectively.\n\n```js\nMath.max(1, 2, 3, 4); // 4\nMath.min(1, 2, 3, 4); // 1\n```\n\nThese functions will not work as-is with arrays of numbers. However, there are some ways around this.\n\n[`Function.prototype.apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) allows you to call a function with a given `this` value and an _array_ of arguments.\n\n```js\nvar numbers = [1, 2, 3, 4];\nMath.max.apply(null, numbers) // 4\nMath.min.apply(null, numbers) // 1\n```\n\nPassing the `numbers` array as the second argument of `apply()` results in the function being called with all values in the array as parameters.\n\nA simpler, ES2015 way of accomplishing this is with the new [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).\n\n```js\nvar numbers = [1, 2, 3, 4];\nMath.max(...numbers) // 4\nMath.min(...numbers) // 1\n```\n\nThis operator causes the values in the array to be expanded, or \"spread\", into the function's arguments.\n"},"2016-01-05-differences-between-undefined-and-null.md":{"name":"2016-01-05-differences-between-undefined-and-null.md","sha":"2e32c5625d3dd3c37375b94a48a8882d6be3fc2c","content":"---\nlayout: post\n\ntitle: Differences between `undefined` and `null`\ntip-number: 05\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Understanding the differences between `undefined` and `null`.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/differences-between-undefined-and-null/\n\ncategories:\n - en\n - javascript\n---\n\n- `undefined` means a variable has not been declared, or has been declared but has not yet been assigned a value\n- `null` is an assignment value that means \"no value\"\n- Javascript sets unassigned variables with a default value of `undefined`\n- Javascript never sets a value to `null`. It is used by programmers to indicate that a `var` has no value.\n- `undefined` is not valid in JSON while `null` is\n- `undefined` typeof is `undefined`\n- `null` typeof is an `object`. [Why?](http://www.2ality.com/2013/10/typeof-null.html)\n- Both are primitives\n- Both are [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)\n (`Boolean(undefined) // false`, `Boolean(null) // false`)\n- You can know if a variable is [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)\n\n ```javascript\n typeof variable === \"undefined\"\n```\n- You can check if a variable is [null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null)\n\n ```javascript\n variable === null\n```\n- The **equality** operator considers them equal, but the **identity** doesn't\n\n ```javascript\n null == undefined // true\n\n null === undefined // false\n```"},"2016-02-15-detect-document-ready-in-pure-js.md":{"name":"2016-02-15-detect-document-ready-in-pure-js.md","sha":"062a482e8caf566bc3083119faa1a36e19096948","content":"---\nlayout: post\n\ntitle: Detect document ready in pure JS\ntip-number: 46\ntip-username: loverajoel\ntip-username-profile: https://www.twitter.com/loverajoel\ntip-tldr: The cross-browser way to check if the document has loaded in pure JavaScript\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/detect-document-ready-in-pure-js/\n\ncategories:\n - en\n - javascript\n---\n\nThe cross-browser way to check if the document has loaded in pure JavaScript is using [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState).\n\n```js\nif (document.readyState === 'complete') {\n // The page is fully loaded\n}\n```\n\nYou can detect when the document is ready...\n\n\n```js\nlet stateCheck = setInterval(() => {\n if (document.readyState === 'complete') {\n clearInterval(stateCheck);\n // document ready\n }\n}, 100);\n```\n\nor with [onreadystatechange](https://developer.mozilla.org/en-US/docs/Web/Events/readystatechange)...\n\n\n```js\ndocument.onreadystatechange = () => {\n if (document.readyState === 'complete') {\n // document ready\n }\n};\n```\n\nUse `document.readyState === 'interactive'` to detect when the DOM is ready.\n"},"2016-02-05-observe-dom-changes.md":{"name":"2016-02-05-observe-dom-changes.md","sha":"0f61072f638b5ee20e58edb4bf497ed2b08546fa","content":"---\nlayout: post\n\ntitle: Observe DOM changes in extensions\ntip-number: 36\ntip-username: beyondns\ntip-username-profile: https://github.com/beyondns\ntip-tldr: When you develop extensions to existent sites it's not so easy to play with DOM 'cause of modern dynamic javascript.\n\n\nredirect_from:\n - /en/observe-dom-changes/\n\ncategories:\n - en\n - javascript\n---\n[MutationObserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) is a solution to listen DOM changes and do what you want to do with elements when they changed. In following example there is some emulation of dynamic content loading with help of timers, after first \"target\" element creation goes \"subTarget\".\nIn extension code firstly rootObserver works till targetElement appearance then elementObserver starts. This cascading observing helps finally get moment when subTargetElement found.\nThis useful to develop extensions to complex sites with dynamic content loading.\n\n```js\nconst observeConfig = {\n attributes: true,\n childList: true,\n characterData: true,\n subtree: true\n};\n\nfunction initExtension(rootElement, targetSelector, subTargetSelector) {\n var rootObserver = new MutationObserver(function(mutations) {\n console.log(\"Inside root observer\");\n targetElement = rootElement.querySelector(targetSelector);\n if (targetElement) {\n rootObserver.disconnect();\n var elementObserver = new MutationObserver(function(mutations) {\n console.log(\"Inside element observer\");\n subTargetElement = targetElement.querySelector(subTargetSelector);\n if (subTargetElement) {\n elementObserver.disconnect();\n console.log(\"subTargetElement found!\");\n }\n });\n elementObserver.observe(targetElement, observeConfig);\n }\n });\n rootObserver.observe(rootElement, observeConfig);\n}\n\n(function() {\n\n initExtension(document.body, \"div.target\", \"div.subtarget\");\n\n setTimeout(function() {\n del = document.createElement(\"div\");\n del.innerHTML = \"<div class='target'>target</div>\";\n document.body.appendChild(del);\n }, 3000);\n\n\n setTimeout(function() {\n var el = document.body.querySelector('div.target');\n if (el) {\n del = document.createElement(\"div\");\n del.innerHTML = \"<div class='subtarget'>subtarget</div>\";\n el.appendChild(del);\n }\n }, 5000);\n\n})();\n```\n\n"},"2016-02-11-preventing-unapply-attacks.md":{"name":"2016-02-11-preventing-unapply-attacks.md","sha":"131d4f37c31286a21df129e9db852709886a0918","content":"---\nlayout: post\n\ntitle: Preventing Unapply Attacks\ntip-number: 42\ntip-username: emars \ntip-username-profile: https://twitter.com/marseltov\ntip-tldr: Freeze the builtin prototypes.\n\nredirect_from:\n - /en/preventing-unapply-attacks/\n\ncategories:\n - en\n - javascript\n---\n\nBy overriding the builtin prototypes, external code can cause code to break by rewriting code to expose and change bound arguments. This can be an issue that seriously breaks applications that works by using polyfill es5 methods.\n\n```js\n// example bind polyfill\nfunction bind(fn) {\n var prev = Array.prototype.slice.call(arguments, 1);\n return function bound() {\n var curr = Array.prototype.slice.call(arguments, 0);\n var args = Array.prototype.concat.apply(prev, curr);\n return fn.apply(null, args);\n };\n}\n\n\n// unapply-attack\nfunction unapplyAttack() {\n var concat = Array.prototype.concat;\n Array.prototype.concat = function replaceAll() {\n Array.prototype.concat = concat; // restore the correct version\n var curr = Array.prototype.slice.call(arguments, 0);\n var result = concat.apply([], curr);\n return result;\n };\n}\n```\n\nThe above function discards the `prev` array from the bind meaning that any `.concat` the first concat call following using the unapply attack will throw an error.\n\nBy using [Object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), making an object immutable, you prevent any overriding of the builtin object prototypes. \n\n\n```js\n(function freezePrototypes() {\n if (typeof Object.freeze !== 'function') {\n throw new Error('Missing Object.freeze');\n }\n Object.freeze(Object.prototype);\n Object.freeze(Array.prototype);\n Object.freeze(Function.prototype);\n}());\n```\n\nYou can read more about unapply attacks [here](https://glebbahmutov.com/blog/unapply-attack/).\nAlthough this concept is called an 'unapply attack' due to some code being able to access closures that normally wouldn't be in scope, it is mostly wrong to consider this a security feature due to it not preventing an attacker with code execution from extending prototypes before the freezing happens and also still having the potential to read all scopes using various language features. ECMA modules would give realm based isolation which is much stronger than this solution however still doesn't fix the issues of third party scripts.\n"},"2016-01-07-use-strict-and-get-lazy.md":{"name":"2016-01-07-use-strict-and-get-lazy.md","sha":"8b4622d7c0e98361066cdb12d47616debfe26a05","content":"---\nlayout: post\n\ntitle: use strict and get lazy\ntip-number: 07\ntip-username: nainslie\ntip-username-profile: https://twitter.com/nat5an\ntip-tldr: Strict-mode JavaScript makes it easier for the developer to write \"secure\" JavaScript.\n\nredirect_from:\n - /en/use-strict-and-get-lazy/\n\ncategories:\n - en\n - javascript\n---\n\nStrict-mode JavaScript makes it easier for the developer to write \"secure\" JavaScript.\n\nBy default, JavaScript allows the programmer to be pretty careless, for example, by not requiring us to declare our variables with \"var\" when we first introduce them. While this may seem like a convenience to the unseasoned developer, it's also the source of many errors when a variable name is misspelled or accidentally referred to out of its scope.\n\nProgrammers like to make the computer do the boring stuff for us, and automatically check our work for mistakes. That's what the JavaScript \"use strict\" directive allows us to do, by turning our mistakes into JavaScript errors.\n\nWe add this directive either by adding it at the top of a js file:\n\n```javascript\n// Whole-script strict mode syntax\n\"use strict\";\nvar v = \"Hi! I'm a strict mode script!\";\n```\n\nor inside a function:\n\n```javascript\nfunction f()\n{\n // Function-level strict mode syntax\n 'use strict';\n function nested() { return \"And so am I!\"; }\n return \"Hi! I'm a strict mode function! \" + nested();\n}\nfunction f2() { return \"I'm not strict.\"; }\n```\n\nBy including this directive in a JavaScript file or function, we will direct the JavaScript engine to execute in strict mode which disables a bunch of behaviors that are usually undesirable in larger JavaScript projects. Among other things, strict mode changes the following behaviors:\n\n* Variables can only be introduced when they are preceded with \"var\"\n* Attempting to write to read-only properties generates a noisy error\n* You have to call constructors with the \"new\" keyword\n* \"this\" is not implicitly bound to the global object\n* Very limited use of eval() allowed\n* Protects you from using reserved words or future reserved words as variable names\n\nStrict mode is great for new projects, but can be challenging to introduce into older projects that don't already use it in most places. It also can be problematic if your build chain concatenates all your js files into one big file, as this may cause all files to execute in strict mode.\n\nIt is not a statement, but a literal expression, ignored by earlier versions of JavaScript.\nStrict mode is supported in:\n\n* Internet Explorer from version 10.\n* Firefox from version 4.\n* Chrome from version 13.\n* Safari from version 5.1.\n* Opera from version 12.\n\n[See MDN for a fuller description of strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)."},"2016-01-01-angularjs-digest-vs-apply.md":{"name":"2016-01-01-angularjs-digest-vs-apply.md","sha":"79e9e72a02505877125742e6799d5dd24943a640","content":"---\nlayout: post\n\ntitle: AngularJs - `$digest` vs `$apply`\ntip-number: 01\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: JavaScript modules and build steps are getting more numerous and complicated, but what about boilerplate in new frameworks?\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/angularjs-digest-vs-apply/\n\ncategories:\n - en\n - angular\n---\n\nOne of the most appreciated features of AngularJs is the two-way data binding. In order to make this work AngularJs evaluates the changes between the model and the view through cycles(`$digest`). You need to understand this concept in order to understand how the framework works under the hood.\n\nAngular evaluates each watcher whenever one event is fired. This is the known `$digest` cycle.\nSometimes you have to force it to run a new cycle manually and you must choose the correct option because this phase is one of the most influential in terms of performance.\n\n### `$apply`\nThis core method lets you to start the digestion cycle explicitly. That means that all watchers are checked; the entire application starts the `$digest loop`. Internally, after executing an optional function parameter, it calls `$rootScope.$digest();`.\n\n### `$digest`\nIn this case the `$digest` method starts the `$digest` cycle for the current scope and its children. You should notice that the parent's scopes will not be checked.\n and not be affected.\n\n### Recommendations\n- Use `$apply` or `$digest` only when browser DOM events have triggered outside of AngularJS.\n- Pass a function expression to `$apply`, this has an error handling mechanism and allows integrating changes in the digest cycle.\n\n```javascript\n$scope.$apply(() => {\n\t$scope.tip = 'Javascript Tip';\n});\n```\n\n- If you only need to update the current scope or its children, use `$digest`, and prevent a new digest cycle for the whole application. The performance benefit is self-evident.\n- `$apply()` is a hard process for the machine and can lead to performance issues when there is a lot of binding.\n- If you are using >AngularJS 1.2.X, use `$evalAsync`, which is a core method that will evaluate the expression during the current cycle or the next. This can improve your application's performance"},"2016-02-07-flattening-multidimensional-arrays-in-javascript.md":{"name":"2016-02-07-flattening-multidimensional-arrays-in-javascript.md","sha":"514f400334572d36c314d2294eb6935dd0c111f1","content":"---\nlayout: post\n\ntitle: Flattening multidimensional Arrays in JavaScript\ntip-number: 38\ntip-username: loverajoel\ntip-username-profile: https://www.twitter.com/loverajoel\ntip-tldr: Three different solutions to merge multidimensional array into a single array.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\n\nredirect_from:\n - /en/flattening-multidimensional-arrays-in-javascript/\n\ncategories:\n - en\n - javascript\n---\n\nThese are the three known ways to merge multidimensional array into a single array.\n\nGiven this array:\n\n```js\nvar myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]];\n```\n\nWe wanna have this result:\n\n```js\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\n### Solution 1: Using [`concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) and [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)\n\n```js\nvar myNewArray = [].concat.apply([], myArray);\n// [1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\n### Solution 2: Using [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Flatten_an_array_of_arrays)\n\n```js\nvar myNewArray = myArray.reduce(function(prev, curr) {\n return prev.concat(curr);\n});\n// [1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\n### Solution 3:\n\n```js\nvar myNewArray3 = [];\nfor (var i = 0; i < myArray.length; ++i) {\n for (var j = 0; j < myArray[i].length; ++j)\n myNewArray3.push(myArray[i][j]);\n}\nconsole.log(myNewArray3);\n// [1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\n### Solution 4: Using [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) in ES6\n\n```js\nvar myNewArray4 = [].concat(...myArray);\nconsole.log(myNewArray4);\n// [1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\nTake a look [here](https://jsbin.com/janana/edit?js,console) these 4 algorithms in action.\n\nFor infinitely nested array try Lodash [flattenDeep()](https://lodash.com/docs#flattenDeep).\n\nIf you are curious about performance, [here](http://jsperf.com/flatten-an-array-loop-vs-reduce/6) a test for check how it works.\n"},"2016-02-10-array-average-and-median.md":{"name":"2016-02-10-array-average-and-median.md","sha":"ce99bbaea9efed95cd91877685428adf9cdcd02f","content":"---\nlayout: post\n\ntitle: Array average and median\ntip-number: 41\ntip-username: soyuka\ntip-username-profile: https://github.com/soyuka\ntip-tldr: Calculate the average and median from array values\n\n\nredirect_from:\n - /en/array-average-and-median/\n\ncategories:\n - en\n - javascript\n---\n\nThe following examples will be based on the following array:\n\n```javascript\nlet values = [2, 56, 3, 41, 0, 4, 100, 23];\n```\n\nTo get the average, we have to sum up numbers and then divide by the number of values. Steps are:\n- get the array length\n- sum up values\n- get the average (`sum/length`)\n\n```javascript\nlet values = [2, 56, 3, 41, 0, 4, 100, 23];\nlet sum = values.reduce((previous, current) => current += previous);\nlet avg = sum / values.length;\n// avg = 28\n```\n\nOr:\n\n```javascript\nlet values = [2, 56, 3, 41, 0, 4, 100, 23];\nlet count = values.length;\nvalues = values.reduce((previous, current) => current += previous);\nvalues /= count;\n// avg = 28\n```\n\nNow, to get the median steps are:\n- sort the array\n- get the arethmic mean of the middle values\n\n```javascript\nlet values = [2, 56, 3, 41, 0, 4, 100, 23];\nvalues.sort((a, b) => a - b);\nlet lowMiddle = Math.floor((values.length - 1) / 2);\nlet highMiddle = Math.ceil((values.length - 1) / 2);\nlet median = (values[lowMiddle] + values[highMiddle]) / 2;\n// median = 13,5\n```\n\nWith a bitwise operator:\n\n```javascript\nlet values = [2, 56, 3, 41, 0, 4, 100, 23];\nvalues.sort((a, b) => a - b);\nlet median = (values[(values.length - 1) >> 1] + values[values.length >> 1]) / 2\n// median = 13,5\n```\n"},"2016-01-18-rounding-the-fast-way.md":{"name":"2016-01-18-rounding-the-fast-way.md","sha":"3ea755ecfa4371883a61d8625b59b0079d09c1a6","content":"---\nlayout: post\n\ntitle: Truncating the fast (but risky) way\ntip-number: 18\ntip-username: pklinger\ntip-username-profile: https://github.com/pklinger\ntip-tldr: .`~~X` is usually a faster `Math.trunc(X)`, but can also make your code do nasty things.\n\nredirect_from:\n - /en/rounding-the-fast-way/\n\ncategories:\n - en\n - javascript\n---\n\nThis tip is about performance...with a hidden price tag.\n\nHave you ever come across the [double tilde `~~` operator](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript)? It's also often called the \"double bitwise NOT\" operator. You can often use it as a faster substitute for `Math.trunc()`. Why is that?\n\nOne bitwise shift `~` first truncates `input` to 32 bits, then transforms it into `-(input+1)`. The double bitwise shift therefore transforms the input into `-(-(input + 1)+1)` making it a great tool to round towards zero. For numeric input, it therefore mimics `Math.trunc()`. On failure, `0` is returned, which might come in handy sometimes instead of `Math.trunc()`, which returns `NaN` on failure.\n\n```js\n// single ~\nconsole.log(~1337) // -1338\n\n// numeric input\nconsole.log(~~47.11) // -> 47\nconsole.log(~~1.9999) // -> 1\nconsole.log(~~3) // -> 3\n```\n\nHowever, while `~~` is probably a better performer, experienced programmers often stick with `Math.trunc()` instead. To understand why, here's a clinical view on this operator.\n\n### INDICATIONS\n\n##### When every CPU cycle counts\n`~~` is probably faster than `Math.trunc()` across the board, though you should [test that assumption](https://jsperf.com/jsfvsbitnot/10) on whichever platforms matter to you. Also, you'd generally have to perform millions of such operations to have any visible impact at run time.\n\n##### When code clarity is not a concern\nIf you're trying to confuse others, or get maximum utility from your minifier/uglifier, this is a relatively cheap way to do it.\n\n### CONTRAINDICATIONS\n\n##### When your code needs to be maintained\nCode clarity is of great importance in the long term, whether you work in a team, contribute to public code repos, or fly solo. As [the oft-quoted saying](http://c2.com/cgi/wiki?CodeForTheMaintainer) goes:\n> Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.\n\nFor a solo programmer, that psychopath is inevitably \"you in six months\".\n\n##### When you forget that `~~` always rounds to zero\nNewbie programmers may fixate on the cleverness of `~~`, forgetting the significance of \"just drop the fractional portion of this number\". This can easily lead to **fencepost errors** (a.k.a. \"off-by-one\") when transforming floats to array indices or related ordinal values, where a different kind of fractional rounding may actually be called for. (Lack of code clarity usually contributes to this problem.)\n\nFor instance, if you're counting numbers on a \"nearest integer\" basis, you should use `Math.round()` instead of `~~`, but programmer laziness and the impact of **_10 whole characters saved per use_** on human fingers often triumph over cold logic, leading to incorrect results.\n\nIn contrast, the very names of the `Math.xyz()` functions clearly communicate their effect, reducing the probability of accidental errors.\n\n##### When dealing with large-magnitude numbers\nBecause `~` first does a 32-bit conversion, `~~` results in bogus values around ±2.15 billion. If you don't properly range-check your input, a user could trigger unexpected behavior when the transformed value ends up being a great distance from the original:\n\n```js\na = 2147483647.123 // maximum positive 32-bit integer, plus a bit more\nconsole.log(~~a) // -> 2147483647 (ok)\na += 10000 // -> 2147493647.123 (ok)\nconsole.log(~~a) // -> -2147483648 (huh?)\n```\nOne particularly vulnerable area involves dealing with Unix epoch timestamps (measured in seconds from 1 Jan 1970 00:00:00 UTC). A quick way to get such values is:\n\n```js\nepoch_int = ~~(+new Date() / 1000) // Date() epochs in milliseconds, so we scale accordingly\n```\nHowever, when dealing with timestamps after 19 Jan 2038 03:14:07 UTC (sometimes called the **Y2038 limit**), this breaks horribly:\n\n```js\n// epoch timestamp for 1 Jan 2040 00:00:00.123 UTC\nepoch = +new Date('2040-01-01') / 1000 + 0.123 // -> 2208988800.123\n\n// back to the future!\nepoch_int = ~~epoch // -> -2085978496\nconsole.log(new Date(epoch_int * 1000)) // -> Wed Nov 25 1903 17:31:44 UTC\n\n// that was fun, now let's get real\nepoch_flr = Math.floor(epoch) // -> 2208988800\nconsole.log(new Date(epoch_flr * 1000)) // -> Sun Jan 01 2040 00:00:00 UTC\n```\n\n##### When the original input wasn't sanitized\nBecause `~~` transforms every non-number into `0`:\n\n```js\nconsole.log(~~[]) // -> 0\nconsole.log(~~NaN) // -> 0\nconsole.log(~~null) // -> 0\n```\nsome programmers treat it as alternative to proper input validation. However, this can lead to strange logic bugs down the line, since you're no longer distinguishing between invalid inputs and actual `0` values. This is therefore _not_ a recommended practice.\n\n##### When so many people think `~~X == Math.floor(X)`\nMost people who write about \"double bitwise NOT\" incorrectly equate it with `Math.floor()` for some reason. If you can't write about it accurately, odds are good you'll eventually misuse it.\n\nOthers are more careful to mention `Math.floor()` for positive inputs and `Math.ceil()` for negative ones, but that forces you to stop and think about the values you're dealing with. This defeats the purpose of `~~` as a handy no-gotchas shortcut.\n\n### DOSAGE\nAvoid where possible. Use sparingly otherwise.\n\n### ADMINISTRATION\n1. Apply cautiously.\n2. Sanitize values before applying.\n3. Carefully document relevant assumptions about the values being transformed.\n4. Review code to deal with, at minimum:\n * logic bugs where invalid inputs are instead passed to other code modules as valid `0` values\n * range errors on transformed inputs\n * fencepost errors due to incorrect rounding direction\n"},"2016-01-08-converting-a-node-list-to-an-array.md":{"name":"2016-01-08-converting-a-node-list-to-an-array.md","sha":"6b7d74aaae2e477ae70a5b024d818cb30767c1a5","content":"---\nlayout: post\n\ntitle: Converting a Node List to an Array\ntip-number: 08\ntip-username: Tevko\ntip-username-profile: https://twitter.com/tevko\ntip-tldr: Here's a quick, safe, and reusable way to convert a node list into an array of DOM elements.\n\nredirect_from:\n - /en/converting-a-node-list-to-an-array/\n\ncategories:\n - en\n - javascript\n---\n\nThe `querySelectorAll` method returns an array-like object called a node list. These data structures are referred to as \"Array-like\", because they appear as an array, but can not be used with array methods like `map` and `forEach`. Here's a quick, safe, and reusable way to convert a node list into an array of DOM elements:\n\n```javascript\nconst nodelist = document.querySelectorAll('div');\nconst nodelistToArray = Array.apply(null, nodelist);\n\n//later on ..\n\nnodelistToArray.forEach(...);\nnodelistToArray.map(...);\nnodelistToArray.slice(...);\n\n//etc...\n```\n\nThe `apply` method is used to pass an array of arguments to a function with a given `this` value. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) states that `apply` will take an array-like object, which is exactly what `querySelectorAll` returns. Since we don't need to specify a value for `this` in the context of the function, we pass in `null` or `0`. The result is an actual array of DOM elements which contains all of the available array methods.\n\nAlternatively you can use `Array.prototype.slice` combined with `Function.prototype.call` or `Function.prototype.apply` passing the array-like object as the value of `this`:\n\n```javascript\nconst nodelist = document.querySelectorAll('div');\nconst nodelistToArray = Array.prototype.slice.call(nodelist); // or equivalently Array.prototype.slice.apply(nodelist);\n\n//later on ..\n\nnodelistToArray.forEach(...);\nnodelistToArray.map(...);\nnodelistToArray.slice(...);\n\n//etc...\n```\n\nOr if you are using ES2015 you can use the [spread operator `...`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)\n\n```js\nconst nodelist = [...document.querySelectorAll('div')]; // returns a real array\n\n//later on ..\n\nnodelist.forEach(...);\nnodelist.map(...);\nnodelist.slice(...);\n\n//etc...\n```\n"},"2016-02-03-implementing-asynchronous-loops.md":{"name":"2016-02-03-implementing-asynchronous-loops.md","sha":"d0c2fc34d4df0903a8d1ed3a55806668b2309e95","content":"---\nlayout: post\n\ntitle: Implementing asynchronous loop\ntip-number: 34\ntip-username: madmantalking\ntip-username-profile: https://github.com/madmantalking\ntip-tldr: You may run into problems while implementing asynchronous loops. \n\nredirect_from:\n - /en/implementing-asynchronous-loops/\n\ncategories:\n - en\n - javascript\n---\n\nLet's try out writing an asynchronous function which prints the value of the loop index every second.\n\n```js\nfor (var i=0; i<5; i++) {\n\tsetTimeout(function(){\n\t\tconsole.log(i); \n\t}, 1000 * (i+1));\n} \n```\nThe output of the above programs turns out to be\n\n```js\n> 5\n> 5\n> 5\n> 5\n> 5\n```\nSo this definitely doesn't work.\n\n**Reason**\n\nEach timeout refers to the original `i`, not a copy. So the for loop increments `i` until it gets to 5, then the timeouts run and use the current value of `i` (which is 5).\n\nWell , this problem seems easy. An immediate solution that strikes is to cache the loop index in a temporary variable.\n\n```js\nfor (var i=0; i<5; i++) {\n\tvar temp = i;\n \tsetTimeout(function(){\n\t\tconsole.log(temp); \n\t}, 1000 * (i+1));\n} \n```\nBut again the output of the above programs turns out to be\n\n```js\n> 4\n> 4\n> 4\n> 4\n> 4\n```\n\nSo , that doesn't work either , because blocks don't create a scope and variables initializers are hoisted to the top of the scope. In fact, the previous block is the same as:\n\n```js\nvar temp;\nfor (var i=0; i<5; i++) {\n \ttemp = i;\n\tsetTimeout(function(){\n\t\tconsole.log(temp); \n \t}, 1000 * (i+1));\n} \n```\n**Solution**\n\nThere are a few different ways to copy `i`. The most common way is creating a closure by declaring a function and passing `i` as an argument. Here we do this as a self-calling function.\n\n```js\nfor (var i=0; i<5; i++) {\n\t(function(num){\n\t\tsetTimeout(function(){\n\t\t\tconsole.log(num); \n\t\t}, 1000 * (i+1)); \n\t})(i); \n} \n```\nIn JavaScript, arguments are passed by value to a function. So primitive types like numbers, dates, and strings are basically copied. If you change them inside the function, it does not affect the outside scope. Objects are special: if the inside function changes a property, the change is reflected in all scopes.\n\nAnother approach for this would be with using `let`. With ES6 the `let` keyword is useful since it's block scoped unlike `var`\n\n```js\nfor (let i=0; i<5; i++) {\n \tsetTimeout(function(){\n\t\tconsole.log(i); \n\t}, 1000 * (i+1));\n} \n```\n"},"2016-01-24-use_===_instead_of_==.md":{"name":"2016-01-24-use_===_instead_of_==.md","sha":"39dfef88a2dfc3467680b8a00faed5502625cb74","content":"---\nlayout: post\n\ntitle: Use === instead of ==\ntip-number: 24\ntip-username: bhaskarmelkani\ntip-username-profile: https://www.twitter.com/bhaskarmelkani\ntip-tldr: The `==` (or `!=`) operator performs an automatic type conversion if needed. The `===` (or `!==`) operator will not perform any conversion. It compares the value and the type, which could be considered faster ([jsPref](http://jsperf.com/strictcompare)) than `==`.\n\nredirect_from:\n - /en/use_===_instead_of_==/\n\ncategories:\n - en\n - javascript\n---\n\nThe `==` (or `!=`) operator performs an automatic type conversion if needed. The `===` (or `!==`) operator will not perform any conversion. It compares the value and the type, which could be considered faster ([jsPref](http://jsperf.com/strictcompare)) than `==`.\n\n```js\n[10] == 10 // is true\n[10] === 10 // is false\n\n'10' == 10 // is true\n'10' === 10 // is false\n\n [] == 0 // is true\n [] === 0 // is false\n\n '' == false // is true but true == \"a\" is false\n '' === false // is false \n\n```\n"},"2016-01-17-nodejs-run-a-module-if-it-is-not-required.md":{"name":"2016-01-17-nodejs-run-a-module-if-it-is-not-required.md","sha":"5641b9482d3447487f0b073237747caec8e3cf63","content":"---\nlayout: post\n\ntitle: Node.js - Run a module if it is not `required`\ntip-number: 17\ntip-username: odsdq\ntip-username-profile: https://twitter.com/odsdq\ntip-tldr: In node, you can tell your program to do two different things depending on whether the code is run from `require('./something.js')` or `node something.js`. This is useful if you want to interact with one of your modules independently.\n\nredirect_from:\n - /en/nodejs-run-a-module-if-it-is-not-required/\n\ncategories:\n - en\n - javascript\n---\n\nIn node, you can tell your program to do two different things depending on whether the code is run from `require('./something.js')` or `node something.js`. This is useful if you want to interact with one of your modules independently.\n\n```js\nif (!module.parent) {\n // ran with `node something.js`\n app.listen(8088, function() {\n console.log('app listening on port 8088');\n })\n} else {\n // used with `require('/.something.js')`\n module.exports = app;\n}\n```\n\nSee [the documentation for modules](https://nodejs.org/api/modules.html#modules_module_parent) for more info."},"2016-01-29-speed-up-recursive-functions-with-memoization.md":{"name":"2016-01-29-speed-up-recursive-functions-with-memoization.md","sha":"9213872415ffd06bb972efe1afb72472f5b4abd4","content":"---\nlayout: post\n\ntitle: Speed up recursive functions with memoization\ntip-number: 29\ntip-username: hingsir\ntip-username-profile: https://github.com/hingsir\ntip-tldr: Fibonacci sequence is very familiar to everybody. we can write the following function in 20 seconds.it works, but not efficient. it did lots of duplicate computing works, we can cache its previously computed results to speed it up.\n\n\nredirect_from:\n - /en/speed-up-recursive-functions-with-memoization/\n\ncategories:\n - en\n - javascript\n---\n\nFibonacci sequence is very familiar to everybody. We can write the following function in 20 seconds.\n\n```js\nvar fibonacci = function(n) {\n return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n}\n```\n\nIt works, but is not efficient. It did lots of duplicate computing works, we can cache its previously computed results to speed it up.\n\n```js\nvar fibonacci = (function() {\n var cache = [0, 1]; // cache the value at the n index\n return function(n) {\n if (cache[n] === undefined) {\n for (var i = cache.length; i <= n; ++i) {\n cache[i] = cache[i - 1] + cache[i - 2];\n }\n }\n return cache[n];\n }\n})();\n```\n\nAlso, we can define a higher-order function that accepts a function as its argument and returns a memoized version of the function.\n\n```js\nvar memoize = function(func) {\n var cache = {};\n return function() {\n var key = JSON.stringify(Array.prototype.slice.call(arguments));\n return key in cache ? cache[key] : (cache[key] = func.apply(this, arguments));\n }\n}\nfibonacci = memoize(fibonacci);\n```\n\nAnd this is an ES6 version of the memoize function.\n\n```js\nvar memoize = function(func) {\n const cache = {};\n return (...args) => {\n const key = JSON.stringify(args);\n return key in cache ? cache[key] : (cache[key] = func(...args));\n }\n}\nfibonacci = memoize(fibonacci);\n```\n\nwe can use `memoize()` in many other situations\n\n* GCD(Greatest Common Divisor)\n\n```js\nvar gcd = memoize(function(a, b) {\n var t;\n if (a < b) t = b, b = a, a = t;\n while (b != 0) t = b, b = a % b, a = t;\n return a;\n});\ngcd(27, 183); //=> 3\n```\n\n* Factorial calculation\n\n```js\nvar factorial = memoize(function(n) {\n return (n <= 1) ? 1 : n * factorial(n - 1);\n})\nfactorial(5); //=> 120\n```\n\nLearn more about memoization:\n\n- [Memoization - Wikipedia](https://en.wikipedia.org/wiki/Memoization)\n- [Implementing Memoization in JavaScript](https://www.sitepoint.com/implementing-memoization-in-javascript/)\n"},"2016-02-06-deduplicate-an-array.md":{"name":"2016-02-06-deduplicate-an-array.md","sha":"9f0d3da772b3d7fc26ef60393fc4a4fd8c84d598","content":"---\nlayout: post\n\ntitle: Deduplicate an Array\ntip-number: 37\ntip-username: danillouz\ntip-username-profile: https://www.twitter.com/danillouz\ntip-tldr: How to remove duplicate elements, of different data types, from an Array.\n\n\nredirect_from:\n - /en/deduplicate-an-array/\n\ncategories:\n - en\n - javascript\n---\n\n# Primitives\nIf an Array only contains primitive values, we can deduplicate it by\nonly using the [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) methods.\n\n```javascript\nvar deduped = [ 1, 1, 'a', 'a' ].filter(function (el, i, arr) {\n\treturn arr.indexOf(el) === i;\n});\n\nconsole.log(deduped); // [ 1, 'a' ]\n```\n\n## ES2015\nWe can write this in a more compact way using an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\n\n```javascript\nvar deduped = [ 1, 1, 'a', 'a' ].filter( (el, i, arr) => arr.indexOf(el) === i);\n\nconsole.log(deduped); // [ 1, 'a' ]\n```\n\nBut with the introduction of [Sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and the [`from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method, we can achieve the same\nresult in a more concise way.\n\n```javascript\nvar deduped = Array.from( new Set([ 1, 1, 'a', 'a' ]) );\n\nconsole.log(deduped); // [ 1, 'a' ]\n```\n\n# Objects\nWe can't use the same approach when the elements are Objects,\nbecause Objects are stored by reference and primitives are stored\nby value.\n\n```javascript\n1 === 1 // true\n\n'a' === 'a' // true\n\n{ a: 1 } === { a: 1 } // false\n```\n\nTherefore we need to change our approach and use a hash table.\n\n```javascript\nfunction dedup(arr) {\n\tvar hashTable = {};\n\n\treturn arr.filter(function (el) {\n\t\tvar key = JSON.stringify(el);\n\t\tvar match = Boolean(hashTable[key]);\n\n\t\treturn (match ? false : hashTable[key] = true);\n\t});\n}\n\nvar deduped = dedup([\n\t{ a: 1 },\n\t{ a: 1 },\n\t[ 1, 2 ],\n\t[ 1, 2 ]\n]);\n\nconsole.log(deduped); // [ {a: 1}, [1, 2] ]\n```\n\nBecause a hash table in javascript is simply an `Object`, the keys\nwill always be of the type `String`. This means that normally we can't\ndistinguish between strings and numbers of the same value, i.e. `1` and\n`'1'`.\n\n```javascript\nvar hashTable = {};\n\nhashTable[1] = true;\nhashTable['1'] = true;\n\nconsole.log(hashTable); // { '1': true }\n```\n\nHowever, because we're using [`JSON.stringify`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), keys that are of the\ntype `String`, will be stored as an escaped string value, giving us unique\nkeys in our `hashTable`.\n\n```javascript\nvar hashTable = {};\n\nhashTable[JSON.stringify(1)] = true;\nhashTable[JSON.stringify('1')] = true;\n\nconsole.log(hashTable); // { '1': true, '\\'1\\'': true }\n```\n\nThis means duplicate elements of the same value, but of a different type,\nwill still be deduplicated using the same implementation.\n\n```javascript\nvar deduped = dedup([\n\t{ a: 1 },\n\t{ a: 1 },\n\t[ 1, 2 ],\n\t[ 1, 2 ],\n\t1,\n\t1,\n\t'1',\n\t'1'\n]);\n\nconsole.log(deduped); // [ {a: 1}, [1, 2], 1, '1' ]\n```\n\n# Resources\n## Methods\n* [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)\n* [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\n* [`from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from)\n* [`JSON.stringify`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n\n## ES2015\n* [arrow functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n* [Sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n\n## Stack overflow\n* [remove duplicates from array](http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array/9229821#9229821)\n"},"2016-01-12-pseudomandatory-parameters-in-es6-functions.md":{"name":"2016-01-12-pseudomandatory-parameters-in-es6-functions.md","sha":"91122de391e67694a6b86f7775292ab9873e4418","content":"---\nlayout: post\n\ntitle: Pseudomandatory parameters in ES6 functions\ntip-number: 12\ntip-username: Avraam Mavridis\ntip-username-profile: https://github.com/AvraamMavridis\ntip-tldr: In many programming languages the parameters of a function are by default mandatory and the developer has to explicitly define that a parameter is optional.\n\nredirect_from:\n - /en/pseudomandatory-parameters-in-es6-functions/\n\ncategories:\n - en\n - javascript\n---\n\nIn many programming languages the parameters of a function are by default mandatory and the developer has to explicitly define that a parameter is optional. In Javascript, every parameter is optional, but we can enforce this behavior without messing with the actual body of a function, taking advantage of [**es6's default values for parameters**] (http://exploringjs.com/es6/ch_parameter-handling.html#sec_parameter-default-values) feature.\n\n```javascript\nconst _err = function( message ){\n throw new Error( message );\n}\n\nconst getSum = (a = _err('a is not defined'), b = _err('b is not defined')) => a + b\n\ngetSum( 10 ) // throws Error, b is not defined\ngetSum( undefined, 10 ) // throws Error, a is not defined\n```\n\n `_err` is a function that immediately throws an Error. If no value is passed for one of the parameters, the default value is going to be used, `_err` will be called and an Error will be thrown. You can see more examples for the **default parameters feature** on [Mozilla's Developer Network ](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters)"},"2016-02-08-advanced-properties.md":{"name":"2016-02-08-advanced-properties.md","sha":"d4de90d791d15d620b5e7e2988b204f1511501e2","content":"---\nlayout: post\n\ntitle: Advanced Javascript Properties\ntip-number: 39\ntip-username: mallowigi\ntip-username-profile: https://github.com/mallowigi\ntip-tldr: How to add private properties, getters and setters to objects.\n\n\nredirect_from:\n - /en/advanced-properties/\n\ncategories:\n - en\n - javascript\n---\n\nIt is possible to configure object properties in Javascript for example to set properties to be pseudo-private or readonly. This feature is available since ECMAScript 5.1, therefore supported by all recent browsers.\n\nTo do so, you need to use the method `defineProperty` of the `Object` prototype like so:\n\n```js\nvar a = {};\nObject.defineProperty(a, 'readonly', {\n value: 15,\n writable: false\n});\n\na.readonly = 20;\nconsole.log(a.readonly); // 15\n```\n\nThe syntax is as follows: \n```js\nObject.defineProperty(dest, propName, options)\n```\n\nor for multiple definitions:\n```js\nObject.defineProperties(dest, {\n propA: optionsA,\n propB: optionsB, //...\n})\n```\n\nwhere options include the following attributes:\n- *value*: if the property is not a getter (see below), value is a mandatory attribute. `{a: 12}` === `Object.defineProperty(obj, 'a', {value: 12})`\n- *writable*: set the property as readonly. Note that if the property is a nested objects, its properties are still editable.\n- *enumerable*: set the property as hidden. That means that `for ... of` loops and `stringify` will not include the property in their result, but the property is still there. Note: That doesn't mean that the property is private! It can still be accessible from the outside, it just means that it won't be printed.\n- *configurable*: set the property as non modifiable, e.g. protected from deletion or redefinition. Again, if the property is a nested object, its properties are still configurable.\n\n\nSo in order to create a private constant property, you can define it like so:\n\n```js\nObject.defineProperty(obj, 'myPrivateProp', {value: val, enumerable: false, writable: false, configurable: false});\n```\n\nBesides configuring properties, `defineProperty` allows us to define *dynamic properties*, thanks to the second parameter being a string. For instance, let's say that I want to create properties according to some external configuration:\n\n```js\n\nvar obj = {\n getTypeFromExternal(): true // illegal in ES5.1\n}\n\nObject.defineProperty(obj, getTypeFromExternal(), {value: true}); // ok\n\n// For the example sake, ES6 introduced a new syntax:\nvar obj = {\n [getTypeFromExternal()]: true\n}\n```\n\nBut that's not all! Advanced properties allows us to create **getters** and **setters**, just like other OOP languages! In that case, one cannot use the `writable`, `enumerable` and `configurable` properties, but instead:\n\n```js\nfunction Foobar () {\n var _foo; // true private property\n\n Object.defineProperty(obj, 'foo', {\n get: function () { return _foo; }\n set: function (value) { _foo = value }\n });\n\n}\n\nvar foobar = new Foobar();\nfoobar.foo; // 15\nfoobar.foo = 20; // _foo = 20\n```\n\nAside for the obvious advantage of encapsulation and advanced accessors, you will notice that we didn't \"call\" the getter, instead we just \"get\" the property without parentheses! This is awesome! For instance, let's imagine that we have an object with long nested properties, like so:\n\n```js\nvar obj = {a: {b: {c: [{d: 10}, {d: 20}] } } };\n```\n\nNow instead of doing `a.b.c[0].d` (where one of the properties can resolve to `undefined` and throw an error), we can instead create an alias:\n\n```js\nObject.defineProperty(obj, 'firstD', {\n get: function () { return a && a.b && a.b.c && a.b.c[0] && a.b.c[0].d }\n})\n\nconsole.log(obj.firstD) // 10\n```\n\n### Note\nIf you define a getter without a setter and still try to set a value, you will get an error! This is particularly important when using helper functions such as `$.extend` or `_.merge`. Be careful!\n\n### Links\n\n- [defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n- [Defining properties in JavaScript](http://bdadam.com/blog/defining-properties-in-javascript.html)\n"},"2016-01-21-shuffle-an-array.md":{"name":"2016-01-21-shuffle-an-array.md","sha":"1a8eb444d4ca71abf5ae795a1ee0ca96ad98c114","content":"---\nlayout: post\n\ntitle: Shuffle an Array\ntip-number: 21\ntip-username: 0xmtn\ntip-username-profile: https://github.com/0xmtn/\ntip-tldr: Fisher-Yates Shuffling it's an algorithm to shuffle an array.\n\nredirect_from:\n - /en/shuffle-an-array/\n\ncategories:\n - en\n - javascript\n---\n\n This snippet here uses [Fisher-Yates Shuffling](https://www.wikiwand.com/en/Fisher%E2%80%93Yates_shuffle) Algorithm to shuffle a given array.\n\n```javascript\nfunction shuffle(arr) {\n var i,\n j,\n temp;\n for (i = arr.length - 1; i > 0; i--) {\n j = Math.floor(Math.random() * (i + 1));\n temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n return arr; \n};\n```\nAn example:\n\n```javascript\nvar a = [1, 2, 3, 4, 5, 6, 7, 8];\nvar b = shuffle(a);\nconsole.log(b);\n// [2, 7, 8, 6, 5, 3, 1, 4]\n```"},"2016-01-10-check-if-a-property-is-in-a-object.md":{"name":"2016-01-10-check-if-a-property-is-in-a-object.md","sha":"2563ba14680cbb36e85444cd9796c8dac98838c9","content":"---\nlayout: post\n\ntitle: Check if a property is in a Object\ntip-number: 10\ntip-username: loverajoel\ntip-username-profile: https://www.twitter.com/loverajoel\ntip-tldr: These are ways to check if a property is present in an object.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/check-if-a-property-is-in-a-object/\n\ncategories:\n - en\n - javascript\n---\n\nWhen you have to check if a property is present in an [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects), you probably are doing something like this:\n\n```javascript\nvar myObject = {\n name: '@tips_js'\n};\n\nif (myObject.name) { ... }\n\n```\n\nThat's ok, but you have to know that there are two native ways for this kind of thing, the [`in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) and [`Object.hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty). Every object descended from `Object`, has both ways available.\n\n### See the big Difference\n\n```javascript\nvar myObject = {\n name: '@tips_js'\n};\n\nmyObject.hasOwnProperty('name'); // true\n'name' in myObject; // true\n\nmyObject.hasOwnProperty('valueOf'); // false, valueOf is inherited from the prototype chain\n'valueOf' in myObject; // true\n\n```\n\nBoth differ in the depth at which they check the properties. In other words, `hasOwnProperty` will only return true if key is available on that object directly. However, the `in` operator doesn't discriminate between properties created on an object and properties inherited from the prototype chain.\n\nHere's another example:\n\n```javascript\nvar myFunc = function() {\n this.name = '@tips_js';\n};\nmyFunc.prototype.age = '10 days';\n\nvar user = new myFunc();\n\nuser.hasOwnProperty('name'); // true\nuser.hasOwnProperty('age'); // false, because age is from the prototype chain\n```\n\nCheck the [live examples here](https://jsbin.com/tecoqa/edit?js,console)!\n\nI also recommend reading [this discussion](https://github.com/loverajoel/jstips/issues/62) about common mistakes made when checking a property's existence in objects."},"2016-01-23-converting-to-number-fast-way.md":{"name":"2016-01-23-converting-to-number-fast-way.md","sha":"406404dc7d4cbc8705dd0d2c3612db7a1f7829b5","content":"---\nlayout: post\n\ntitle: Converting to number fast way\ntip-number: 23\ntip-username: sonnyt\ntip-username-profile: http://twitter.com/sonnyt\ntip-tldr: Converting strings to numbers is extremely common. The easiest and fastest way to achieve that would be using the + operator.\n\nredirect_from:\n - /en/converting-to-number-fast-way/\n\ncategories:\n - en\n - javascript\n---\n\nConverting strings to numbers is extremely common. The easiest and fastest ([jsPerf](https://jsperf.com/number-vs-parseint-vs-plus/29)) way to achieve that would be using the `+` (plus) operator.\n\n```javascript\nvar one = '1';\n\nvar numberOne = +one; // Number 1\n```\n\nYou can also use the `-` (minus) operator which type-converts the value into number but also negates it.\n\n```javascript\nvar one = '1';\n\nvar negativeNumberOne = -one; // Number -1\n```\n"},"2016-01-19-safe-string-concatenation.md":{"name":"2016-01-19-safe-string-concatenation.md","sha":"2ffa5b1d80d65aab198b1e2ab940a78017a19cc6","content":"---\nlayout: post\n\ntitle: Safe string concatenation\ntip-number: 19\ntip-username: gogainda\ntip-username-profile: https://twitter.com/gogainda\ntip-tldr: Suppose you have a couple of variables with unknown types and you want to concatenate them in a string. To be sure that the arithmetical operation is not be applied during concatenation, use concat\n\nredirect_from:\n - /en/safe-string-concatenation/\n\ncategories:\n - en\n - javascript\n---\n\nSuppose you have a couple of variables with unknown types and you want to concatenate them in a string. To be sure that the arithmetical operation is not be applied during concatenation, use `concat`:\n\n```javascript\nvar one = 1;\nvar two = 2;\nvar three = '3';\n\nvar result = ''.concat(one, two, three); //\"123\"\n```\n\nThis way of concatenting does exactly what you'd expect. In contrast, concatenation with pluses might lead to unexpected results:\n\n```javascript\nvar one = 1;\nvar two = 2;\nvar three = '3';\n\nvar result = one + two + three; //\"33\" instead of \"123\"\n```\n\nSpeaking about performance, compared to the `join` [type](http://www.sitepoint.com/javascript-fast-string-concatenation/) of concatenation, the speed of `concat` is pretty much the same.\n\nYou can read more about the `concat` function on MDN [page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat)."},"2016-02-16-basics-declarations.md":{"name":"2016-02-16-basics-declarations.md","sha":"b8434bf03ae29fcaec470a1a8f52a4b82036cc88","content":"---\nlayout: post\n\ntitle: Basics declarations\ntip-number: 47\ntip-username: adaniloff \ntip-username-profile: https://github.com/adaniloff\ntip-tldr: Understand and work with declarations.\n\nredirect_from:\n - /en/basics-declarations/\n\ncategories:\n - en\n - javascript\n---\n\nBelow, different ways to declare variables in JavaScript. \nComments and console.log should be enough to explain what's happening here:\n\n```js\nvar y, x = y = 1 //== var x; var y; x = y = 1\nconsole.log('--> 1:', `x = ${x}, y = ${y}`)\n\n// Will print\n//--> 1: x = 1, y = 1\n```\n\nFirst, we just set two variables. Nothing much here.\n\n```js\n;(() => { \n var x = y = 2 // == var x; x = y = 2;\n console.log('2.0:', `x = ${x}, y = ${y}`)\n})()\nconsole.log('--> 2.1:', `x = ${x}, y = ${y}`)\n\n// Will print\n//2.0: x = 2, y = 2\n//--> 2.1: x = 1, y = 2\n```\n\nAs you can see, the code has only changed the global y, as we haven't declared the variable in the closure.\n\n```js\n;(() => { \n var x, y = 3 // == var x; var y = 3;\n console.log('3.0:', `x = ${x}, y = ${y}`)\n})()\nconsole.log('--> 3.1:', `x = ${x}, y = ${y}`)\n\n// Will print\n//3.0: x = undefined, y = 3\n//--> 3.1: x = 1, y = 2\n```\n\nNow we declare both variables through var. Meaning they only live in the context of the closure.\n\n```js\n;(() => { \n var y, x = y = 4 // == var x; var y; x = y = 4\n console.log('4.0:', `x = ${x}, y = ${y}`)\n})()\nconsole.log('--> 4.1:', `x = ${x}, y = ${y}`)\n\n// Will print\n//4.0: x = 4, y = 4\n//--> 4.1: x = 1, y = 2\n```\n\nBoth variables have been declared using var and only after that we've set their values. As local > global, x and y are local in the closure, meaning the global x and y are untouched.\n\n```js\nx = 5 // == x = 5\nconsole.log('--> 5:', `x = ${x}, y = ${y}`)\n\n// Will print\n//--> 5: x = 5, y = 2\n```\n\nThis last line is explicit by itself.\n\nYou can test this and see the result [thanks to babel](https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=var%20y%2C%20x%20%3D%20y%20%3D%201%20%2F%2F%3D%3D%20var%20x%3B%20var%20y%3B%20x%20%3D%20y%20%3D%201%0Aconsole.log('--%3E%201%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%0A%2F%2F%20Will%20print%0A%2F%2F--%3E%201%3A%20x%20%3D%201%2C%20y%20%3D%201%0A%0A%3B(()%20%3D%3E%20%7B%20%0A%20%20var%20x%20%3D%20y%20%3D%202%20%2F%2F%20%3D%3D%20var%20x%3B%20y%20%3D%202%3B%0A%20%20console.log('2.0%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%7D)()%0Aconsole.log('--%3E%202.1%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%0A%2F%2F%20Will%20print%0A%2F%2F2.0%3A%20x%20%3D%202%2C%20y%20%3D%202%0A%2F%2F--%3E%202.1%3A%20x%20%3D%201%2C%20y%20%3D%202%0A%0A%3B(()%20%3D%3E%20%7B%20%0A%20%20var%20x%2C%20y%20%3D%203%20%2F%2F%20%3D%3D%20var%20x%3B%20var%20y%20%3D%203%3B%0A%20%20console.log('3.0%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%7D)()%0Aconsole.log('--%3E%203.1%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%0A%2F%2F%20Will%20print%0A%2F%2F3.0%3A%20x%20%3D%20undefined%2C%20y%20%3D%203%0A%2F%2F--%3E%203.1%3A%20x%20%3D%201%2C%20y%20%3D%202%0A%0A%3B(()%20%3D%3E%20%7B%20%0A%20%20var%20y%2C%20x%20%3D%20y%20%3D%204%20%2F%2F%20%3D%3D%20var%20x%3B%20var%20y%3B%20x%20%3D%20y%20%3D%203%0A%20%20console.log('4.0%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%7D)()%0Aconsole.log('--%3E%204.1%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%0A%2F%2F%20Will%20print%0A%2F%2F4.0%3A%20x%20%3D%204%2C%20y%20%3D%204%0A%2F%2F--%3E%204.1%3A%20x%20%3D%201%2C%20y%20%3D%202%0A%0Ax%20%3D%205%20%2F%2F%20%3D%3D%20x%20%3D%205%0Aconsole.log('--%3E%205%3A'%2C%20%60x%20%3D%20%24%7Bx%7D%2C%20y%20%3D%20%24%7By%7D%60)%0A%0A%2F%2F%20Will%20print%0A%2F%2F--%3E%205%3A%20x%20%3D%205%2C%20y%20%3D%202).\n\nMore informations available on the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var).\n\nSpecial thanks to @kurtextrem for his collaboration :)!\n"},"2016-01-25-Using-immediately-invoked-function-expression.md":{"name":"2016-01-25-Using-immediately-invoked-function-expression.md","sha":"49c40274cc713f9ef769dd1634d7d76e5b756873","content":"---\nlayout: post\n\ntitle: Using immediately invoked function expression\ntip-number: 25\ntip-username: rishantagarwal \ntip-username-profile: https://github.com/rishantagarwal\ntip-tldr: Called as \"Iffy\" ( IIFE - immediately invoked function expression) is an anonymous function expression that is immediately invoked and has some important uses in Javascript.\n\n\nredirect_from:\n - /en/Using-immediately-invoked-function-expression/\n\ncategories:\n - en\n - javascript\n---\n\nCalled as \"Iffy\" ( IIFE - immediately invoked function expression) is an anonymous function expression that is immediately invoked and has some important uses in Javascript.\n\n```javascript\n\n(function() {\n // Do something\n }\n)()\n\n```\n\nIt is an anonymous function expression that is immediately invoked, and it has some particularly important uses in JavaScript.\n\nThe pair of parenthesis surrounding the anonymous function turns the anonymous function into a function expression or variable expression. So instead of a simple anonymous function in the global scope, or wherever it was defined, we now have an unnamed function expression.\n\nSimilarly, we can even create a named, immediately invoked function expression:\n\n```javascript\n(someNamedFunction = function(msg) {\n\tconsole.log(msg || \"Nothing for today !!\")\n\t}) (); // Output --> Nothing for today !!\n\nsomeNamedFunction(\"Javascript rocks !!\"); // Output --> Javascript rocks !!\nsomeNamedFunction(); // Output --> Nothing for today !!\n```\n\nFor more details, check the following URL's - \n1. [Link 1](https://blog.mariusschulz.com/2016/01/13/disassembling-javascripts-iife-syntax) \n2. [Link 2](http://javascriptissexy.com/12-simple-yet-powerful-javascript-tips/) \n\nPerformance:\n[jsPerf](http://jsperf.com/iife-with-call)"},"2015-12-29-insert-item-inside-an-array.md":{"name":"2015-12-29-insert-item-inside-an-array.md","sha":"b87f22259c4209a162b64505b3c173bfa1096b0b","content":"---\nlayout: post\n\ntitle: Insert item inside an Array\n\ntip-number: 00\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Inserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/insert-item-inside-an-array/\n\ncategories:\n - en\n - javascript\n---\n\n# Inserting an item into an existing array\n\nInserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice.\n\nThose are known methods, but it doesn't mean there isn't a more performant way. Here we go:\n\n## Adding an element at the end\n\nAdding an element at the end of the array is easy with push(), but it can be done in different ways.\n\n```javascript\n\nvar arr = [1,2,3,4,5];\nvar arr2 = [];\n\narr.push(6);\narr[arr.length] = 6;\narr2 = arr.concat([6]);\n```\nBoth first methods modify the original array. Don't believe me? Check the [jsperf](http://jsperf.com/push-item-inside-an-array)\n\n### Performance on mobile :\n\n#### Android (v4.2.2)\n\n1. _arr.push(6);_ and _arr[arr.length] = 6;_ have the same performance // 3 319 694 ops/sec\n3. _arr2 = arr.concat([6]);_ 50.61 % slower than the other two methods\n\n#### Chrome Mobile (v33.0.0)\n\n1. _arr[arr.length] = 6;_ // 6 125 975 ops/sec\n2. _arr.push(6);_ 66.74 % slower\n3. _arr2 = arr.concat([6]);_ 87.63 % slower\n\n#### Safari Mobile (v9)\n\n1. _arr[arr.length] = 6;_ // 7 452 898 ops/sec\n2. _arr.push(6);_ 40.19 % slower\n3. _arr2 = arr.concat([6]);_ 49.78 % slower\n\n```javascript\nFinal victor\n\n1. arr[arr.length] = 6; // with an average of 5 632 856 ops/sec\n2. arr.push(6); // 35.64 % slower\n3. arr2 = arr.concat([6]); // 62.67 % slower\n```\n\n### Performance on desktop\n\n#### Chrome (v48.0.2564)\n\n1. _arr[arr.length] = 6;_ // 21 602 722 ops/sec\n2. _arr.push(6);_ 61.94 % slower\n3. _arr2 = arr.concat([6]);_ 87.45 % slower\n\n#### Firefox (v44)\n\n1. _arr.push(6);_ // 56 032 805 ops/sec\n2. _arr[arr.length] = 6;_ 0.52 % slower\n3. _arr2 = arr.concat([6]);_ 87.36 % slower\n\n#### IE (v11)\n\n1. _arr[arr.length] = 6;_ // 67 197 046 ops/sec\n2. _arr.push(6);_ 39.61 % slower\n3. _arr2 = arr.concat([6]);_ 93.41 % slower\n\n#### Opera (v35.0.2066.68)\n\n1. _arr[arr.length] = 6;_ // 30 775 071 ops/sec\n2. _arr.push(6);_ 71.60 % slower\n3. _arr2 = arr.concat([6]);_ 83.70 % slower\n\n#### Safari (v9.0.3)\n\n1. _arr.push(6);_ // 42 670 978 ops/sec\n2. _arr[arr.length] = 6;_ 0.80 % slower\n3. _arr2 = arr.concat([6]);_ 76.07 % slower\n\n```javascript\nFinal victor\n\n1. arr[arr.length] = 6; // with an average of 42 345 449 ops/sec\n2. arr.push(6); // 34.66 % slower\n3. arr2 = arr.concat([6]); // 85.79 % slower\n```\n\n## Add an element at the beginning\n\nNow if we are trying to add an item to the beginning of the array:\n\n```javascript\nvar arr = [1,2,3,4,5];\n\narr.unshift(0);\n[0].concat(arr);\n```\nHere is a little more detail: unshift edits the original array; concat returns a new array. [jsperf](http://jsperf.com/unshift-item-inside-an-array)\n\n### Performance on mobile :\n\n#### Android (v4.2.2)\n\n1. _[0].concat(arr);_ // 1 808 717 ops/sec\n2. _arr.unshift(0);_ 97.85 % slower\n\n#### Chrome Mobile (v33.0.0)\n\n1. _[0].concat(arr);_ // 1 269 498 ops/sec\n2. _arr.unshift(0);_ 99.86 % slower\n\n#### Safari Mobile (v9)\n\n1. _arr.unshift(0);_ // 3 250 184 ops/sec\n2. _[0].concat(arr);_ 33.67 % slower\n\n```javascript\nFinal victor\n\n1. [0].concat(arr); // with an average of 4 972 622 ops/sec\n2. arr.unshift(0); // 64.70 % slower\n```\n\n### Performance on desktop\n\n#### Chrome (v48.0.2564)\n\n1. _[0].concat(arr);_ // 2 656 685 ops/sec\n2. _arr.unshift(0);_ 96.77 % slower\n\n#### Firefox (v44)\n\n1. _[0].concat(arr);_ // 8 039 759 ops/sec\n2. _arr.unshift(0);_ 99.72 % slower\n\n#### IE (v11)\n\n1. _[0].concat(arr);_ // 3 604 226 ops/sec\n2. _arr.unshift(0);_ 98.31 % slower\n\n#### Opera (v35.0.2066.68)\n\n1. _[0].concat(arr);_ // 4 102 128 ops/sec\n2. _arr.unshift(0);_ 97.44 % slower\n\n#### Safari (v9.0.3)\n\n1. _arr.unshift(0);_ // 12 356 477 ops/sec\n2. _[0].concat(arr);_ 15.17 % slower\n\n```javascript\nFinal victor\n\n1. [0].concat(arr); // with an average of 6 032 573 ops/sec\n2. arr.unshift(0); // 78.65 % slower\n```\n\n## Add an element in the middle\n\nAdding items in the middle of an array is easy with splice, and it's the most performant way to do it.\n\n```javascript\nvar items = ['one', 'two', 'three', 'four'];\nitems.splice(items.length / 2, 0, 'hello');\n```\n\nI tried to run these tests in various Browsers and OS and the results were similar. I hope these tips will be useful for you and encourage to perform your own tests!\n"},"2016-01-03-improve-nested-conditionals.md":{"name":"2016-01-03-improve-nested-conditionals.md","sha":"305b107c6fbd8bc3fd1d1cdc8c2457632f07e339","content":"---\nlayout: post\n\ntitle: Improve Nested Conditionals\ntip-number: 03\ntip-username: AlbertoFuente \ntip-username-profile: https://github.com/AlbertoFuente\ntip-tldr: How can we improve and make a more efficient nested `if` statement in javascript?\n\nredirect_from:\n - /en/improve-nested-conditionals/\n\ncategories:\n - en\n - javascript\n---\n\nHow can we improve and make a more efficient nested `if` statement in javascript?\n\n```javascript\nif (color) {\n if (color === 'black') {\n printBlackBackground();\n } else if (color === 'red') {\n printRedBackground();\n } else if (color === 'blue') {\n printBlueBackground();\n } else if (color === 'green') {\n printGreenBackground();\n } else {\n printYellowBackground();\n }\n}\n```\n\nOne way to improve the nested `if` statement would be using the `switch` statement. Although it is less verbose and is more ordered, it's not recommended to use it because it's so difficult to debug errors. Here's [why](https://toddmotto.com/deprecating-the-switch-statement-for-object-literals).\n\n```javascript\nswitch(color) {\n case 'black':\n printBlackBackground();\n break;\n case 'red':\n printRedBackground();\n break;\n case 'blue':\n printBlueBackground();\n break;\n case 'green':\n printGreenBackground();\n break;\n default:\n printYellowBackground();\n}\n```\n\nBut what if we have a conditional with several checks in each statement? In this case, if we want it less verbose and more ordered, we can use the conditional `switch`.\nIf we pass `true` as a parameter to the `switch` statement, it allows us to put a conditional in each case.\n\n```javascript\nswitch(true) {\n case (typeof color === 'string' && color === 'black'):\n printBlackBackground();\n break;\n case (typeof color === 'string' && color === 'red'):\n printRedBackground();\n break;\n case (typeof color === 'string' && color === 'blue'):\n printBlueBackground();\n break;\n case (typeof color === 'string' && color === 'green'):\n printGreenBackground();\n break;\n case (typeof color === 'string' && color === 'yellow'):\n printYellowBackground();\n break;\n}\n```\n\nIf refactoring is an option, we can try to simplify the functions themselves. For example instead of having a function for each background color we could have an function that takes the color as an argument.\n\n```javascript\nfunction printBackground(color) {\n if (!color || typeof color !== 'string') {\n return; // Invalid color, return immediately\n }\n}\n```\n\nBut if refactoring is not an option, we must always avoid having several checks in every condition and avoid using `switch` as much as possible. We also must take into account that the most efficient way to do this is through an `object`.\n\n```javascript\nvar colorObj = {\n 'black': printBlackBackground,\n 'red': printRedBackground,\n 'blue': printBlueBackground,\n 'green': printGreenBackground,\n 'yellow': printYellowBackground\n};\n\nif (color in colorObj) {\n colorObj[color]();\n}\n```\n\nHere you can find more information about [this](http://www.nicoespeon.com/en/2015/01/oop-revisited-switch-in-js/).\n"},"2016-01-04-sorting-strings-with-accented-characters.md":{"name":"2016-01-04-sorting-strings-with-accented-characters.md","sha":"9331f29d9b41ab7a79b486fd951018a2695d0c9c","content":"---\nlayout: post\n\ntitle: Sorting strings with accented characters\ntip-number: 04\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Javascript has a native method **sort** that allows sorting arrays. Doing a simple `array.sort()` will treat each array entry as a string and sort it alphabetically. But when you try order an array of non ASCII characters you will obtain a strange result.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/sorting-strings-with-accented-characters/\n\ncategories:\n - en\n - javascript\n---\n\nJavascript has a native method **[sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)** that allows sorting arrays. Doing a simple `array.sort()` will treat each array entry as a string and sort it alphabetically. Also you can provide your [own custom sorting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters) function.\n\n```javascript\n['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();\n// [\"Buenos Aires\", \"Mumbai\", \"New York\", \"Shanghai\"]\n```\n\nBut when you try order an array of non ASCII characters like this `['é', 'a', 'ú', 'c']`, you will obtain a strange result `['c', 'e', 'á', 'ú']`. That happens because sort works only with the English language.\n\nSee the next example:\n\n```javascript\n// Spanish\n['único','árbol', 'cosas', 'fútbol'].sort();\n// [\"cosas\", \"fútbol\", \"árbol\", \"único\"] // bad order\n\n// German\n['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();\n// [\"Wann\", \"Woche\", \"wäre\", \"wöchentlich\"] // bad order\n```\n\nFortunately, there are two ways to overcome this behavior [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) and [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) provided by ECMAScript Internationalization API.\n\n> Both methods have their own custom parameters in order to configure it to work adequately.\n\n### Using `localeCompare()`\n\n```javascript\n['único','árbol', 'cosas', 'fútbol'].sort(function (a, b) {\n return a.localeCompare(b);\n});\n// [\"árbol\", \"cosas\", \"fútbol\", \"único\"]\n\n['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(function (a, b) {\n return a.localeCompare(b);\n});\n// [\"Wann\", \"wäre\", \"Woche\", \"wöchentlich\"]\n```\n\n### Using `Intl.Collator()`\n\n```javascript\n['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);\n// [\"árbol\", \"cosas\", \"fútbol\", \"único\"]\n\n['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);\n// [\"Wann\", \"wäre\", \"Woche\", \"wöchentlich\"]\n```\n\n- For each method you can customize the location.\n- According to [Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#Performance) Intl.Collator is faster when comparing large numbers of strings.\n\nSo when you are working with arrays of strings in a language other than English, remember to use this method to avoid unexpected sorting."},"2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions—it-kills-optimization.md":{"name":"2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions—it-kills-optimization.md","sha":"a5e0f1510aefb775b23ddd39d36ed02297cb7661","content":"---\nlayout: post\n\ntitle: Avoid modifying or passing `arguments` into other functions — it kills optimization\ntip-number: 31\ntip-username: berkana\ntip-username-profile: https://github.com/berkana\ntip-tldr: Within JavaScript functions, the variable name `arguments` lets you access all of the arguments passed to the function. `arguments` is an *array-like object*; `arguments` can be accessed using array notation, and it has the *length* property, but it doesn't have many of the built-in methods that arrays have such as `filter` and `map` and `forEach`. Because of this, it is a fairly common practice to convert `arguments` into an array using the following snipet\n\n\nredirect_from:\n - /en/avoid-modifying-or-passing-arguments-into-other-functions-it-kills-optimization/\n\ncategories:\n - en\n - javascript\n---\n\n###Background\n\nWithin JavaScript functions, the variable name [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments) lets you access all of the arguments passed to the function. `arguments` is an *array-like object*; `arguments` can be accessed using array notation, and it has the *length* property, but it doesn't have many of the built-in methods that arrays have such as `filter` and `map` and `forEach`. Because of this, it is a fairly common practice to convert `arguments` into an array using the following:\n\n```js\nvar args = Array.prototype.slice.call(arguments);\n```\nThis calls the `slice` method from the `Array` prototype, passing it `arguments`; the `slice` method returns a shallow copy of `arguments` as a new array object. A common shorthand for this is :\n\n```js\nvar args = [].slice.call(arguments);\n```\nIn this case, instead of calling `slice` from the `Array` prototype, it is simply being called from an empty array literal.\n\n###Optimization\n\nUnfortunately, passing `arguments` into any function call will cause the V8 JavaScript engine used in Chrome and Node to skip optimization on the function that does this, which can result in considerably slower performance. See this article on [optimization killers](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers). Passing `arguments` to any other function is known as *leaking `arguments`*.\n\nInstead, if you want an array of the arguments that lets you use you need to resort to this:\n\n```js\nvar args = new Array(arguments.length);\nfor(var i = 0; i < args.length; ++i) {\n args[i] = arguments[i];\n}\n```\n\nYes it is more verbose, but in production code, it is worth it for the performance optimization."},"2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md":{"name":"2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md","sha":"a60f583b3dc0ce83894e0c5691da044cf4f392d9","content":"---\nlayout: post\n\ntitle: Map() to the rescue; adding order to Object properties\ntip-number: 32\ntip-username: loverajoel\ntip-username-profile: https://twitter.com/loverajoel\ntip-tldr: An Object it is an unordered collection of properties... that means that if you are trying to save ordered data inside an Object, you have to review it because properties order in objects are not guaranteed.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/map-to-the-rescue-adding-order-to-object-properties/\n\ncategories:\n - en\n - javascript\n---\n\n## Object properties order\n\n> An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. [ECMAScript](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf)\n\nTake a look in action\n\n```js\nvar myObject = {\n\tz: 1,\n\t'@': 2,\n\tb: 3,\n\t1: 4,\n\t5: 5\n};\nconsole.log(myObject) // Object {1: 4, 5: 5, z: 1, @: 2, b: 3}\n\nfor (item in myObject) {...\n// 1\n// 5\n// z\n// @\n// b\n```\nEach browser have his own rules about the order in objects bebause technically, order is unspecified.\n\n## How to solve this?\n\n### Map\n\nUsing a new ES6 feature called Map. A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object iterates its elements in insertion order — a `for...of` loop returns an array of [key, value] for each iteration. \n\n```js\nvar myObject = new Map();\nmyObject.set('z', 1);\nmyObject.set('@', 2);\nmyObject.set('b', 3);\nfor (var [key, value] of myObject) {\n console.log(key, value);\n...\n// z 1\n// @ 2\n// b 3\n```\n\n### Hack for old browsers\n\nMozilla suggest:\n> So, if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.\n\n```js\n// Using two separate arrays\nvar objectKeys = [z, @, b, 1, 5];\nfor (item in objectKeys) {\n\tmyObject[item]\n...\n\n// Build an array of single-property objects\nvar myData = [{z: 1}, {'@': 2}, {b: 3}, {1: 4}, {5: 5}];\n```\n"},"2016-02-12-use-destructuring-in-function-parameters.md":{"name":"2016-02-12-use-destructuring-in-function-parameters.md","sha":"11015e45f29193fa997a1e68520a453269af6409","content":"---\nlayout: post\n\ntitle: Use destructuring in function parameters\ntip-number: 43\ntip-username: dislick \ntip-username-profile: https://github.com/dislick\ntip-tldr: Did you know that you can use destructuring in function parameters?\n\nredirect_from:\n - /en/use-destructuring-in-function-parameters/\n\ncategories:\n - en\n - javascript\n---\n\nI am sure many of you are already familiar with the [ES6 Destructuring Assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). Did you know that you can also use it in function parameters? \n\n```js\nvar sayHello = function({ name, surname }) {\n console.log(`Hello ${name} ${surname}! How are you?`);\n};\n\nsayHello({ name: 'John', surname: 'Smith' })\n// -> Hello John Smith! How are you?\n```\n\nThis is great for functions which accept an options object. For this use case, you can also add [default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) to fill in whatever values the caller leaves out, or if the caller forgets to pass one at all:\n\n```js\nvar sayHello2 = function({ name = \"Anony\", surname = \"Moose\" } = {}) {\n console.log(`Hello ${name} ${surname}! How are you?`);\n};\n```\n\nThe `= {}` says that the default object to be destructured for this parameter is `{}`, in case the caller forgets to pass the parameter, or passes one of the wrong type (more on this below).\n\n```js\nsayHello2()\n// -> Hello Anony Moose! How are you?\nsayHello2({ name: \"Bull\" })\n// -> Hello Bull Moose! How are you?\n```\n\n##### Argument Handling\n\nWith plain destructuring assignment, if the the input parameter can't be matched with the function's specified object arguments, all the unmatched arguments are `undefined`, so you need to add code that handles this properly:\n\n```js\nvar sayHelloTimes = function({ name, surname }, times) {\n console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);\n}\n\nsayHelloTimes({ name: \"Pam\" }, 5678)\n// -> Hello Pam undefined! I've seen you 5678 times before.\nsayHelloTimes(5678)\n// -> Hello undefined undefined! I've seen you undefined times before.\n```\n\nWorse, if the parameter to be destructured is missing, an exception is thrown, probably bringing your app to a screeching halt:\n\n```js\nsayHelloTimes()\n// -> Uncaught TypeError: Cannot match against 'undefined' or 'null'...\n```\n\nIt's conceptually similar to accessing a property of an undefined object, just with a different exception type.\n\nDestructuring assignment with default parameters hides all the above to a certain extent:\n\n```js\nvar sayHelloTimes2 = function({ name = \"Anony\", surname = \"Moose\" } = {}, times) {\n console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);\n};\n\nsayHelloTimes2({ name: \"Pam\" }, 5678)\n// -> Hello Pam Moose! I've seen you 5678 times before.\nsayHelloTimes2(5678)\n// -> Hello Anony Moose! I've seen you undefined times before.\nsayHelloTimes2()\n// -> Hello Anony Moose! I've seen you undefined times before.\n```\n\nAs for `= {}`, it covers the case of a missing _object_, for which individual property defaults won't help at all:\n\n```js\nvar sayHelloTimes2a = function({ name = \"Anony\", surname = \"Moose\" }, times) {\n console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);\n};\n\nsayHelloTimes2a({ name: \"Pam\" }, 5678)\n// -> Hello Pam Moose! I've seen you 5678 times before.\nsayHelloTimes2a(5678)\n// -> Hello Anony Moose! I've seen you undefined times before.\nsayHelloTimes2a()\n// -> Uncaught TypeError: Cannot match against 'undefined' or 'null'.\n```\n\n##### Availability\n\nNote that destructuring assignment may not yet be available by default, in the version of Node.js or browser that you're using. For Node.js, you can try using the `--harmony-destructuring` flag on startup to activate this feature.\n"},"2016-02-17-reminders-about-reduce-function-usage.md":{"name":"2016-02-17-reminders-about-reduce-function-usage.md","sha":"a6f79f602a2c8fadd38d55e95c989124360c0836","content":"---\nlayout: post\n\ntitle: How to `reduce()` arrays\ntip-number: 48\ntip-username: darul75\ntip-username-profile: https://twitter.com/darul75\ntip-tldr: Some reminders about using `reduce()`\n\nredirect_from:\n - /en/reminders-about-reduce-function-usage/\n\ncategories:\n - en\n - javascript\n---\n\nAs written in documentation the `reduce()` method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.\n\n### Signature\n\n[reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) function accepts 2 parameters (M: mandatory, O: optional):\n\n- (M) a callback **reducer function** to be applied that deals with a pair of previous (result of previous computation) and next element until end of the list.\n- (O) an **initial value** to be used as the first argument to the first call of the callback.\n\nSo let's see a common usage and later a more sophisticated one.\n\n### Common usage (accumulation, concatenation)\n\nWe are on Amazon website (prices in $) and our caddy is quite full, let's compute total.\n\n```javascript\n// my current amazon caddy purchases\nvar items = [{price: 10}, {price: 120}, {price: 1000}];\n\n// our reducer function\nvar reducer = function add(sumSoFar, item) { return sumSoFar + item.price; };\n\n// do the job\nvar total = items.reduce(reducer, 0);\n\nconsole.log(total); // 1130\n```\n\nOptional reduce function parameter was primitive integer type 0 in that first case, but it could have been an Object, an Array...instead of a primitive type,\nbut we will see that later.\n\nNow, cool I received a discount coupon of 20$.\n\n```javascript\nvar total = items.reduce(reducer,-20);\n\nconsole.log(total); // 1110\n```\n\n### Advanced usage (combination)\n\nThis second usage example is inspired by Redux [combineReducers](http://redux.js.org/docs/api/combineReducers.html) function [source](https://github.com/reactjs/redux/blob/master/src/combineReducers.js#L93).\n\nIdea behind is to separate reducer function into separate individual functions and at the end compute a new *single big reducer function*. \n\nTo illustrate this, let's create a single object literal with some reducers function able to compute total prices in different currency $, €...\n\n```javascript\nvar reducers = {\n totalInDollar: function(state, item) {\n // specific statements...\n return state.dollars += item.price;\n },\n totalInEuros : function(state, item) {\n return state.euros += item.price * 0.897424392;\n },\n totalInPounds : function(state, item) {\n return state.pounds += item.price * 0.692688671;\n },\n totalInYen : function(state, item) {\n return state.yens += item.price * 113.852;\n }\n // more...\n};\n```\n\nThen, we create a new swiss knife function \n\n- responsible for applying each partial reduce functions.\n- that will return a new callback reducer function\n\n```javascript\nvar combineTotalPriceReducers = function(reducers) {\n return function(state, item) {\n return Object.keys(reducers).reduce(\n function(nextState, key) {\n reducers[key](state, item);\n return state;\n },\n {} \n );\n }\n};\n```\n\nNow let's see how using it.\n\n```javascript\nvar bigTotalPriceReducer = combineTotalPriceReducers(reducers);\n\nvar initialState = {dollars: 0, euros:0, yens: 0, pounds: 0};\n\nvar totals = items.reduce(bigTotalPriceReducer, initialState);\n\nconsole.log(totals);\n\n/*\nObject {dollars: 1130, euros: 1015.11531904, yens: 127524.24, pounds: 785.81131152}\n*/\n```\n\nI hope this approach can give you another idea of using reduce() function for your own needs.\n\nYour reduce function could handle an history of each computation by instance as it is done in Ramdajs with [scan](http://ramdajs.com/docs/#scan) function\n\n[JSFiddle to play with](https://jsfiddle.net/darul75/81tgt0cd/)\n"},"2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md":{"name":"2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md","sha":"47a238c57225f3641631d1c1e83d1d8a14a2d9e9","content":"---\nlayout: post\n\ntitle: Writing a single method for arrays and a single element\ntip-number: 06\ntip-username: mattfxyz\ntip-username-profile: https://twitter.com/mattfxyz\ntip-tldr: Rather than writing separate methods to handle an array and a single element parameter, write your functions so they can handle both. This is similar to how some of jQuery's functions work (`css` will modify everything matched by the selector).\n\nredirect_from:\n - /en/writing-a-single-method-for-arrays-and-a-single-element/\n\ncategories:\n - en\n - javascript\n---\n\nRather than writing separate methods to handle an array and a single element parameter, write your functions so they can handle both. This is similar to how some of jQuery's functions work (`css` will modify everything matched by the selector).\n\nYou just have to concat everything into an array first. `Array.concat` will accept an array or a single element.\n\n```javascript\nfunction printUpperCase(words) {\n var elements = [].concat(words || []);\n for (var i = 0; i < elements.length; i++) {\n console.log(elements[i].toUpperCase());\n }\n}\n```\n\n`printUpperCase` is now ready to accept a single node or an array of nodes as its parameter. It also avoids the potential `TypeError` that would be thrown if no parameter was passed.\n\n```javascript\nprintUpperCase(\"cactus\");\n// => CACTUS\nprintUpperCase([\"cactus\", \"bear\", \"potato\"]);\n// => CACTUS\n// BEAR\n// POTATO\n```\n"},"2016-01-30-converting-truthy-falsy-values-to-boolean.md":{"name":"2016-01-30-converting-truthy-falsy-values-to-boolean.md","sha":"33b929dce58555786bc46ac6351b2ba48339595d","content":"---\nlayout: post\n\ntitle: Converting truthy/falsy values to boolean\ntip-number: 30\ntip-username: hakhag\ntip-username-profile: https://github.com/hakhag\ntip-tldr: Logical operators are a core part of JavaScript, here you can see a a way you always get a true or false no matter what was given to it.\n\n\nredirect_from:\n - /en/converting-truthy-falsy-values-to-boolean/\n\ncategories:\n - en\n - javascript\n---\n\nYou can convert a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) or [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value to true boolean with the `!!` operator.\n\n```js\n!!\"\" // false\n!!0 // false\n!!null // false\n!!undefined // false\n!!NaN // false\n\n!!\"hello\" // true\n!!1 // true\n!!{} // true\n!![] // true\n```\n\n"},"2016-01-09-template-strings.md":{"name":"2016-01-09-template-strings.md","sha":"f4f614f0195eb313896a3bdca2a7366782f479b1","content":"---\nlayout: post\n\ntitle: Template Strings\ntip-number: 09\ntip-username: JakeRawr\ntip-username-profile: https://github.com/JakeRawr\ntip-tldr: As of ES6, JS now has template strings as an alternative to the classic end quotes strings.\n\nredirect_from:\n - /en/template-strings/\n\ncategories:\n - en\n - javascript\n---\n\nAs of ES6, JS now has template strings as an alternative to the classic end quotes strings.\n\nEx:\nNormal string\n\n```javascript\nvar firstName = 'Jake';\nvar lastName = 'Rawr';\nconsole.log('My name is ' + firstName + ' ' + lastName);\n// My name is Jake Rawr\n```\nTemplate String\n\n```javascript\nvar firstName = 'Jake';\nvar lastName = 'Rawr';\nconsole.log(`My name is ${firstName} ${lastName}`);\n// My name is Jake Rawr\n```\n\nYou can do multi-line strings without `\\n`, perform simple logic (ie 2+3) or even use the [ternary operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) inside `${}` in template strings.\n\n```javascript\nvar val1 = 1, val2 = 2;\nconsole.log(`${val1} is ${val1 < val2 ? 'less than': 'greater than'} ${val2}`)\n// 1 is less than 2\n```\n\nYou are also able to modify the output of template strings using a function; they are called [tagged template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings) for example usages of tagged template strings.\n\nYou may also want to [read](https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2) to understand template strings more.\n"},"2016-01-14-fat-arrow-functions.md":{"name":"2016-01-14-fat-arrow-functions.md","sha":"6ab5f3777c2f86c16eef0c0e29a1817d5b5f3fdd","content":"---\nlayout: post\n\ntitle: Fat Arrow Functions\ntip-number: 14\ntip-username: pklinger\ntip-username-profile: https://github.com/pklinger/\ntip-tldr: Introduced as a new feature in ES6, fat arrow functions may come as a handy tool to write more code in fewer lines\n\nredirect_from:\n - /en/fat-arrow-functions/\n\ncategories:\n - en\n - javascript\n---\n\nIntroduced as a new feature in ES6, fat arrow functions may come as a handy tool to write more code in fewer lines. The name comes from its syntax, `=>`, which is a 'fat arrow', as compared to a thin arrow `->`. Some programmers might already know this type of function from different languages such as Haskell, as 'lambda expressions', or as 'anonymous functions'. It is called anonymous, as these arrow functions do not have a descriptive function name.\n\n### What are the benefits?\n* Syntax: fewer LOC; no more typing `function` keyword over and over again\n* Semantics: capturing the keyword `this` from the surrounding context\n\n### Simple syntax example\nHave a look at these two code snippets, which do the exact same job, and you will quickly understand what fat arrow functions do:\n\n```javascript\n// general syntax for fat arrow functions\nparam => expression\n\n// may also be written with parentheses\n// parentheses are required on multiple params\n(param1 [, param2]) => expression\n\n\n// using functions\nvar arr = [5,3,2,9,1];\nvar arrFunc = arr.map(function(x) {\n return x * x;\n});\nconsole.log(arr)\n\n// using fat arrow\nvar arr = [5,3,2,9,1];\nvar arrFunc = arr.map((x) => x*x);\nconsole.log(arr)\n```\n\nAs you can see, the fat arrow function in this case can save you time typing out the parentheses as well as the function and return keywords. I would advise you to always write parentheses around the parameter inputs, as the parentheses will be needed for multiple input parameters, such as in `(x,y) => x+y`. It is just a way to cope with forgetting them in different use cases. But the code above would also work like this: `x => x*x`. So far, these are only syntactical improvements, which lead to fewer LOC and better readability.\n\n### Lexically binding `this`\n\nThere is another good reason to use fat arrow functions. There is the issue with the context of `this`. With arrow functions, you don't need to worry about `.bind(this)` or setting `that = this` anymore, as fat arrow functions pick the context of `this` from the lexical surrounding. Have a look at the next [example] (https://jsfiddle.net/pklinger/rw94oc11/):\n\n```javascript\n\n// globally defined this.i\nthis.i = 100;\n\nvar counterA = new CounterA();\nvar counterB = new CounterB();\nvar counterC = new CounterC();\nvar counterD = new CounterD();\n\n// bad example\nfunction CounterA() {\n // CounterA's `this` instance (!! gets ignored here)\n this.i = 0;\n setInterval(function () {\n // `this` refers to global object, not to CounterA's `this`\n // therefore starts counting with 100, not with 0 (local this.i)\n this.i++;\n document.getElementById(\"counterA\").innerHTML = this.i;\n }, 500);\n}\n\n// manually binding that = this\nfunction CounterB() {\n this.i = 0;\n var that = this;\n setInterval(function() {\n that.i++;\n document.getElementById(\"counterB\").innerHTML = that.i;\n }, 500);\n}\n\n// using .bind(this)\nfunction CounterC() {\n this.i = 0;\n setInterval(function() {\n this.i++;\n document.getElementById(\"counterC\").innerHTML = this.i;\n }.bind(this), 500);\n}\n\n// fat arrow function\nfunction CounterD() {\n this.i = 0;\n setInterval(() => {\n this.i++;\n document.getElementById(\"counterD\").innerHTML = this.i;\n }, 500);\n}\n```\n\nFurther information about fat arrow functions may be found at [MDN] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). To see different syntax options visit [this site] (http://jsrocks.org/2014/10/arrow-functions-and-their-scope/)."},"2016-02-26-extract-unix-timestamp-easily.md":{"name":"2016-02-26-extract-unix-timestamp-easily.md","sha":"3faa1acf67b25a44bec51b196c7ab05f2dfc3f8d","content":"---\nlayout: post\n\ntitle: Easiest way to extract unix timestamp in JS\ntip-number: 49\ntip-username: nmrony\ntip-username-profile: https://github.com/nmrony\ntip-tldr: In Javascript you can easily get the unix timestamp\n\nredirect_from:\n - /en/extract-unix-timestamp-easily/\n\ncategories:\n - en\n - javascript\n---\n\nWe frequently need to calculate with unix timestamp. There are several ways to grab the timestamp. For current unix timestamp easiest and fastest way is\n\n```js\nconst dateTime = Date.now();\nconst timestamp = Math.floor(dateTime / 1000);\n```\nor\n\n```js\nconst dateTime = new Date().getTime();\nconst timestamp = Math.floor(dateTime / 1000);\n```\n\nTo get unix timestamp of a specific date pass `YYYY-MM-DD` or `YYYY-MM-DDT00:00:00Z` as parameter of `Date` constructor. For example\n\n```js\nconst dateTime = new Date('2012-06-08').getTime();\nconst timestamp = Math.floor(dateTime / 1000);\n```\nYou can just add a `+` sign also when declaring a `Date` object like below\n\n```js\nconst dateTime = +new Date();\nconst timestamp = Math.floor(dateTime / 1000);\n```\nor for specific date\n\n```js\nconst dateTime = +new Date('2012-06-08');\nconst timestamp = Math.floor(dateTime / 1000);\n```\nUnder the hood the runtime calls `valueOf` method of the `Date` object. Then the unary `+` operator calls `toNumber()` with that returned value. For detailed explanation please check the following links\n\n* [Date.prototype.valueOf](http://es5.github.io/#x15.9.5.8)\n* [Unary + operator](http://es5.github.io/#x11.4.6)\n* [toNumber()](http://es5.github.io/#x9.3)\n* [Date Javascript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)\n* [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)\n"},"2016-03-03-helpful-console-log-hacks.md":{"name":"2016-03-03-helpful-console-log-hacks.md","sha":"0668840ce81368d0e43721b904410c866205880a","content":"---\r\nlayout: post\r\n\r\ntitle: Helpful Console Logging Tricks\r\ntip-number: 50\r\ntip-username: zackhall\r\ntip-username-profile: https://twitter.com/zthall\r\ntip-tldr: Helpful logging techniques using coercion and conditonal breakpoints.\r\n\r\nredirect_from:\r\n - /en/helpful-console-log-hacks/\r\n\r\ncategories:\r\n - en\r\n - javascript\r\n---\r\n\r\n## Using conditional breakpoints to log data\r\n\r\nIf you wanted to log to the console a value each time a function is called, you can use conditional break points to do this. Open up your dev tools, find the function where you'd like to log data to the console and set a breakpoint with the following condition:\r\n\r\n```js\r\nconsole.log(data.value) && false\r\n```\r\n\r\nA conditional breakpoint pauses the page thread only if the condition for the breakpoint evaluates to true. So by using a condition like console.log('foo') && false it's guaranteed to evaluate to false since you're putting the literal false in the AND condition. So this will not pause the page thread when it's hit, but it will log data to the console. This can also be used to count how many times a function or callback is called.\r\n\r\nHere's how you can set a conditional breakpoint in [Edge](https://dev.windows.com/en-us/microsoft-edge/platform/documentation/f12-devtools-guide/debugger/#setting-and-managing-breakpoints \"Managing Breakpoints in Edge\"), [Chrome](https://developer.chrome.com/devtools/docs/javascript-debugging#breakpoints \"Managing Breakpoints in Chrome\"), [Firefox](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Set_a_conditional_breakpoint \"Managing Breakpoints in Firefox\") and [Safari](https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Debugger/Debugger.html \"Managing Breakpoints in Safari\").\r\n\r\n## Printing a function variable to console\r\n\r\nHave you ever logged a function variable to the console and weren't able to just view the function's code? The quickest way to see the function's code is to coerce it to a string using concatenation with an empty string.\r\n\r\n```js\r\nconsole.log(funcVariable + '');\r\n```"},"2016-03-16-DOM-event-listening-made-easy.md":{"name":"2016-03-16-DOM-event-listening-made-easy.md","sha":"fcee4c06dcdfd2f7045cb50c93b7b9d20f1bcf1b","content":"---\nlayout: post\n\ntitle: DOM event listening made easy\ntip-number: 51\ntip-username: octopitus\ntip-username-profile: https://github.com/octopitus\ntip-tldr: An elegant and easy way to handle DOM events\n\nredirect_from:\n - /en/DOM-event-listening-made-easy/\n\ncategories:\n - en\n - javascript\n---\nMany of us are still doing these things:\n\n- `element.addEventListener('type', obj.method.bind(obj))`\n- `element.addEventListener('type', function (event) {})`\n- `element.addEventListener('type', (event) => {})`\n\nThe above examples all create new anonymous event handlers that can't be removed when no longer needed. This may cause performance problems or unexpected logic bugs, when handlers that you no longer need still get accidentally triggered through unexpected user interactions or [event bubbling](http://www.javascripter.net/faq/eventbubbling.htm).\n\nSafer event-handling patterns include the following:\n\nUse a reference:\n\n```js\nconst handler = function () {\n console.log(\"Tada!\")\n}\nelement.addEventListener(\"click\", handler)\n// Later on\nelement.removeEventListener(\"click\", handler)\n```\n\nNamed function that removes itself:\n\n```js\nelement.addEventListener('click', function click(e) {\n if (someCondition) {\n return e.currentTarget.removeEventListener('click', click);\n }\n});\n```\n\nA better approach:\n\n```js\nfunction handleEvent (eventName, {onElement, withCallback, useCapture = false} = {}, thisArg) {\n const element = onElement || document.documentElement\n\n function handler (event) {\n if (typeof withCallback === 'function') {\n withCallback.call(thisArg, event)\n }\n }\n\n handler.destroy = function () {\n return element.removeEventListener(eventName, handler, useCapture)\n }\n\n element.addEventListener(eventName, handler, useCapture)\n return handler\n}\n\n// Anytime you need\nconst handleClick = handleEvent('click', {\n onElement: element,\n withCallback: (event) => {\n console.log('Tada!')\n }\n})\n\n// And anytime you want to remove it\nhandleClick.destroy()\n```\n"},"2016-04-05-return-values-with-the-new-operator.md":{"name":"2016-04-05-return-values-with-the-new-operator.md","sha":"2df1c4536526b1783606e577275afe2cf2788f8f","content":"---\nlayout: post\n\ntitle: Return Values with the 'new' Operator\ntip-number: 52\ntip-username: Morklympious\ntip-username-profile: https://github.com/morklympious\ntip-tldr: Understand what gets returned when using new vs. not using new.\n\nredirect_from:\n - /en/return-values-with-the-new-operator/\n\ncategories:\n - en\n - javascript\n---\n\nYou're going to run into some instances where you'll be using `new` to allocate new objects in JavaScript. It's going to blow your mind unless you read this tip to understand what's happening behind the scenes.\n\nThe `new` operator in JavaScript is an operator that, under reasonable circumstances, returns a new instance of an object. Let's say we have a constructor function:\n\n````js\nfunction Thing() {\n this.one = 1;\n this.two = 2;\n}\n\nvar myThing = new Thing();\n\nmyThing.one // 1\nmyThing.two // 2\n````\n\n__Note__: `this` refers to the new object created by `new`. Otherwise if `Thing()` is called without `new`, __no object is created__, and `this` is going to point to the global object, which is `window`. This means that:\n\n1. You'll suddenly have two new global variables named `one` and `two`.\n2. `myThing` is now undefined, since nothing is returned in `Thing()`.\n\nNow that you get that example, here's where things get a little bit wonky. Let's say I add something to the constructor function, a little SPICE:\n\n````js\nfunction Thing() {\n this.one = 1;\n this.two = 2;\n\n return 5;\n}\n\nvar myThing = new Thing();\n````\n\nNow, what does myThing equal? Is it 5? is it an object? Is it my crippled sense of self-worth? The world may never know!\n\nExcept the world does know:\n\n````js\nmyThing.one // 1\nmyThing.two // 2\n````\n\nInterestingly enough, we never actually see the five that we supposedly 'returned' from our constructor. That's weird, isn't it? What are you doing function? WHERE'S THE FIVE? Let's try it with something else.\n\nLet's return a non-primitive type instead, something like an object.\n\n````js\nfunction Thing() {\n this.one = 1;\n this.two = 2;\n\n return {\n three: 3,\n four: 4\n };\n}\n\nvar myThing = new Thing();\n````\n\nLet's check it out. A quick console.log reveals all:\n\n````js\nconsole.log(myThing);\n/*\n Object {three: 3, four: 4}\n What happened to this.one and this.two!?\n They've been stomped, my friend.\n*/\n````\n\n__Here's where we learn:__ When you invoke a function with the `new` keyword, you can set properties on it using the keyword `this` (but you probably already knew that). Returning a primitive value from a function you called with the `new` keyword will not return the value you specified, but instead will return the `this` instance of the function (the one you put properties on, like `this.one = 1;`).\n\nHowever, returning a non-primitive, like an `object`, `array`, or `function` will stomp on the `this` instance, and return that non-primitive instead, effectively ruining all the hard work you did assigning everything to `this`.\n"},"2016-04-21-get-file-extension.md":{"name":"2016-04-21-get-file-extension.md","sha":"3ddd9a7045cce27e0d4a00afbaa78157a413f261","content":"---\nlayout: post\n\ntitle: Get File Extension\ntip-number: 53\ntip-username: richzw\ntip-username-profile: https://github.com/richzw\ntip-tldr: How to get the file extension more efficiently?\n\nredirect_from:\n - /en/get-file-extension/\n\ncategories:\n - en\n - javascript\n---\n\n### Question: How to get the file extension?\n\n```javascript\nvar file1 = \"50.xsl\";\nvar file2 = \"30.doc\";\ngetFileExtension(file1); //returs xsl\ngetFileExtension(file2); //returs doc\n\nfunction getFileExtension(filename) {\n /*TODO*/\n}\n```\n\n### Solution 1: Regular Expression\n\n```js\nfunction getFileExtension1(filename) {\n return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;\n}\n```\n\n### Solution 2: String `split` method\n\n```js\nfunction getFileExtension2(filename) {\n return filename.split('.').pop();\n}\n```\n\nThose two solutions couldnot handle some edge cases, here is another more robust solution.\n\n### Solution3: String `slice`, `lastIndexOf` methods\n\n```js\nfunction getFileExtension3(filename) {\n return filename.slice((filename.lastIndexOf(\".\") - 1 >>> 0) + 2);\n}\n\nconsole.log(getFileExtension3('')); // ''\nconsole.log(getFileExtension3('filename')); // ''\nconsole.log(getFileExtension3('filename.txt')); // 'txt'\nconsole.log(getFileExtension3('.hiddenfile')); // ''\nconsole.log(getFileExtension3('filename.with.many.dots.ext')); // 'ext'\n```\n\n_How does it works?_\n\n- [String.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) method returns the last occurrence of the specified value (`'.'` in this case). Returns `-1` if the value is not found.\n- The return values of `lastIndexOf` for parameter `'filename'` and `'.hiddenfile'` are `-1` and `0` respectively. [Zero-fill right shift operator (>>>)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#%3E%3E%3E_%28Zero-fill_right_shift%29) will transform `-1` to `4294967295` and `-2` to `4294967294`, here is one trick to insure the filename unchanged in those edge cases.\n- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) extracts file extension from the index that was calculated above. If the index is more than the length of the filename, the result is `\"\"`.\n\n### Comparison\n\n| Solution | Paramters | Results |\n| ----------------------------------------- |:-------------------:|:--------:|\n| Solution 1: Regular Expression | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | undefined <br> undefined <br> 'txt' <br> 'hiddenfile' <br> 'ext' <br> |\n| Solution 2: String `split` | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | '' <br> 'filename' <br> 'txt' <br> 'hiddenfile' <br> 'ext' <br> |\n| Solution 3: String `slice`, `lastIndexOf` | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | '' <br> '' <br> 'txt' <br> '' <br> 'ext' <br> |\n\n### Live Demo and Performance\n\n[Here](https://jsbin.com/tipofu/edit?js,console) is the live demo of the above codes.\n\n[Here](http://jsperf.com/extract-file-extension) is the performance test of those 3 solutions.\n\n### Source\n\n[How can I get file extensions with JavaScript](http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript)\n"},"2016-05-06-use-optional-arguments.md":{"name":"2016-05-06-use-optional-arguments.md","sha":"38e626f75e111df527d8e83b434d456d8737ea09","content":"---\nlayout: post\n\ntitle: How to use optional arguments in functions (with optional callback)\ntip-number: 54\ntip-username: alphashuro\ntip-username-profile: https://github.com/alphashuro\ntip-tldr: You can make function arguments and callback optional\n\nredirect_from:\n - /en/use-optional-arguments/\n\ncategories:\n - en\n - javascript\n---\n\nExample function where arguments 2 and 3 are optional\n\n```javascript\n function example( err, optionalA, optionalB, callback ) {\n // retrieve arguments as array\n var args = new Array(arguments.length);\n for(var i = 0; i < args.length; ++i) {\n args[i] = arguments[i];\n };\n \n // first argument is the error object\n // shift() removes the first item from the\n // array and returns it\n err = args.shift();\n\n // if last argument is a function then its the callback function.\n // pop() removes the last item in the array\n // and returns it\n if (typeof args[args.length-1] === 'function') { \n callback = args.pop();\n }\n \n // if args still holds items, these are\n // your optional items which you could\n // retrieve one by one like this:\n if (args.length > 0) optionalA = args.shift(); else optionalA = null;\n if (args.length > 0) optionalB = args.shift(); else optionalB = null;\n\n // continue as usual: check for errors\n if (err) { \n return callback && callback(err);\n }\n \n // for tutorial purposes, log the optional parameters\n console.log('optionalA:', optionalA);\n console.log('optionalB:', optionalB);\n console.log('callback:', callback);\n\n /* do your thing */\n\n }\n\n // ES6 with shorter, more terse code\n function example(...args) {\n // first argument is the error object\n const err = args.shift();\n // if last argument is a function then its the callback function\n const callback = (typeof args[args.length-1] === 'function') ? args.pop() : null;\n\n // if args still holds items, these are your optional items which you could retrieve one by one like this:\n const optionalA = (args.length > 0) ? args.shift() : null;\n const optionalB = (args.length > 0) ? args.shift() : null;\n // ... repeat for more items\n\n if (err && callback) return callback(err);\n\n /* do your thing */\n }\n\n // invoke example function with and without optional arguments\n \n example(null, 'AA');\n\n example(null, function (err) { /* do something */ });\n\n example(null, 'AA', function (err) {});\n\n example(null, 'AAAA', 'BBBB', function (err) {});\n```\n\n### How do you determine if optionalA or optionalB is intended?\n\nDesign your function to require optionalA in order to accept optionalB\n"},"2016-05-12-make-easy-loop-on-array.md":{"name":"2016-05-12-make-easy-loop-on-array.md","sha":"b4f16213ced8afb02f387551061aecd6d166408d","content":"---\nlayout: post\n\ntitle: Create an easy loop using an array\ntip-number: 55\ntip-username: jamet-julien\ntip-username-profile: https://github.com/jamet-julien\ntip-tldr: Sometimes, we need to loop endlessly over an array of items, like a carousel of images or an audio playlist. Here’s how to take an array and give it “looping powers” \n\nredirect_from:\n - /en/make-easy-loop-on-array/\n\ncategories:\n - en\n - javascript\n---\nSometimes, we need to loop endlessly over an array of items, like a carousel of images or an audio playlist. Here's how to take an array and give it \"looping powers\":\n\n```js\nvar aList = ['A','B','C','D','E'];\n\nfunction make_looper( arr ){\n\n arr.loop_idx = 0;\n\n // return current item\n arr.current = function(){\n\n if( this.loop_idx < 0 ){// First verification\n this.loop_idx = this.length - 1;// update loop_idx\n }\n\n if( this.loop_idx >= this.length ){// second verification\n this.loop_idx = 0;// update loop_idx\n }\n\n return arr[ this.loop_idx ];//return item\n };\n \n // increment loop_idx AND return new current\n arr.next = function(){\n this.loop_idx++;\n return this.current();\n };\n // decrement loop_idx AND return new current\n arr.prev = function(){\n this.loop_idx--;\n return this.current();\n };\n}\n\n\nmake_looper( aList);\n\naList.current();// -> A\naList.next();// -> B\naList.next();// -> C\naList.next();// -> D\naList.next();// -> E\naList.next();// -> A\naList.pop() ;// -> E\naList.prev();// -> D\naList.prev();// -> C\naList.prev();// -> B\naList.prev();// -> A\naList.prev();// -> D\n```\n\nUsing the ```%``` ( Modulus ) operator is prettier.The modulus return division's rest ( ``` 2 % 5 = 1``` and ``` 5 % 5 = 0```):\n\n```js\n\nvar aList = ['A','B','C','D','E'];\n\n\nfunction make_looper( arr ){\n\n arr.loop_idx = 0;\n\n // return current item\n arr.current = function(){\n this.loop_idx = ( this.loop_idx ) % this.length;// no verification !!\n return arr[ this.loop_idx ];\n };\n\n // increment loop_idx AND return new current\n arr.next = function(){\n this.loop_idx++;\n return this.current();\n };\n \n // decrement loop_idx AND return new current\n arr.prev = function(){\n this.loop_idx += this.length - 1;\n return this.current();\n };\n}\n\nmake_looper( aList);\n\naList.current();// -> A\naList.next();// -> B\naList.next();// -> C\naList.next();// -> D\naList.next();// -> E\naList.next();// -> A\naList.pop() ;// -> E\naList.prev();// -> D\naList.prev();// -> C\naList.prev();// -> B\naList.prev();// -> A\naList.prev();// -> D\n```\n"},"2016-08-02-copy-to-clipboard.md":{"name":"2016-08-02-copy-to-clipboard.md","sha":"9e35c08199a6b5f0b498b8748885fadae13057ee","content":"---\nlayout: post\n\ntitle: Copy to Clipboard\ntip-number: 56\ntip-username: loverajoel\ntip-username-profile: https://twitter.com/loverajoel\ntip-tldr: This week I had to create a common \"Copy to Clipboard\" button, I've never created one before and I want to share how I made it.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\nredirect_from:\n - /en/copy-to-clipboard/\n\ncategories:\n - en\n - javascript\n---\n\nThis is a simple tip, this week I had to create a common \"Copy to Clipboard\" button, I've never created one before and I want to share how I made it.\nIt's easy, the bad thing is that we must add an `<input/>` with the text to be copied to the DOM. Then, we selected the content and execute the copy command with [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand).\n`execCommand('copy')` will copy the actual selected content.\n\nAlso, this command that now is [supported](http://caniuse.com/#search=execCommand) by all the latest version of browsers, allows us to execute another system commands like `copy`, `cut`, `paste`, and make changes like fonts color, size, and much more.\n\n```js\ndocument.querySelector('#input').select();\ndocument.execCommand('copy');\n```\n\n##### Playground\n<div>\n <a class=\"jsbin-embed\" href=\"http://jsbin.com/huhozu/embed?js,output\">JS Bin on jsbin.com</a><script src=\"http://static.jsbin.com/js/embed.min.js?3.39.11\"></script>\n</div>\n"},"2016-08-10-comma-operaton-in-js.md":{"name":"2016-08-10-comma-operaton-in-js.md","sha":"550391f0334962ddc1b858c9746283b0edb0199d","content":"---\nlayout: post\n\ntitle: Comma operator in JS\ntip-number: 57\ntip-username: bhaskarmelkani\ntip-username-profile: https://www.twitter.com/bhaskarmelkani\ntip-tldr: When placed in an expression, it evaluates every expression from left to right and returns the last one.\n\nredirect_from:\n - /en/comma-operaton-in-js/\n\ncategories:\n - en\n - javascript\n---\nApart from being just a delimiter, the comma operator allows you to put multiple statements in a place where one statement is expected.\nEg:-\n\n```js\nfor(var i=0, j=0; i<5; i++, j++, j++){\n console.log(\"i:\"+i+\", j:\"+j);\n}\n```\n\nOutput:-\n\n```js\ni:0, j:0\ni:1, j:2\ni:2, j:4\ni:3, j:6\ni:4, j:8\n```\n\nWhen placed in an expression, it evaluates every expression from left to right and returns the right most expression.\n\nEg:-\n\n```js\nfunction a(){console.log('a'); return 'a';} \nfunction b(){console.log('b'); return 'b';} \nfunction c(){console.log('c'); return 'c';}\n\nvar x = (a(), b(), c());\n\nconsole.log(x); // Outputs \"c\"\n```\nOutput:-\n\n```js\n\"a\"\n\"b\"\n\"c\"\n\n\"c\"\n```\n\n* Note: The comma(`,`) operator has the lowest priority of all javascript operators, so without the parenthesis the expression would become: `(x = a()), b(), c();`.\n\n##### Playground\n<div>\n <a class=\"jsbin-embed\" href=\"http://jsbin.com/vimogap/embed?js,console\">JS Bin on jsbin.com</a><script src=\"http://static.jsbin.com/js/embed.min.js?3.39.11\"></script>\n</div>\n"},"2016-08-17-break-continue-loop-functional.md":{"name":"2016-08-17-break-continue-loop-functional.md","sha":"38a8e48abad521b44608f81e38b04f80a614d164","content":"---\nlayout: post\n\ntitle: Breaking or continuing loop in functional programming\ntip-number: 58\ntip-username: vamshisuram\ntip-username-profile: https://github.com/vamshisuram\ntip-tldr: A common task for us is iterate over a list looking for a value or values, but we can't return from inside a loop so we will have to iterate the whole array, even if the item we search is the first in the list, in this tip we will see how to short circuit with `.some` and `.every`.\n\n\nredirect_from:\n - /en/break-continue-loop-functional/\n\ncategories:\n - en\n - javascript\n---\n\n\nA common requirement of iteration is cancelation. Using `for` loops we can `break` to end iteration early.\n\n```javascript\nconst a = [0, 1, 2, 3, 4];\nfor (var i = 0; i < a.length; i++) {\n if (a[i] === 2) {\n break; // stop the loop\n }\n console.log(a[i]);\n}\n//> 0, 1\n```\n\nAnother common requirement is to close over our variables.\n\nA quick approach is to use `.forEach` but\nthen we lack the ability to `break`. In this situation the closest we get is `continue` functionality through `return`.\n\n```javascript\n[0, 1, 2, 3, 4].forEach(function(val, i) {\n if (val === 2) {\n // how do we stop?\n return true;\n }\n console.log(val); // your code\n});\n//> 0, 1, 3, 4\n```\n\nThe `.some` is a method on Array prototype. It tests whether some element in the array passes the test implemented by the provided function. If any value is returning true, then it stops executing. Here is a [MDN link](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some) for more details.\n\nAn example quoted from that link\n\n```javascript\nconst isBiggerThan10 = numb => numb > 10;\n\n[2, 5, 8, 1, 4].some(isBiggerThan10); // false\n[12, 5, 8, 1, 4].some(isBiggerThan10); // true\n```\n\nUsing `.some` we get iteration functionally similar to `.forEach` but with the ability to `break` through `return` instead.\n\n```javascript\n[0, 1, 2, 3, 4].some(function(val, i) {\n if (val === 2) {\n return true;\n }\n console.log(val); // your code\n});\n//> 0, 1\n```\n\n\nYou keep returning `false` to make it `continue` to next item. When you return `true`, the loop will `break` and `a.some(..)` will `return` `true`.\n\n```javascript\n// Array contains 2\nconst isTwoPresent = [0, 1, 2, 3, 4].some(function(val, i) {\n if (val === 2) {\n return true; // break\n }\n});\nconsole.log(isTwoPresent);\n//> true\n```\n\nAlso there is `.every`, which can be used. We have to return the opposite boolean compared to `.some`.\n\n##### Playground\n<div>\n <a class=\"jsbin-embed\" href=\"http://jsbin.com/jopeji/embed?js,console\">JS Bin on jsbin.com</a><script src=\"http://static.jsbin.com/js/embed.min.js?3.39.11\"></script>\n</div>\n"},"2016-08-25-keyword-var-vs-let.md":{"name":"2016-08-25-keyword-var-vs-let.md","sha":"59122ed33b79bf3a6ec7d38f5ed46a39ebb027e4","content":"---\nlayout: post\n\ntitle: ES6, var vs let\ntip-number: 59\ntip-username: richzw\ntip-username-profile: https://github.com/richzw\ntip-tldr: In this tip, I will introduce the block-scope difference between keyword var and let. Should I replace var by let? let's take a look\n\n\nredirect_from:\n - /en/keyword-var-vs-let/\n\ncategories:\n - en\n - javascript\n---\n\n### Overview\n\n- The scope of a variable defined with `var` is function scope or declared outside any function, global.\n- The scope of a variable defined with `let` is block scope.\n\n```js\nfunction varvslet() {\n console.log(i); // i is undefined due to hoisting\n // console.log(j); // ReferenceError: j is not defined\n\n for( var i = 0; i < 3; i++ ) {\n console.log(i); // 0, 1, 2\n };\n\n console.log(i); // 3\n // console.log(j); // ReferenceError: j is not defined\n\n for( let j = 0; j < 3; j++ ) {\n console.log(j);\n };\n\n console.log(i); // 3\n // console.log(j); // ReferenceError: j is not defined\n}\n```\n\n### Difference Details\n\n- Variable Hoisting\n\n `let` will not hoist to the entire scope of the block they appear in. By contrast, `var` could hoist as below.\n\n```js\n{\n console.log(c); // undefined. Due to hoisting\n var c = 2;\n}\n\n{\n console.log(b); // ReferenceError: b is not defined\n let b = 3;\n}\n```\n\n- Closure in Loop\n\n `let` in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration, so it can be used to avoid issue with closures.\n\n```js\nfor (var i = 0; i < 5; ++i) {\n setTimeout(function () {\n console.log(i); // output '5' 5 times\n }, 100); \n}\n```\n\n After replacing `var` with `let`\n \n```js\n// print 1, 2, 3, 4, 5\nfor (let i = 0; i < 5; ++i) {\n setTimeout(function () {\n console.log(i); // output 0, 1, 2, 3, 4 \n }, 100); \n}\n```\n\n\n### Should I replace `var` with `let`?\n\n> NO, `let` is the new block scoping `var`. That statement emphasizes that `let` should replace `var` only when `var` was already signaling\nblock scoping stylistically. Otherwise, leave `var` alone. `let` improves scoping options in JS, not replaces. `var` is still a useful signal for variables that are used throughout the function. \n\n### `let` compatibility\n\n- In server side, such as Node.js, you can safely use the `let` statement now.\n \n- In client side, through a transpiler (like [Traceur](https://github.com/google/traceur-compiler)), you can safely use the `let` statement. Otherwise, please consider the browser support [here](http://caniuse.com/#search=let)\n\n### Playground\n<div>\n <a class=\"jsbin-embed\" href=\"http://jsbin.com/yumaye/embed?js,console\">JS Bin on jsbin.com</a><script src=\"http://static.jsbin.com/js/embed.min.js?3.39.11\"></script>\n</div>\n\n### More info\n\n- [Let keyword vs var keyword](http://stackoverflow.com/questions/762011/let-keyword-vs-var-keyword)\n- [For and against let](https://davidwalsh.name/for-and-against-let)\n- [Explanation of `let` and block scoping with for loops](http://stackoverflow.com/questions/30899612/explanation-of-let-and-block-scoping-with-for-loops/30900289#30900289)."},"2016-10-28-three-useful-hacks.md":{"name":"2016-10-28-three-useful-hacks.md","sha":"cc36dab772d00d5ff67ee3236fe084534cb6bb00","content":"---\nlayout: post\n\ntitle: Three useful hacks\ntip-number: 60\ntip-username: leandrosimoes \ntip-username-profile: https://github.com/leandrosimoes\ntip-tldr: Three very useful and syntax sugar hacks to speed up your development.\n\n\nredirect_from:\n - /en/three-useful-hacks/\n\ncategories:\n - en\n - javascript\n---\n\n#### Getting array items from behind to front\n\nIf you want to get the array items from behind to front, just do this:\n\n```javascript\nvar newArray = [1, 2, 3, 4];\n\nconsole.log(newArray.slice(-1)); // [4]\nconsole.log(newArray.slice(-2)); // [3, 4]\nconsole.log(newArray.slice(-3)); // [2, 3, 4]\nconsole.log(newArray.slice(-4)); // [1, 2, 3, 4]\n```\n\n#### Short-circuits conditionals\n\nIf you have to execute a function just if a condition is `true`, like this:\n\n```javascript\nif(condition){\n dosomething();\n}\n```\n\nYou can use a short-circuit just like this:\n\n```javascript\ncondition && dosomething();\n```\n\n\n#### Set variable default values using \"||\"\n\n\nIf you have to set a default value to variables, you can simple do this:\n\n```javascript\nvar a;\n\nconsole.log(a); //undefined\n\na = a || 'default value';\n\nconsole.log(a); //default value\n\na = a || 'new value';\n\nconsole.log(a); //default value\n```"},"2017-01-19-binding-objects-to-functions.md":{"name":"2017-01-19-binding-objects-to-functions.md","sha":"7ebb8ba3e15eb1005a1bec7819b4736a2a268d54","content":"---\nlayout: post\n\ntitle: Binding objects to functions\ntip-number: 61\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Understanding how to use `Bind` method with objects and functions in JavaScript\n\n\nredirect_from:\n - /en/binding-objects-to-functions/\n\ncategories:\n - en\n - javascript\n---\n\nMore than often, we need to bind an object to a function’s this object. JS uses the bind method when this is specified explicitly and we need to invoke desired method.\n\n### Bind syntax\n\n```js\nfun.bind(thisArg[, arg1[, arg2[, ...]]])\n```\n\n## Parameters\n**thisArg**\n\n`this` parameter value to be passed to target function while calling the `bound` function.\n\n**arg1, arg2, ...**\n\nPrepended arguments to be passed to the `bound` function while invoking the target function.\n\n**Return value**\n\nA copy of the given function along with the specified `this` value and initial arguments.\n\n### Bind method in action in JS\n\n```js\nconst myCar = {\n brand: 'Ford',\n type: 'Sedan',\n color: 'Red'\n};\n\nconst getBrand = function () {\n console.log(this.brand);\n};\n\nconst getType = function () {\n console.log(this.type);\n};\n\nconst getColor = function () {\n console.log(this.color);\n};\n\ngetBrand(); // object not bind,undefined\n\ngetBrand(myCar); // object not bind,undefined\n\ngetType.bind(myCar)(); // Sedan\n\nlet boundGetColor = getColor.bind(myCar);\nboundGetColor(); // Red\n\n```"},"2017-03-07-preventing-unwanted-scopes-creation-in-angularjs.md":{"name":"2017-03-07-preventing-unwanted-scopes-creation-in-angularjs.md","sha":"55d989715b6222100f0e0c06ccc8063b8063db11","content":"---\nlayout: post\n\ntitle: Preventing Unwanted Scopes Creation in AngularJs\ntip-number: 62\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: In this tip I am going to show how to pass data between scopes preventing unwanted scopes created by `ng-repeat` and `ng-if`\ntip-writer-support: https://www.coinbase.com/loverajoel\n\ncategories:\n - en\n - angular\n---\n\nOne of the most appreciated features of AngularJs is thUnderstanding and preventing ```ng-model``` data scope is one of the main challenge you get quite often.\nWhile working with ```ng-model``` data, new unwanted scope can be created by ```ng-repeat``` or ```ng-if``` procedures.\nTake a look on following example-\n\n\n```js\n<div ng-app>\n <input type=\"text\" ng-model=\"data\">\n <div ng-repeat=\"i in [1]\">\n <input type=\"text\" ng-model=\"data\"><br/>\n innerScope:{{data}}\n </div>\n outerScope:{{data}}\n</div>\n```\n\nIn the above example, ```innerScope``` inherits from ```outerScope``` and pass the value in ```outerScope```.\nIf you input a value in ```innerScope``` it will reflect in ```outerScope```. But if you edit ```outerScope```,\n```innerScope``` doesn’t reflect the same value as ```outerScope``` because ```innerScope``` creates its own field\nso no longer inherits from ```outerScope```.\n\nTo prevent this to happen we can use “Controller As” approach instead of using scope as a container\nfor all data and functions. But one more catchy solution is to keep everything in objects as shown is below example- \n\n\n```js\n<div ng-app>\n <input type=\"text\" ng-model=\"data.text\">\n <div ng-repeat=\"i in [1]\">\n <input type=\"text\" ng-model=\"data.text\"><br/>\n inner scope:{{data.text}}\n </div>\n outer scope:{{data.text}}\n</div>\n```\n\nNow ```innerScope``` is no longer creates a new field and editing value in either ```innerScope``` or ```outerScope``` will\nreflect in both ```innerScope``` and ```outerScope```.\n"},"2017-03-09-working-with-websocket-timeout.md":{"name":"2017-03-09-working-with-websocket-timeout.md","sha":"152ed3799e9f194efcb9dde56483a8a5f9275307","content":"---\nlayout: post\n\ntitle: Working With Websocket Timeout\ntip-number: 63\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: A trick to control the timeout\n\ncategories:\n - en\n - javascript\n---\n\nIn case of established websocket connection, server or firewall could timeout and terminate the connection after a period of inactivity. To deal with this situation, we send periodic message to the server. To control the timeout we will add two functions in our code : one to make sure connection keep alive and another one to cancel the keep alive. Also we need a common ```timerID``` variable.\nLet’s have a look on implementation-\n\n```js\nvar timerID = 0; \nfunction keepAlive() { \n var timeout = 20000; \n if (webSocket.readyState == webSocket.OPEN) { \n webSocket.send(''); \n } \n timerId = setTimeout(keepAlive, timeout); \n} \nfunction cancelKeepAlive() { \n if (timerId) { \n clearTimeout(timerId); \n } \n}\n```\n\nNow as we have both of our desired function for the task, we will place ```keepAlive()``` function at the end of ```onOpen()``` method of websocket connection and ```cancelKeepAlive()``` function at the end of ```onClose()``` method of websocket connection. \n\nYes! We have perfectly implemented hack for websocket timeout problem.\n"},"2017-03-12-3-array-hacks.md":{"name":"2017-03-12-3-array-hacks.md","sha":"bd94677701ad184373242db4d4c37fb2e13db353","content":"---\nlayout: post\n\ntitle: 3 Array Hacks\ntip-number: 64\ntip-username: hassanhelfi\ntip-username-profile: https://twitter.com/hassanhelfi\ntip-tldr: Arrays are everywhere and with the new spread operators introduced in ECMAScript 6, you can do awesome things with them. In this post I will show you 3 useful tricks you can use when programming.\n\n\ncategories:\n - en\n - javascript\n---\n\nArrays are everywhere in JavaScript and with the new [spread operators](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator) introduced in ECMAScript 6, you can do awesome things with them. In this post I will show you 3 useful tricks you can use when programming.\n\n### 1. Iterating through an empty array\n\nJavaScript arrays are sparse in nature in that there are a lot of holes in them. Try creating an array using the Array’s constructor and you will see what I mean.\n\n```javascript\n> const arr = new Array(4);\n[undefined, undefined, undefined, undefined]\n```\n\nYou may find that iterating over a sparse array to apply a certain transformation is hard.\n\n```javascript\n> const arr = new Array(4);\n> arr.map((elem, index) => index);\n[undefined, undefined, undefined, undefined]\n```\n\nTo solve this, you can use `Array.apply` when creating the array.\n\n```javascript\n> const arr = Array.apply(null, new Array(4));\n> arr.map((elem, index) => index);\n[0, 1, 2, 3]\n```\n\n### 2. Passing an empty parameter to a method\n\nIf you want to call a method and ignore one of its parameters, then JavaScript will complain if you keep it empty.\n\n```javascript\n> method('parameter1', , 'parameter3');\nUncaught SyntaxError: Unexpected token ,\n```\n\nA workaround that people usually resort to is to pass either `null` or `undefined`.\n\n```javascript\n> method('parameter1', null, 'parameter3') // or\n> method('parameter1', undefined, 'parameter3');\n```\n\nI personally don’t like using `null` since JavaScript treats it as an object and that’s just weird. With the introduction of spread operators in ES6, there is a neater way of passing empty parameters to a method. As previously mentioned, arrays are sparse in nature and so passing empty values to it is totally okay. We'll use this to our advantage.\n\n```javascript\n> method(...['parameter1', , 'parameter3']); // works!\n```\n\n### 3. Unique array values\n\nI always wonder why the Array constructor does not have a designated method to facilitate the use of unique array values. Spread operators are here for the rescue. Use spread operators with the `Set` constructor to generate unique array values.\n\n```javascript\n> const arr = [...new Set([1, 2, 3, 3])];\n[1, 2, 3]\n```\n"},"2017-03-16-tapping-for-quick-debugging.md":{"name":"2017-03-16-tapping-for-quick-debugging.md","sha":"42bf82ef97f58ac3b4528074c03c8d33610bcfae","content":"---\nlayout: post\n\ntitle: Tapping for quick debugging\ntip-number: 65\ntip-username: loverajoel\ntip-username-profile: https://twitter.com/loverajoel\ntip-tldr: This little beastie here is tap. A really useful function for quick-debugging chains of function calls, anonymous functions and, actually, whatever you just want to print.\ntip-md-link: https://github.com/loverajoel/jstips/blob/master/_posts/en/javascript/2017-03-16-tapping-for-quick-debugging.md\n\ncategories:\n - en\n - javascript\n---\n\nThis little beastie here is tap. A really useful function for quick-debugging\nchains of function calls, anonymous functions and, actually, whatever you just\nwant to print.\n\n``` javascript\nfunction tap(x) {\n console.log(x);\n return x;\n}\n```\n\nWhy would you use instead of good old `console.log`? Let me show you an example:\n\n``` javascript\nbank_totals_by_client(bank_info(1, banks), table)\n .filter(c => c.balance > 25000)\n .sort((c1, c2) => c1.balance <= c2.balance ? 1 : -1 )\n .map(c =>\n console.log(`${c.id} | ${c.tax_number} (${c.name}) => ${c.balance}`));\n```\n\nNow, suppose you're getting nothing from this chain (possibly an error).\nWhere is it failing? Maybe `bank_info` isn't returning anything, so we'll tap it:\n\n``` javascript\nbank_totals_by_client(tap(bank_info(1, banks)), table)\n```\n\nDepending on our particular implementation, it might print something or not.\nI'll assume the information that we got from our tapping was correct and\ntherefore, bank_info isn't causing anything.\n\nWe must then move on to the next chain, filter.\n\n``` javascript\n .filter(c => tap(c).balance > 25000)\n```\n\nAre we receiving any c's (clients actually)? If so, then bank_totals_by_client\nworks alright. Maybe it's the condition within the filter?\n\n``` javascript\n .filter(c => tap(c.balance > 25000))\n```\n\nAh! Sweet, we see nothing but `false` printed, so there's no client with >25000,\nthat's why the function was returning nothing.\n\n## (Bonus) A more advanced tap.\n\n``` javascript\nfunction tap(x, fn = x => x) {\n console.log(fn(x));\n return x;\n}\n```\n\nNow we're talking about a more advanced beast, what if we wanted to perform a\ncertain operation *prior* to tapping? i.e, we want to access a certain object\nproperty, perform a logical operation, etc. with our tapped object? Then we\ncall old good tap with an extra argument, a function to be applied at the moment\nof tapping.\n\n\n``` javascript\ntap(3, x => x + 2) === 3; // prints 5, but expression evaluates to true, why :-)?\n```\n"},"2017-03-27-state-to-props-maps-with-memory.md":{"name":"2017-03-27-state-to-props-maps-with-memory.md","sha":"fbf5410c77c1b00a629de7606e3ae4f740704a4d","content":"---\nlayout: post\n\ntitle: State to Props maps with memory\ntip-number: 66\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: You've been building your React apps with a Redux store for quite a while, yet you feel awkward when your components update so often. You've crafted your state thoroughly, and your architecture is such that each component gets just what it needs from it, no more no less. Yet, they update behind your back. Always mapping, always calculating.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\ncategories:\n - en\n - react\n---\n\nYou've been building your React apps with a Redux store for quite a while,\nyet you feel awkward when your components update so often. You've crafted\nyour state thoroughly, and your architecture is such that each component\ngets just what it needs from it, no more no less. Yet, they update behind\nyour back. Always mapping, always calculating.\n\n## Reselector to the rescue\n\nHow could would it be if you could just calculate what you need? If this\npart of the state tree changes, then yes, please, update this.\n\nLet's take a look at the code for a simple TODOs list with a visibility filter,\nspecially the part in charge of getting the visible TODOs in our container\ncomponent:\n\n\n```javascript\nconst getVisibleTodos = (todos, filter) => {\n switch (filter) {\n case 'SHOW_ALL':\n return todos\n case 'SHOW_COMPLETED':\n return todos.filter(t => t.completed)\n case 'SHOW_ACTIVE':\n return todos.filter(t => !t.completed)\n }\n}\n\nconst mapStateToProps = (state) => {\n return {\n todos: getVisibleTodos(state.todos, state.visibilityFilter)\n }\n}\n```\n\nEach time our component is updated, this needs be recalculated again. Reselector\nactually allows us to give our `getVisibleTodos` function memory. So it knows\nwhether the parts of the state we need have changed. If they have, it will\nproceed, if they haven't, it will just return the last result.\n\n\nLet's bring selectors!\n\n```javascript\nconst getVisibilityFilter = (state) => state.visibilityFilter\nconst getTodos = (state) => state.todos\n```\n\nNow that we can *select* which parts of the state we want to keep track of,\nwe're ready to give memory to getVisibleTodos\n\n```javascript\nimport {createSelector} from 'reselect'\n\nconst getVisibleTodos = createSelector(\n [getVisibilityFilter, getTodos],\n (visibilityFilter, todos) => {\n switch (visibilityFilter) {\n case 'SHOW_ALL':\n return todos\n case 'SHOW_COMPLETED':\n return todos.filtler(t => t.completed)\n case 'SHOW_ACTIVE':\n return todos.filter(t => !t.completed)\n }\n }\n)\n```\n\nAnd change our map to give the full state to it:\n\n```javascript\nconst mapStateToProps = (state) => {\n return {\n todos: getVisibleTodos(state)\n }\n}\n```\n\nAnd that's it! We've given memory to our function. No extra calculations if\nthe involved parts of the state haven't changed!"},"2017-03-29-recursion-iteration-and-tail-calls-in-js.md":{"name":"2017-03-29-recursion-iteration-and-tail-calls-in-js.md","sha":"ea8089795847c55d9480f44575c36c8bb0b95dc2","content":"---\nlayout: post\n\ntitle: Recursion, iteration and tail calls in JS\ntip-number: 67\ntip-username: loverajoel\ntip-username-profile: https://twitter.com/loverajoel\ntip-tldr: If you've been on the business for some time, you have, most likely, come across the definition of recursion, for which the factorial of a given number `n! = n * n - 1 * ... * 1` is a standard example...\ntip-md-link: https://github.com/loverajoel/jstips/blob/master/_posts/en/javascript/2017-03-29-recursion-iteration-and-tail-calls-in-js.md\n\ncategories:\n - en\n - javascript\n---\n\nIf you've been on the business for some time, you have, most likely,\ncome across the definition of recursion, for which the factorial of\na given number `n! = n * (n - 1) * ... * 1` is a standard example.\n\n``` javascript\nfunction factorial(n) {\n if (n === 0) {\n return 1;\n }\n return n * factorial(n - 1);\n}\n```\n\nThe example shown above is but the most naive implementation of the\nfactorial function.\n\nFor the sake of completeness, let's look at how this executes for\n`n = 6`:\n\n- factorial(6)\n - 6 * factorial(5)\n - 5 * factorial (4)\n - 4 * factorial(3)\n - 3 * factorial(2)\n - 2 * factorial(1)\n - 1 * factorial(0)\n - 1\n - (resuming previous execution) 1 * 1 = 1\n - (resuming...) 2 * 1 = 2\n - (...) 3 * 2 = 6\n - ... 4 * 6 = 24\n - 5 * 24 = 120\n - 6 * 120 = 720\n- factorial(6) = 720\n\nNow, we must be very cautious as to what's happening so we can understand\nwhat is to come next.\n\nWhen we invoke a function, several things happen at once. The location to\nwhich we must return to after calling the function is saved, along with\nthe information of the current frame (i.e, the value of n). Then space is\nallocated for the new function and a new frame is born.\n\nThis goes on and on, we keep stacking these frames and then we unwind that\nstack, replacing function calls with values returned by them.\n\nAnother thing to notice is the shape of the process generated by our function.\nYou might not be surprised if I call this shape *recursive*. We have, thus, a\n*recursive process*.\n\nLet's take a look at a second implementation of this function.\n\n``` javascript\nfunction factorial(n, res) {\n if (n === 0) {\n return res;\n }\n return factorial(n - 1, res * n);\n}\n```\n\nWe can encapsulate functionality a bit further by defining an inner function.\n\n``` javascript\nfunction factorial(n) {\n function inner_factorial(n, res) {\n if (n === 0) {\n return res;\n }\n return inner_factorial(n - 1, res * n);\n }\n return inner_factorial(n, 1);\n}\n```\n\nLet's take a look at how this gets executed:\n\n- factorial(6)\n - inner anonymous function (iaf) gets called with (n = 6, res = 1)\n - iaf(5, 1 * 6)\n - iaf(4, 6 * 5)\n - iaf(3, 30 * 4)\n - iaf(2, 120 * 3)\n - iaf(1, 360 * 2)\n - iaf(0, 720)\n - 720\n - 720\n - 720\n - 720\n - 720\n - 720\n - 720\n - iaf (6, 1) = 720\n- factorial(6) = 720\n\nYou might notice that we didn't need to perform any calculation after unwinding\nthe stack. We just returned a value. But, according to our rules, we had to save\nthe state as a stack frame, even if it weren't of any use later in the chain.\n\nOur rules, however, are not applied to every language out there. In fact, in\nScheme it's mandatory for such chains to be optimized with tail call\noptimization. This ensures that our stack is not filled with unnecessary frames.\nOur previous calculation would look, thus, this way:\n\n- factorial(6)\n- iaf(6, 1)\n- iaf(5, 6)\n- iaf(4, 30)\n- iaf(3, 120)\n- iaf(2, 360)\n- iaf(1, 720)\n- iaf(0, 720)\n- 720\n\nWhich in turns, looks an awfully lot like\n\n``` javascript\nres = 1;\nn = 6;\n\nwhile(n > 1) {\n res = res * n;\n n--;\n}\n```\n\nThis means, we actually have an *iterative process*, even if we're using\nrecursion. How cool is that?\n\nThe good news is, this is a feature in ES6. As long as your recursive call\nis in tail position and your function has strict mode, tail call optimization\nwill kick in and save you from having a `maximum stack size exceeded` error.\n\nUPDATE Dec 1, 2017:\nThe only major browser with tail call optimization is Safari.<sup id=\"a1\">1</sup> V8 has an implentation<sup>2</sup> but has not shipped it yet<sup>3</sup> for the reasons listed.\n\n1: https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)\n\n2: https://bugs.chromium.org/p/v8/issues/detail?id=4698\n\n3: https://v8project.blogspot.com/2016/04/es6-es7-and-beyond.html\n \n"},"2017-04-03-why-you-should-use-Object.is()-in-equality-comparison.md":{"name":"2017-04-03-why-you-should-use-Object.is()-in-equality-comparison.md","sha":"85656a244a5d9ba8a6d071f1198cc2a690299aa1","content":"---\nlayout: post\n\ntitle: Why you should use Object.is() in equality comparison \ntip-number: 68\ntip-username: TarekAlQaddy\ntip-username-profile: https://github.com/TarekAlQaddy\ntip-tldr: A good solution for the looseness of equality comparisons in javascript \n\ncategories:\n - en\n - javascript\n---\n\nWe all know that JavaScript is loosely typed and in some cases it fall behind specially when it comes to quality comparison with '==', comparing with '==' gives unexpected results due to whats called coercion or casting \"converting one of the 2 operands to the other's type then compare\".\n\n``` javascript\n0 == ' ' //true\nnull == undefined //true\n[1] == true //true\n```\n\nSo they provided us with the triple equal operator '===' which is more strict and does not coerce operands, However comparing with '===' is not the best solution you can get:\n\n``` javascript\nNaN === NaN //false\n```\n\nThe great news that in ES6 there is the new 'Object.is()' which is better and more precise it has the same features as '===' and moreover it behaves well in some special cases:\n\n``` javascript\nObject.is(0 , ' '); //false\nObject.is(null, undefined); //false\nObject.is([1], true); //false\nObject.is(NaN, NaN); //true\n```\n\nMozilla team doesn't think that Object.is is \"stricter\" than '===' they say that we should think of how this method deal with NaN, -0 and +0 but overall I think it is now a good practice in real applications.\n\nNow this table illustrates..\n\n![differences of operators in equality comparisons javascript](http://i.imgur.com/pCyqkLc.png)\n\n## References:\n[Equality comparisons and sameness](http://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)\n\n"},"2017-04-04-enhancing-react-components-composition.md":{"name":"2017-04-04-enhancing-react-components-composition.md","sha":"3ff1cdec1aa1491c7dfc4d71532d7f01b15cb80f","content":"---\nlayout: post\n\ntitle: Enhancing React components, Composition\ntip-number: 69\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: React is extremely flexible in terms of how you can structure your components, but this pattern will make your apps more efficient.\ntip-writer-support: https://www.coinbase.com/loverajoel\n\ncategories:\n - en\n - react\n---\n\n> At Facebook, we use React in thousands of components, and we haven't found any\n> use cases where we would recommend creating component inheritance hierarchies.\n\n*Long live to composition, inheritance is dead.*\n\nSo, how do you *extend* a component in React?\n\nWell, it's pretty obvious that the guys @Facebook consider inappropriate to\ninherit from parent components. Let's look at alternatives:\n\n## Planning ahead of time\nThere might be some cases where you have a component which can't know what its\nchildren will be ahead of time (like most of us). For them, React gifts\n`props.children`:\n\n``` javascript\nfunction List(props) {\n return (\n <ul className={'List List-' + props.importance}>\n {props.children}\n </ul>\n );\n}\n\nfunction DownloadMenu() {\n return (\n <List importance=\"High\">\n <li>Download SBCL</li>\n <li>Download Racket</li>\n <li>Download Haskell</li>\n </List>\n );\n}\n```\n\nAs we can see, `props.children` receives everything that's in between the\ncomponent's open and closing tag.\n\nFurthermore, we can exploit `props` to fill voids:\n\n``` javascript\nfunction ListWithHeader(props) {\n return (\n <ul className={'List List-' + props.importance}>\n <li className=\"List List-Header\">\n {props.header}\n </li>\n {props.children}\n </ul>\n );\n}\n\nfunction DownloadMenuWithHeader() {\n return (\n <List importance=\"High\" header={ <LispLogo /> }>\n <li>Download SBCL</li>\n ...\n </List>\n );\n}\n```\n\n## Generic components and specialization\nSo, we've got this great *FolderView* component\n\n``` javascript\nfunction FolderView(props) {\n return (\n <div className=\"FolderView\">\n <h1>{props.folderName}</h1>\n <ul className=\"FolderView FolderView-Actions\">\n {props.availableActions}\n </ul>\n <ul className=\"FolderView FolderView-Files\">\n {props.files}\n </ul>\n </div>\n );\n}\n```\nThis could represent any folder in our filesystem, however, we only want to\n*specialize* it so it shows only the Pictures and Desktop folders.\n\n``` javascript\nfunction DesktopFolder(props) {\n return (\n <FolderView folderName=\"Desktop\"\n availableActions={\n <li>Create Folder</li>\n <li>Create Document</li>\n }\n files={props.files}\n />\n );\n}\n\nfunction PicturesFolder(props) {\n return (\n <FolderView\n folderName=\"Pictures\"\n availableActions={\n <li>New Picture</li>\n }\n files={props.files}\n />\n );\n}\n```\n\nAnd just like so, we've *specialized* our component, without creating any\ninheritance hierarchy!"},"2017-04-05-picking-and-rejecting-object-properties.md":{"name":"2017-04-05-picking-and-rejecting-object-properties.md","sha":"80a3dd348937943b0fcfb264b15de1cb812fae96","content":"---\nlayout: post\n\ntitle: Picking and rejecting object properties \ntip-number: 70\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Sometimes we need to whitelist certain attributes from an object, say we've got an array representation of a database table and we need to `select` just a few fields for some function.\n\ncategories:\n - en\n - javascript\n---\n\n\nSometimes we need to whitelist certain attributes from an object, say we've\ngot an array representation of a database table and we need to `select` just\na few fields for some function:\n\n``` javascript\nfunction pick(obj, keys) {\n return keys.map(k => k in obj ? {[k]: obj[k]} : {})\n .reduce((res, o) => Object.assign(res, o), {});\n}\n\nconst row = {\n 'accounts.id': 1,\n 'client.name': 'John Doe',\n 'bank.code': 'MDAKW213'\n};\n\nconst table = [\n row,\n {'accounts.id': 3, 'client.name': 'Steve Doe', 'bank.code': 'STV12JB'}\n];\n\npick(row, ['client.name']); // Get client name\n\ntable.map(row => pick(row, ['client.name'])); // Get a list of client names\n```\n\nThere's a bit of skulduggery going on in pick. First, we `map` a function over\nthe keys that will return, each time, an object with only the attribute pointed\nby the current key (or an empty object if there's no such attribute in the\nobject). Then, we `reduce` this collection of single-attribute objects by\nmerging the objects.\n\nBut what if we want to `reject` the attributes? Well, the function changes a bit\n\n``` javascript\nfunction reject(obj, keys) {\n return Object.keys(obj)\n .filter(k => !keys.includes(k))\n .map(k => Object.assign({}, {[k]: obj[k]}))\n .reduce((res, o) => Object.assign(res, o), {});\n}\n\n// or, reusing pick\nfunction reject(obj, keys) {\n const vkeys = Object.keys(obj)\n .filter(k => !keys.includes(k));\n return pick(obj, vkeys);\n}\n\nreject({a: 2, b: 3, c: 4}, ['a', 'b']); // => {c: 4}\n```"},"2017-04-10-adventurers-guide-to-react.md":{"name":"2017-04-10-adventurers-guide-to-react.md","sha":"7754db5acfc59031b82e0b6837da753047512927","content":"---\nlayout: post\n\ntitle: Adventurers Guide to React (Part I)\ntip-number: 72\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: So you've heard of this *React* thing, and you actually peeked at the docs, maybe even went through some of the pages. Then you suddenly came across mysterious runes that spelled somewhat along the lines of Webpack, Browserify, Yarn, Babel, NPM and yet much more.\n\ncategories:\n - en\n - react\n---\n\n> I used to be an adventurer like you, but then I took a RTFM in the knee...\n>\n> Guard outside of Castle Reducer in the Land of React\n\nSo you've heard of this *React* thing, and you actually peeked at the docs,\nmaybe even went through some of the pages. Then you suddenly came across\nmysterious runes that spelled somewhat along the lines of Webpack, Browserify,\nYarn, Babel, NPM and yet much more.\n\n\nThus, you went to their official sites and went through the docs, just to find\nyourself lost in the ever growing collection of modern tools (tm) to build\nweb applications with JS.\n\n\nAfraid you must be not.\n\n## Yarn, NPM\nThey are just dependency managers, nothing to be afraid of. In fact, they are\nthe less scary part. If you've ever used a GNU/Linux distro, FreeBSD, Homebrew\non MacOSX, Ruby and Bundler, Lisp and Quicklisp just to name a few, you'll be\nfamiliar with the concept.\n\n\nShould you not be, it's a very simple thing, so don't worry. The Land of React\nis but a province in a much bigger world, which some call Javascript and others\nEcmascript (JS/ES for short).\n\n\nNow suppose you are starting your own town, but you really want to use React's\ntools for your buildings, because, let's face it, it is popular. The traditional\nway would be to walk to the Land of React and ask the ruler to handle you some\nof his tools. The problem is you waste time, and you must keep contact with him\nso if any tools is faulty, you get a new one.\n\n\nHowever, with the advent of drones and near-instant travel for them, some smart\nguys started a registry of the different towns, cities and provinces. Furthermore,\nthey built especial drones that could deliver the tools right to you.\n\n\nNowadays, to require React in your project, you just have to go\n\n```bash\n$ npm init . # create town\n$ npm install --save react # get react and put the materials in the store\n```\n\n\nHandy, isn't it? and free.\n\n\n## Webpack, Browserify and friends\nIn the old times, you had to build your town all by yourself. If you wanted a\nstatue of John McCarthy you would have to fetch marble and some parentheses\non your own. This improved with the advent of *dependency managers*, which could\nfetch the marble and the parentheses for you. Yet, you had to assemble them on\nyour own.\n\n\nThen came some folks from Copy & Paste (inc) and developed some tools that allowed\nyou to copy and paste your materials on some specific order, so you could have\nyour parentheses over the statue or under it.\n\n\nThat was actually pretty cool, you just placed all the material and specified\nhow they were going to be built, and all was peaceful for a while.\n\n\nBut this approach had a problem, which I'm sure other folks tried to circumvent.\nNamely, that if you wanted to replace the parentheses by cars you would have\nto rebuild your entire town. This was no problem for small towns, but large cities\nsuffered by this approach.\n\n\nThen inspiration was given by the mighty Lord and building and module bundlers\nwere born.\n\n\nThis module bundlers allowed you to draw blueprints, and specify exactly how\nthe town was to be constructed. Furthermore, they grew quickly and supported\nonly rebuilding parts of the town, leaving the rest be.\n\n\n## Babel\nBabel is a time traveler who can bring materials from the future for you. like\nES6/7/8 features.\n\n\n## How they all mix together\nGenerally, you'll create a folder for your project, fetch dependencies, configure\nyour module bundler so it knows where to search for your code and where to output\nthe distributable. Furthermore, you may want to wire that to a development server\nso you can get instant feedback on what you're building.\n\n\nHowever, the documentation of module bundlers is a bit overwhelming. There are so\nmany choices and options for the novice adventurer that he might lose his\nmotivation.\n\n\n## create-react-app and friends\nThus yet another tool was created.\n\n```bash\n$ npm install -g create-react-app # globally install create-react-app\n$ create-react-app my-shiny-new-app\n```\n\nAnd that's all. It comes pre-configured so you don't have to go through all\nof Webpack/Browserify docs just to test React. It also brings testing scripts,\na development web server and much more.\n\n\nHowever, this is not yet the final word to our history. There exists a myriad\nof different builders and tools for React, which can be seen here\nhttps://github.com/facebook/react/wiki/Complementary-Tools"},"2017-04-06-vuejs-how-vuejs-makes-a-copy-update-replace-inside-the-data-binding.md":{"name":"2017-04-06-vuejs-how-vuejs-makes-a-copy-update-replace-inside-the-data-binding.md","sha":"d624cab979c955893782a420ce37c237635c0ea6","content":"---\nlayout: post\n\ntitle: VueJS, How VueJS makes a copy-update-replace inside the data binding.\ntip-number: 71\ntip-username: pansila \ntip-username-profile: https://github.com/pansil\ntip-tldr: In this tip, I will introduce an example to show you how it might conflict with other software.\n\ncategories:\n - en\n - more\n---\n\n### Overview\n\nVuejs is a wonderful piece of software that keeps simple yet powerful compared to other prevalent frameworks, like Angularjs and Reactjs.\nYou can quickly master it before you give up by being in awe of the framework complexity unlike them above.\n\nBut it bites you sometimes if you don't know how it works. Here is an example of the conflict with another simple and popular UI framework, Framework7.\n\n```html\n<!-- index.html -->\n<div class=\"pages\">\n <div class=\"page\" date-page=\"index\">\n <!-- load a new page -->\n <a href=\"test.html\">new page</a>\n </div>\n</div>\n\n<!-- test.html -->\n<div class=\"pages\">\n <div class=\"page\" date-page=\"test\" id=\"test\">\n <div class=\"page-content\" id=\"test1\">\n <p>{% raw %}{{content}}{% endraw %}</p>\n </div>\n </div>\n</div>\n```\n\n```js\nvar myApp = new Framework7();\nmyApp.onPageInit('test', function (page) {\n new Vue({\n el: '#test',\n data: {\n content: 'hello world'\n }\n });\n});\n```\n\nYou may be surprised that it doesn't work, nothing changed after new page loaded. In fact, Vue internally makes a copy of the target html template element and replaces the original one with the new copied one after the date binding to it. While during the page loading, Framework7 invokes the `PageInit` callback and then Vue kicks in and makes the update on the `<page>` element. Now the DOM tree has the new copied `<page>` element while Framework7 stays unconcerned and continues to perform the remaining initialization job on the old `<page>` element, like show it eventually, that's the root cause.\n\nTo work around it, don't let Vue selector targets on the `<page>` element, on its child instead. Then the copy-update-replace won't blow away the whole page anymore.\n\n```js\nvar myApp = new Framework7();\nmyApp.onPageInit('test', function (page) {\n new Vue({\n el: '#test1',\n data: {\n content: 'hello world'\n }\n });\n});\n```\n\n### More info\n\n- [Vue](https://github.com/Vuejs/Vue)\n- [Framework7](https://framework7.io/)"},"2017-04-11-protocols-for-the-brave.md":{"name":"2017-04-11-protocols-for-the-brave.md","sha":"7fe661b6b6ad016daf13cabc2ac4318609f98f18","content":"---\nlayout: post\n\ntitle: Protocols for the Brave \ntip-number: 73\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: You might have heard about the old ways gaining hype recently, and we don't mean praying to the gods of the north. Today we're introducing a feature found in Clojure which allows you to define interfaces for your classes.\n\ncategories:\n - en\n - javascript\n---\n\n\nYou might have heard about the old ways gaining hype recently, and we don't\nmean praying to the gods of the north.\n\nFunctional programming is the rediscovered toy which is bringing some sanity\nto the world of mutable state and global bindings.\n\nToday we're introducing a feature found in Clojure which allows you to define\ninterfaces for your classes. Let's look at one-off implementation:\n\n``` javascript\nconst protocols = (...ps) => ps.reduce((c, p) => p(c), Object);\n\nconst Mappable = (klass) => {\n return class extends klass {\n map() {\n throw 'Not implemented';\n }\n };\n};\n\nconst Foldable = (klass) => {\n return class extends klass {\n fold() {\n throw 'Not implemented';\n }\n };\n};\n\nclass NaturalNumbers extends protocols(Mappable, Foldable) {\n constructor() {\n super();\n this.elements = [1,2,3,4,5,6,7,8,9];\n }\n\n map (f) {\n return this.elements.map(f);\n }\n\n fold (f) {\n return this.elements.reduce(f, this.elements, 0);\n }\n}\n```\n\nYes, we're building a chain of class inheritance up there with that reduce boy.\nIt's pretty cool. We're doing it dynamically! You see, each protocol receives\na base class (Object) and extends it somehow returning the new class. The idea\nis similar to that of interfaces.\n\nWe supply method signatures for the protocol and make sure we provide\nimplementations for it on our base classes.\n\nWhat's so cool about it? We get to write things like these:\n\n``` javascript\nconst map = f => o => o.map(f);\nconst fold = f => o => o.fold(f);\nconst compose = (... fns) => fns.reduce((acc, f) => (x) => acc(f(x)), id);\n```\n\nOk, maybe we could have written those two functions without the above fuzz but,\nnow that we know `NaturalNumbers` are `Mappable`, we can call `map` on them\nand trust it will return the right result. Furthermore, with our third function,\nwe can *compose* any number of operations defined in protocols cleanly:\n\n``` javascript\nconst plus1 = x => x + 1;\nconst div5 = x => x / 5;\nconst plus_then_div = compose(map(div5), map(plus1));\nconsole.log(plus_then_div(new NaturalNumbers));\n// => [ 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2 ]\n```\n\nMore important, if we know that an object of ours is `Mappable`, we know `map`\nwill work on it. Protocols gives us an idea of what we can do with an object and\nhelp us abstract common operations between data types, thus reducing the\noverhead of dealing with a hundred functions.\n\nWhat is easier? To have a hundred functions for every different object or ten\nfunctions that work on a hundred objects?"},"2017-04-24-improving-your-async-functions-with-webworkers.md":{"name":"2017-04-24-improving-your-async-functions-with-webworkers.md","sha":"84f56d05ba0dee00fc32584350b41f8954e98457","content":"---\nlayout: post\n\ntitle: Improving your Async functions with WebWorkers\ntip-number: 74\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: JS runs in a single thread in the browser, this is the truth. In this tip I'll show you how to unleash the full power of asynchronous processing with Web Workers.\n\ncategories:\n - en\n - javascript\n---\n\n> JS shall have but one Thread (in the browser at least)\n>\n> -- Thus spoke the master programmer.\n\nJS runs in a single thread in the browser, this is the truth.\n\nSomewhere in its own universe, there exists a Queue which holds messages\nand functions associated with them.\n\nEvery time an event (i.e, a user clicks a button) is registered, there's\na runtime check to see whether there's any listener attached to that event.\nIf there's one, it will enqueue the message. Otherwise, it will be lost\nforever.\n\nNow, our event loop processes one message at a time, meaning that if you\ndo some CPU intensive operation (i.e, number crunching) this will indeed\n'block' the one Thread, rendering our application useless.\n\nThis is true even for `async` functions, which will be queued as soon as\ninvoked and executed as soon as possible (immediately given the queue is\nempty).\n\nI/O such as requests to external resources are non-blocking though, so you\ncan request a file as large as you want without fear. The associated\ncallback, however, will show the same characteristics of an `async` function.\n\nStrategies for processing lots of data vary a lot. You could partition data\nand set timeouts for processing bits of it a time for example. But to unleash\nthe full power of asynchronous processing, you should use Web Workers.\n\nTo do so, you separate the processing part in a different file (possibly\n'my_worker.js'), create a worker with `newWorker = new Worker('my_worker.js');`\nand offload the processing to it.\n\n``` javascript\n// my_worker.js\nconst do_a_lot_of_processing = (data) => {\n ....\n}\n\nonmessage = (e) => {\n postMessage(do_a_lot_of_processing(e.data));\n}\n\n// main.js\nconst myWorker = new Worker('my_worker.js');\n\nasync function get_useful_data() {\n const raw_data = await request(some_url);\n myWorker.postmessage(raw_data);\n}\n\nconst show_data => (e) {\n const data = e.data;\n ...\n}\n\nmyWorker.onmessage(show_data);\nget_useful_data();\n```\n\nYour mileage may vary of course, and there are many abstractions that can be\nbuilt upon this model."},"2017-05-29-upping-performance-by-appending-keying.md":{"name":"2017-05-29-upping-performance-by-appending-keying.md","sha":"4d3fa1298aee3e9bbd3dc884af6e6d13f1a30e6a","content":"---\nlayout: post\n\ntitle: Upping Performance by Appending/Keying\ntip-number: 75\ntip-username: loverajoel \ntip-username-profile: https://github.com/loverajoel\ntip-tldr: React uses a mechanism called **reconciliation** for efficient rendering on update.\n\ncategories:\n - en\n - react\n---\n\nReact uses a mechanism called **reconciliation** for efficient rendering on\nupdate.\n\n**Reconciliation** works by recursively comparing the tree of DOM elements,\nthe specifics of the algorithm might be found on the official documents or\nthe source, which is always the best source.\n\nThis mechanism is partly hidden, and as such, there are some conventions\nthat might be followed to ease its inner workings.\n\nOne such example is **appending** vs **inserting**.\n\n**Reconciliation** compares the list of root's nodes children at the same\ntime, if two children differ, then React will mutate every one.\n\nSo, for example, if you've got the following:\n\n``` html\n<ul>\n <li>Sherlock Holmes</li>\n <li>John Hamish Watson</li>\n</ul>\n```\n\nAnd you insert an element at the beginning\n\n``` html\n<ul>\n <li>Mycroft Holmes</li>\n <li>Sherlock Holmes</li>\n <li>John Hamish Watson</li>\n</ul>\n```\n\nReact will start of by comparing the old tree, where `<li>Second</li>` is the\nfirst child and the new tree where `<li>First</li>` is the new first child.\nBecause they are different, it will mutate the children.\n\nIf, instead of inserting good Mycroft you appended him, React would perform\nbetter, not touching Sherlock nor John.\n\nBut you can't always append, sometimes you've just got to insert.\n\nThis is were **keys** come in. If you supply a **key** *attribute* then React\nwill figure out an efficient transformation from the old tree to the new one.\n\n``` html\n<ul>\n <li key=\"3\">Mycroft Holmes</li>\n <li key=\"1\">Sherlock Holmes</li>\n <li key=\"2\">John Hamish Watson</li>\n</ul>\n```"},"2017-06-15-looping-over-arrays.md":{"name":"2017-06-15-looping-over-arrays.md","sha":"1618512073bd98d113c767d3a3af808d48c2b8d0","content":"---\nlayout: post\n\ntitle: Looping over arrays\ntip-number: 79\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: There's a few methods for looping over arrays in Javascript. We'll start with the classical ones and move towards additions made to the standard.\n\ncategories:\n - en\n - javascript\n---\n\n# Looping over arrays\n\nThere's a few methods for looping over arrays in Javascript. We'll start\nwith the classical ones and move towards additions made to the standard.\n\n## while\n\n```javascript\nlet index = 0;\nconst array = [1,2,3,4,5,6];\n\nwhile (index < array.length) {\n console.log(array[index]);\n index++;\n}\n```\n\n## for (classical)\n\n```javascript\nconst array = [1,2,3,4,5,6];\nfor (let index = 0; index < array.length; index++) {\n console.log(array[index]);\n}\n```\n\n## forEach\n\n```javascript\nconst array = [1,2,3,4,5,6];\n\narray.forEach(function(current_value, index, array) {\n console.log(`At index ${index} in array ${array} the value is ${current_value}`);\n});\n// => undefined\n```\n\n## map\n\nThe last construct was useful, however, it doesn't return a new array which might\nbe undesirable for your specific case. `map` solves this by applying a function\nover every element and then returning the new array.\n\n```javascript\nconst array = [1,2,3,4,5,6];\nconst square = x => Math.pow(x, 2);\nconst squares = array.map(square);\nconsole.log(`Original array: ${array}`);\nconsole.log(`Squared array: ${squares}`);\n```\n\nThe full signature for `map` is `.map(current_value, index, array)`.\n\n## reduce\n\nFrom MDN:\n\n> The reduce() method applies a function against an accumulator and each element\n> in the array (from left to right) to reduce it to a single value.\n\n```javascript\nconst array = [1,2,3,4,5,6];\nconst sum = (x, y) => x + y;\nconst array_sum = array.reduce(sum, 0);\nconsole.log(`The sum of array: ${array} is ${array_sum}`);\n```\n\n\n## filter\n\nFilters elements on an array based on a boolean function.\n\n```javascript\nconst array = [1,2,3,4,5,6];\nconst even = x => x % 2 === 0;\nconst even_array = array.filter(even);\nconsole.log(`Even numbers in array ${array}: ${even_array}`);\n```\n\n## every\n\nGot an array and want to test if a given condition is met in every element?\n\n```javascript\nconst array = [1,2,3,4,5,6];\nconst under_seven = x => x < 7;\n\nif (array.every(under_seven)) {\n console.log('Every element in the array is less than 7');\n} else {\n console.log('At least one element in the array was bigger than 7');\n}\n```\n\n## some\n\nTest if at least one element matches our boolean function.\n\n```javascript\nconst array = [1,2,3,9,5,6,4];\nconst over_seven = x => x > 7;\n\nif (array.some(over_seven)) {\n console.log('At least one element bigger than 7 was found');\n} else {\n console.log('No element bigger than 7 was found');\n}\n```\n"},"2017-06-14-closures-inside-loops.md":{"name":"2017-06-14-closures-inside-loops.md","sha":"643c692f359b247384945f12104074b876696e09","content":"---\nlayout: post\n\ntitle: Closures inside loops\ntip-number: 76\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Closure in a loop is an interesting topic and this is the tip to be a master of it\n\ncategories:\n - en\n - javascript\n---\n\nIf you ever come across the likes of\n\n```javascript\nvar funcs = [];\nfor (var i = 0; i < 3; i++) {\n funcs[i] = function() {\n console.log(\"i value is\" + i);\n };\n}\n\nfor (var i = 0; i < 3; i++) {\n funcs[i]();\n}\n```\n\nYou will notice that the expected output of\n\n```\ni value is 0\ni value is 1\ni value is 2\n```\n\nDoesn't match the actual output which will resemble\n\n```\ni value is 2\ni value is 2\ni value is 2\n```\n\nThis is because of how the capturing mechanism of closures work and how `i` is represented internally.\n\nTo solve this situation you can do as follows:\n\n```javascript\nfor (var i = 0; i < 3; i++) {\n funcs[i] = (function(value) {\n console.log(\"i value is \" + 3);\n })(i);\n}\n```\n\nWhich effectively copies i by value by handing it to our closure or\n\n```javascript\nfor (let i = 0; i < 3; i++) {\n funcs[i] = function() {\n console.log(\"i value is \" + 3);\n }\n}\n```\n\nWhere `let` scopes the variable to our `for` loop and produces a new value each iteration, thus `i` will be bound to different values on our closures as expected."},"2017-06-14-immutable-structures-and-cloning.md":{"name":"2017-06-14-immutable-structures-and-cloning.md","sha":"09a44066aaa85a12bcc3647da31bd3b06f19dcfb","content":"---\nlayout: post\n\ntitle: Immutable structures and cloning\ntip-number: 78\ntip-username: loverajoel\ntip-username-profile: https://github.com/loverajoel\ntip-tldr: Object cloning is a tricky, full of edge-cases, endeavor. The reason is simple enough. Objects maintain internal state, and that is much abused. There are countless techniques, or better phrased, countless derivations of the same technique.\n\ncategories:\n - en\n - javascript\n---\n\nObject cloning is a tricky, full of edge-cases, endeavor. The reason is simple\nenough. Objects maintain internal state, and that is much abused. There are\ncountless techniques, or better phrased, countless derivations of the same\ntechnique.\n\nCloning an object is an indicator that your application is growing, and that\nyou've got a complex object which you'd want to treat as an immutable value, i.e\noperate on it while maintaining a previous state.\n\nIf the object is in your control, you're lucky. A bit of refactoring here and\nthere might lead you to a point where you avoid the problem entirely by\nrethinking your object's structure and behavior.\n\nWith the rediscovering of functional programming techniques, a myriad of debates\nhave been held about immutable structures and how they offer exactly what you\nseek for. Mutable state is the root of all evil, some might argue.\n\nWe encourage to reach **ImmutableJS** by Facebook which provides a nice set of\nimmutable structures free for use. By rethinking your object's inner workings\nand separating state from behavior, making each function consume a state to\nproduce a new one - much like the Haskell's **State** monad - you will\nreduce many nuisances.\n\nIf the object is outside your control, you're partly out of luck. This can be\ncircumvented by creating convoluted computations where you solve for yourself\ncircular references and reach enlightenment. However, as you're using external\nobjects anyways, and they must come, as their name says, from external sources,\nthen you might be more comfortable handling the matter to yet another external\nlibrary and focus on what matters the most, i.e, your application itself.\n\nOne such library is [pvorb/clone](https://github.com/pvorb/clone), which has a\nvery simple API. To clone an object you only have to\n\n``` javascript\nvar clone = require('clone');\n\nvar a = {foo: {bar: 'baz'}};\nvar b = clone(a);\na.foo.bar = 'foo';\nconsole.log(a); // {foo: {bar: 'foo'}}\nconsole.log(b); // {foo: {bar: 'baz'}}\n```\n\nThere are, of course, many more libraries that allow you to do the same such as\n[Ramda](http://ramdajs.com/docs/#clone), [lodash.clonedeep](https://www.npmjs.com/package/lodash.clonedeep)\nand [lodash.clone](https://www.npmjs.com/package/lodash.clone).\n\nAs an end note, if you are serious about dealing with immutable structures, you\nmight want to check **ClojureScript** or (for those that feel that Haskell's\nworth a shot) **PureScript**.\n\nWe neither encourage, nor condemn, the use of self made cloning mechanisms. Only\nnoting that considerable work has been done on the area and that you'd probably\nbe better of reusing than reinventing the wheel."},"2017-09-01-hash-maps-without-side-effects.md":{"name":"2017-09-01-hash-maps-without-side-effects.md","sha":"2075dadf990184da4b17b2c18366818558944ba6","content":"---\nlayout: post\n\ntitle: Hash maps without side effects\ntip-number: 73\ntip-username: bhaskarmelkani\ntip-username-profile: https://www.twitter.com/bhaskarmelkani\ntip-tldr: Create hash maps(without side effects) using `Object.create(null)`.\n\ncategories:\n - en\n - javascript\n---\n\n# Hash maps without side effects\n\nWhen you want to use javascript object as a hash map(purely for storing data), you might want to create it as follows.\n\n```javascript\n const map = Object.create(null);\n```\n\nWhen creating a map using object literal(`const map = {}`), the map inherits properties from Object by default. It is equivalent to `Object.create(Object.prototype)`.\n\nBut by doing `Object.create(null)`, we explicitly specify `null` as its prototype. So it have absolutely no properties, not even constructor, toString, hasOwnProperty, etc. so you're free to use those keys in your data structure if you need to.\n\n## Rationale:\n\n```javascript\nconst dirtyMap = {};\nconst cleanMap = Object.create(null);\n\ndirtyMap.constructor // function Object() { [native code] }\n\ncleanMap.constructor // undefined\n\n// Iterating maps\n\nconst key;\nfor(key in dirtyMap){\n if (dirtyMap.hasOwnProperty(key)) { // Check to avoid iterating over inherited properties.\n console.log(key + \" -> \" + dirtyMap[key]);\n }\n}\n\nfor(key in cleanMap){\n console.log(key + \" -> \" + cleanMap[key]); // No need to add extra checks, as the object will always be clean\n}\n```\n\n## Notes:\n* Object.create() was introduced in ES5: [Compatibility](http://kangax.github.io/compat-table/es5/)\n* ES6 introduced some new structures: [Map](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map), [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap), [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and [Weak Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet)\n"}}