{"id":5254,"date":"2019-02-17T15:20:41","date_gmt":"2019-02-17T14:20:41","guid":{"rendered":"https:\/\/monodes.com\/predaelli\/?p=5254"},"modified":"2019-02-17T15:20:41","modified_gmt":"2019-02-17T14:20:41","slug":"learn-pure-functions-with-javascript-cristi-salcescu-medium","status":"publish","type":"post","link":"https:\/\/monodes.com\/predaelli\/2019\/02\/17\/learn-pure-functions-with-javascript-cristi-salcescu-medium\/","title":{"rendered":"Learn pure functions with JavaScript \u2013 Cristi Salcescu \u2013 Medium"},"content":{"rendered":"<blockquote><p>Pure functions are easier to read, understand, test, debug and munch more.<\/p><\/blockquote>\n<p>Source: <em><a href=\"https:\/\/medium.com\/@cristisalcescu\/learn-pure-functions-with-javascript-abf9b1c59246\">Learn pure functions with JavaScript \u2013 Cristi Salcescu \u2013 Medium<\/a><\/em><\/p>\n<p><!--more--><!--nextpage--><\/p>\n<blockquote>\n<h1 id=\"7e34\" class=\"graf graf--h3 graf--leading graf--title\">Learn pure functions with JavaScript<\/h1>\n<div class=\"uiScale uiScale-ui--regular uiScale-caption--regular u-flexCenter u-marginVertical24 u-fontSize15 js-postMetaLockup\">\n<div class=\"u-flex0\">\n<div class=\"u-relative u-inlineBlock u-flex0\"><img data-recalc-dims=\"1\" decoding=\"async\" class=\"avatar-image u-size50x50\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/fit\/c\/50\/50\/1%2AgAOA0dQY0gxYoH_1F_6VCw.png?w=910&#038;ssl=1\" alt=\"Go to the profile of Cristi Salcescu\" \/><\/p>\n<div class=\"avatar-halo u-absolute u-textColorGreenNormal svgIcon\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"u-paddingBottom3\"><a class=\"ds-link ds-link--styleSubtle ui-captionStrong u-inlineBlock link link--darken link--darker\" dir=\"auto\" href=\"https:\/\/medium.com\/@cristisalcescu\" data-action=\"show-user-card\" data-action-value=\"33d9ca60d9c0\" data-action-type=\"hover\" data-user-id=\"33d9ca60d9c0\">Cristi Salcescu<\/a><\/div>\n<div class=\"ui-caption u-noWrapWithEllipsis js-testPostMetaInlineSupplemental\"><time datetime=\"2019-02-10T15:13:03.200Z\">Feb 10<\/time><\/div>\n<div class=\"aspectRatioPlaceholder is-locked\">\n<div class=\"aspectRatioPlaceholder-fill\"><\/div>\n<div class=\"progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded\" data-image-id=\"1*1b_CYIBvNk0jn6uA6cJJ9A.jpeg\" data-width=\"3000\" data-height=\"2000\" data-is-featured=\"true\" data-action=\"zoom\" data-action-value=\"1*1b_CYIBvNk0jn6uA6cJJ9A.jpeg\" data-scroll=\"native\"><\/div>\n<\/div>\n<div class=\"postArticle-content js-postField js-notesSource js-trackPostScrolls\" data-post-id=\"abf9b1c59246\" data-source=\"post_page\" data-tracking-context=\"postPage\" data-scroll=\"native\">\n<section class=\"section section--body section--first section--last\">\n<div class=\"section-content\">\n<div class=\"section-inner sectionLayout--insetColumn\">\n<figure id=\"daef\" class=\"graf graf--figure graf-after--h3\">\n<div class=\"aspectRatioPlaceholder is-locked\">\n<div class=\"progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded\" data-image-id=\"1*1b_CYIBvNk0jn6uA6cJJ9A.jpeg\" data-width=\"3000\" data-height=\"2000\" data-is-featured=\"true\" data-action=\"zoom\" data-action-value=\"1*1b_CYIBvNk0jn6uA6cJJ9A.jpeg\" data-scroll=\"native\"><img data-recalc-dims=\"1\" decoding=\"async\" class=\"progressiveMedia-image js-progressiveMedia-image\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/800\/1%2A1b_CYIBvNk0jn6uA6cJJ9A.jpeg?w=910&#038;ssl=1\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*1b_CYIBvNk0jn6uA6cJJ9A.jpeg\" \/><\/div>\n<\/div><figcaption class=\"imageCaption\">Photo by <a class=\"markup--anchor markup--figure-anchor\" href=\"https:\/\/unsplash.com\/photos\/zSJscpJBdPk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"nofollow noopener\" data-href=\"https:\/\/unsplash.com\/photos\/zSJscpJBdPk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Ren\u00e9 Reichelt<\/a> on\u00a0<a class=\"markup--anchor markup--figure-anchor\" href=\"https:\/\/unsplash.com\/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"nofollow noopener\" data-href=\"https:\/\/unsplash.com\/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Unsplash<\/a><\/figcaption><\/figure>\n<p id=\"a9d3\" class=\"graf graf--p graf-after--figure\">Pure functions are easier to read, understand, test, debug and munch more. You may have already heard all of that before. A few questions are: what are these pure functions? how do they look like? or can we write the whole application using only pure functions?<\/p>\n<p id=\"e86f\" class=\"graf graf--p graf-after--p\">Here are two definitions of a pure function:<\/p>\n<blockquote id=\"8e54\" class=\"graf graf--pullquote graf-after--p\"><p><span class=\"markup--quote markup--pullquote-quote is-other\" data-creator-ids=\"anon\">A pure function is a function that given the same input always returns the same output and has no side\u00a0effects.<\/span><\/p><\/blockquote>\n<blockquote id=\"cb19\" class=\"graf graf--pullquote graf-after--pullquote\"><p>A pure function is a function that has referential transparency.<\/p><\/blockquote>\n<h3 id=\"8cad\" class=\"graf graf--h3 graf-after--pullquote\">Reading<\/h3>\n<p id=\"70e2\" class=\"graf graf--p graf-after--h3\">Pure functions make code easier to read. Let\u2019s see how.<\/p>\n<h4 id=\"dbbe\" class=\"graf graf--h4 graf-after--p\">From the\u00a0inside<\/h4>\n<p id=\"8b60\" class=\"graf graf--p graf-after--h4\">We don\u2019t need to look outside the function scope to understand what is the value of some variable.<\/p>\n<p id=\"f24f\" class=\"graf graf--p graf-after--p\">There is no need to think how changing the value of the variable in the current function will affect other functions. There is no need to think how changing the value of a variable in other functions will affect the current function.<\/p>\n<p id=\"f363\" class=\"graf graf--p graf-after--p\">Look at a pure function:<\/p>\n<pre id=\"4104\" class=\"graf graf--pre graf-after--p\">function isPriorityTodo(task) {\n  return task.type === \"RE\" &amp;&amp; !task.completed;\n}<\/pre>\n<p id=\"9e63\" class=\"graf graf--p graf-after--pre\">When reading a pure function you can focus in one place, the current function. Pure functions give the reader less code to read.<\/p>\n<h4 id=\"68fe\" class=\"graf graf--h4 graf-after--p\">From the\u00a0outside<\/h4>\n<p id=\"fc19\" class=\"graf graf--p graf-after--h4\">Look at the code below:<\/p>\n<pre id=\"1be5\" class=\"graf graf--pre graf-after--p\">const arr = [1,2,3];\nconst newValue = compute(arr);<\/pre>\n<pre id=\"2f32\" class=\"graf graf--pre graf-after--pre\">console.log(arr);\n\/\/[1,2,3]<\/pre>\n<p id=\"0218\" class=\"graf graf--p graf-after--pre\">When <code class=\"\" data-line=\"\">compute()<\/code> is a pure function, we are sure that <code class=\"\" data-line=\"\">console<\/code> will log <code class=\"\" data-line=\"\">[1,2,3]<\/code>, we don\u2019t need to read and understand the <code class=\"\" data-line=\"\">compute()<\/code> function.<\/p>\n<p id=\"5a64\" class=\"graf graf--p graf-after--p\">Code can be read faster when you read less. Less things to read and understand makes code easier to read.<\/p>\n<h3 id=\"240a\" class=\"graf graf--h3 graf-after--p\">Side effects<\/h3>\n<p id=\"36db\" class=\"graf graf--p graf-after--h3\">A side effect is a change of a variable from outside the local environment or an interaction with the outside environment that happens during the computation of the result. In short, any interaction with the outside world is a side-effect.<\/p>\n<p id=\"a616\" class=\"graf graf--p graf-after--p\">Here are some examples of side-effects:<\/p>\n<ul class=\"postList\">\n<li id=\"368e\" class=\"graf graf--li graf-after--p\">reading and changing of state out of local scope<\/li>\n<li id=\"f248\" class=\"graf graf--li graf-after--li\">network calls<\/li>\n<li id=\"b9b7\" class=\"graf graf--li graf-after--li\">reading and writing to DOM<\/li>\n<li id=\"0819\" class=\"graf graf--li graf-after--li\">listening for user events<\/li>\n<li id=\"47ac\" class=\"graf graf--li graf-after--li\">writing to console<\/li>\n<li id=\"223c\" class=\"graf graf--li graf-after--li\">reading and writing to local storage<\/li>\n<li id=\"6ee3\" class=\"graf graf--li graf-after--li\">using timers (they change the JavaScript Event Loop)<\/li>\n<\/ul>\n<p id=\"c707\" class=\"graf graf--p graf-after--li\">Mutating external state may create unexpected issues in some other distant part of the code. Especially changing input values can create hard to understand bugs. We don\u2019t know where the input object comes from or how changing it will affect other functions.<\/p>\n<p id=\"cc3e\" class=\"graf graf--p graf-after--p\">The result of a function with side effects depends on the external environment. Given the same input it may return different results as the outside state may have changed.<\/p>\n<p id=\"36a1\" class=\"graf graf--p graf-after--p\">Here are a few functions with side effects:<\/p>\n<p id=\"fb79\" class=\"graf graf--p graf-after--p\"><code class=\"\" data-line=\"\">getNextValue()<\/code> is not pure, it changes state outside the function scope.<\/p>\n<pre id=\"1095\" class=\"graf graf--pre graf-after--p\"><strong class=\"markup--strong markup--pre-strong\">let startValue = 0;<\/strong><\/pre>\n<pre id=\"0e16\" class=\"graf graf--pre graf-after--pre\">function getNextValue(){\n    <strong class=\"markup--strong markup--pre-strong\">startValue += 1;<\/strong>\n    return startValue;\n}<\/pre>\n<pre id=\"c70b\" class=\"graf graf--pre graf-after--pre\">getNextValue(); \/\/1\ngetNextValue(); \/\/2<\/pre>\n<p id=\"5c1b\" class=\"graf graf--p graf-after--pre\"><code class=\"\" data-line=\"\">addValue()<\/code> is not pure, it mutates the input variable.<\/p>\n<pre id=\"eca6\" class=\"graf graf--pre graf-after--p\">const numbers = []<\/pre>\n<pre id=\"7574\" class=\"graf graf--pre graf-after--pre\">function addValue(<strong class=\"markup--strong markup--pre-strong\">list<\/strong>, value){\n    <strong class=\"markup--strong markup--pre-strong\">list.push(value);<\/strong>\n}<\/pre>\n<pre id=\"a367\" class=\"graf graf--pre graf-after--pre\">addValue(numbers, 1);\naddValue(numbers, 2);<\/pre>\n<h3 id=\"b637\" class=\"graf graf--h3 graf-after--pre\">Free variables<\/h3>\n<blockquote id=\"1540\" class=\"graf graf--pullquote graf-after--h3\"><p>A free variable is a variable used in a function that is neither a local variables nor a parameter of the function.<\/p><\/blockquote>\n<p id=\"56ee\" class=\"graf graf--p graf-after--pullquote\">Pure functions don\u2019t access free variable unless this free variables are constants.<\/p>\n<p id=\"ebed\" class=\"graf graf--p graf-after--p\">A constant is a variable declared with <code class=\"\" data-line=\"\">const<\/code> storing an immutable value.<\/p>\n<h3 id=\"e173\" class=\"graf graf--h3 graf-after--p\">Immutability<\/h3>\n<p id=\"3111\" class=\"graf graf--p graf-after--h3\">An immutable value is a value that, once created, cannot be changed.<\/p>\n<p id=\"3297\" class=\"graf graf--p graf-after--p\">Pure functions treat input values as immutable. Ideally input values should be immutable values. It is a good practice to return an immutable value.<\/p>\n<p id=\"dd6b\" class=\"graf graf--p graf-after--p\">For more on immutability take a look at <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.com\/@cristisalcescu\/learn-immutability-with-javascript-6a67e4a48d7f\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/medium.com\/@cristisalcescu\/learn-immutability-with-javascript-6a67e4a48d7f\">Learn immutability with JavaScript<\/a>.<\/p>\n<h3 id=\"726b\" class=\"graf graf--h3 graf-after--p\">this<\/h3>\n<p id=\"607c\" class=\"graf graf--p graf-after--h3\"><code class=\"\" data-line=\"\">this<\/code> represents the function\u2019s context.<\/p>\n<p id=\"9543\" class=\"graf graf--p graf-after--p\"><code class=\"\" data-line=\"\">this<\/code> is an implicit input.<\/p>\n<p id=\"47c9\" class=\"graf graf--p graf-after--p\">When <code class=\"\" data-line=\"\">this<\/code> is used, we need to always call the function with <code class=\"\" data-line=\"\">call()<\/code> or <code class=\"\" data-line=\"\">apply()<\/code> and pass in the context object.<\/p>\n<p id=\"9d13\" class=\"graf graf--p graf-after--p\">When <code class=\"\" data-line=\"\">this<\/code> is used and we invoke it with the function form, we create a side effect. In this case the function may give different results based on the environment where it is run. <code class=\"\" data-line=\"\">this<\/code> becomes a free variable.<\/p>\n<p id=\"e359\" class=\"graf graf--p graf-after--p\">We want explicit inputs on functions. If we want to compose functions easily, <code class=\"\" data-line=\"\">this<\/code> should not be used.<\/p>\n<p id=\"4b96\" class=\"graf graf--p graf-after--p\">Making the context object explicit means to add it to the parameter list.<\/p>\n<pre id=\"68a9\" class=\"graf graf--pre graf-after--p\">function transform(context) { }<\/pre>\n<p id=\"2105\" class=\"graf graf--p graf-after--pre\">I would say to avoid <code class=\"\" data-line=\"\">this<\/code> in pure functions.<\/p>\n<h3 id=\"a666\" class=\"graf graf--h3 graf-after--p\">A deterministic function<\/h3>\n<p id=\"7bd8\" class=\"graf graf--p graf-after--h3\">A pure function is deterministic function. For a specific input it always returns the same output.<\/p>\n<p id=\"0d76\" class=\"graf graf--p graf-after--p\"><code class=\"\" data-line=\"\">Math.random()<\/code> or <code class=\"\" data-line=\"\">Date.now()<\/code> will not be used in pure function as they give different results on each call.<\/p>\n<p id=\"8851\" class=\"graf graf--p graf-after--p\">The next function has no side-effects, but it is not deterministic. It is not a pure function:<\/p>\n<pre id=\"88c5\" class=\"graf graf--pre graf-after--p\">function getNextValue(){\n    return <strong class=\"markup--strong markup--pre-strong\">Math.random();<\/strong>\n}<\/pre>\n<h3 id=\"259d\" class=\"graf graf--h3 graf-after--pre\">Referential transparency<\/h3>\n<blockquote id=\"e83e\" class=\"graf graf--pullquote graf-after--h3\"><p>An function has referential transparency if it can be replaced with its output value and the application behavior doesn\u2019t\u00a0change.<\/p><\/blockquote>\n<p id=\"6e78\" class=\"graf graf--p graf-after--pullquote\">Because we can replace the function with its result it means the function had no side-effects.<\/p>\n<p id=\"3f66\" class=\"graf graf--p graf-after--p\">A referentially transparent function does nothing else but computing the result.<\/p>\n<p id=\"da58\" class=\"graf graf--p graf-after--p\">A function that has referential transparency is a pure function.<\/p>\n<h3 id=\"77df\" class=\"graf graf--h3 graf-after--p\">Using other functions<\/h3>\n<h4 id=\"e3c8\" class=\"graf graf--h4 graf-after--h3\">Using other pure functions<\/h4>\n<p id=\"4560\" class=\"graf graf--p graf-after--h4\">Pure functions can use other pure functions. Check the code below where the <code class=\"\" data-line=\"\">getBy()<\/code> pure function uses other two pure functions: <code class=\"\" data-line=\"\">partial()<\/code> and <code class=\"\" data-line=\"\">queryContainsBook()<\/code>.<\/p>\n<pre id=\"5249\" class=\"graf graf--pre graf-after--p\"><strong class=\"markup--strong markup--pre-strong\">import partial from \"lodash\/partial\";<\/strong><\/pre>\n<pre id=\"38f2\" class=\"graf graf--pre graf-after--pre\"><strong class=\"markup--strong markup--pre-strong\">function queryContainsBook(query, book)<\/strong> {\n  if (query &amp;&amp; query.text) {\n    return book.title.includes(query.text);\n  }\n  return true;\n<strong class=\"markup--strong markup--pre-strong\">}<\/strong><\/pre>\n<pre id=\"3ce7\" class=\"graf graf--pre graf-after--pre\">function getBy(books, query) {\n  return books.filter(<strong class=\"markup--strong markup--pre-strong\">partial(queryContainsBook, query)<\/strong>);\n}<\/pre>\n<h4 id=\"b4f0\" class=\"graf graf--h4 graf-after--pre\">Using other impure functions<\/h4>\n<p id=\"5812\" class=\"graf graf--p graf-after--h4\">Calling an impure function inside a function makes the current function impure. Returning a reference of an impure function doesn\u2019t affect the function purity.<\/p>\n<p id=\"5ace\" class=\"graf graf--p graf-after--p\">Consider the next example where <code class=\"\" data-line=\"\">doImpureTask()<\/code> is an impure function:<\/p>\n<pre id=\"ef54\" class=\"graf graf--pre graf-after--p\">function doImpureTask(){}<\/pre>\n<pre id=\"9dc4\" class=\"graf graf--pre graf-after--pre\">function runCallback(){\n  return doImpureTask();\n}<\/pre>\n<pre id=\"b783\" class=\"graf graf--pre graf-after--pre\">function getCallback(){\n  return doImpureTask;\n}<\/pre>\n<p id=\"ccef\" class=\"graf graf--p graf-after--pre\"><code class=\"\" data-line=\"\">runCallback()<\/code> is impure. <code class=\"\" data-line=\"\">getCallback()<\/code> is pure.<\/p>\n<p id=\"dd9d\" class=\"graf graf--p graf-after--p\">By taking this idea further, we can create pure function that returns impure functions.<\/p>\n<pre id=\"ad63\" class=\"graf graf--pre graf-after--p\">function getCallback(){\n  return function(){\n    doImpureTask();\n  }\n}<\/pre>\n<p id=\"3e07\" class=\"graf graf--p graf-after--pre\"><code class=\"\" data-line=\"\">getCallback()<\/code> is still a pure function. The returned function is impure.<\/p>\n<h3 id=\"be30\" class=\"graf graf--h3 graf-after--p\">Purity from the\u00a0inside<\/h3>\n<p id=\"2eaf\" class=\"graf graf--p graf-after--h3\">We can start writing code in pure functional style by just removing features:<\/p>\n<ul class=\"postList\">\n<li id=\"11f1\" class=\"graf graf--li graf-after--p\">No use of assignment operators<\/li>\n<li id=\"d50b\" class=\"graf graf--li graf-after--li\">Declare variable only with <code class=\"\" data-line=\"\">const<\/code>. No use of <code class=\"\" data-line=\"\">let<\/code>, <code class=\"\" data-line=\"\">var<\/code> statements.<\/li>\n<li id=\"49b4\" class=\"graf graf--li graf-after--li\">Only use array pure methods<\/li>\n<li id=\"c160\" class=\"graf graf--li graf-after--li\">No use of <code class=\"\" data-line=\"\">for<\/code> statements<\/li>\n<\/ul>\n<h3 id=\"e8b9\" class=\"graf graf--h3 graf-after--li\">Purity from the\u00a0outside<\/h3>\n<p id=\"bc3c\" class=\"graf graf--p graf-after--h3\">Writing the code in a pure functional style will make it pure both from the inside and outside.<\/p>\n<p id=\"ceb6\" class=\"graf graf--p graf-after--p\">Nevertheless, according to the definition, the purity of a function is decided from the outside not from the inside. Look at the next example:<\/p>\n<pre id=\"55d8\" class=\"graf graf--pre graf-after--p\">function createActionTypes(config) {\n  const actionTypes = Object.create(null);\n  Object.keys(config).<strong class=\"markup--strong markup--pre-strong\">forEach<\/strong>(function addToMap(name) {\n    <strong class=\"markup--strong markup--pre-strong\">actionTypes[name] = name;<\/strong>\n  });\n  return Object.freeze(actionTypes);\n}<\/pre>\n<p id=\"9da7\" class=\"graf graf--p graf-after--pre\">The <code class=\"\" data-line=\"\">createActionTypes()<\/code> is not written in a pure functional style. It uses the assignment operator and the <code class=\"\" data-line=\"\">forEach()<\/code> impure method. However, when we look at the function from the outside, it is pure.<\/p>\n<h3 id=\"6c32\" class=\"graf graf--h3 graf-after--p\">The problem<\/h3>\n<p id=\"abfe\" class=\"graf graf--p graf-after--h3\">The problem with pure functions is that we can\u2019t write the whole application using pure functions. There is state change, there is UI rendering, there is user interaction, there are network calls. All these cannot be implemented with pure functions. Pure functions don\u2019t communicate with the external environment.<\/p>\n<p id=\"537c\" class=\"graf graf--p graf-after--p\">What can we do then? We want all the benefits of pure functions, but at the same time we cannot use 100% pure functions to do a practical application.<\/p>\n<p id=\"6c4f\" class=\"graf graf--p graf-after--p\">The benefits of pure functions are significant and we should write as many pure functions as we can. At the same time we need impure code to communicate with the environment.<\/p>\n<p id=\"288d\" class=\"graf graf--p graf-after--p\">I suggest to aim for purity and encapsulate impure code.<\/p>\n<h3 id=\"b15b\" class=\"graf graf--h3 graf-after--p\">Impure code<\/h3>\n<p id=\"b5a1\" class=\"graf graf--p graf-after--h3\">Side effects are a common source of bugs because they make code harder to read and reason about.<\/p>\n<p id=\"8263\" class=\"graf graf--p graf-after--p\">Side-effects can make code hard to understand, but they are necessary.<\/p>\n<p id=\"9fe8\" class=\"graf graf--p graf-after--p\">Our best approach is to encapsulate side-effects.<\/p>\n<p id=\"1f64\" class=\"graf graf--p graf-after--p\">Collecting the impure code together will make it easier to investigate these parts when bugs arise. By isolating side-effects we know where to look for unexpected issues.<\/p>\n<p id=\"cbcc\" class=\"graf graf--p graf-after--p\">We need to reduce the possible kinds of side effects in a function. The goal is to reduce side effects, not just encapsulate them.<\/p>\n<h3 id=\"d0b7\" class=\"graf graf--h3 graf-after--p\">Encapsulate impure\u00a0code<\/h3>\n<p id=\"7d0f\" class=\"graf graf--p graf-after--h3\">Encapsulation means hiding. The simplest way to encapsulate things in JavaScript is with closures.<\/p>\n<h4 id=\"3b39\" class=\"graf graf--h4 graf-after--p\">Encapsulation with\u00a0objects<\/h4>\n<p id=\"c5fa\" class=\"graf graf--p graf-after--h4\">Look at the next example where we limit the places where state can change.<\/p>\n<pre id=\"c276\" class=\"graf graf--pre graf-after--p\">import { List } from \"immutable\";\nimport partial from \"lodash\/partial\";\nimport matchesProperty from \"lodash\/matchesProperty\";<\/pre>\n<pre id=\"6677\" class=\"graf graf--pre graf-after--pre\">function BookStore(){\n  <strong class=\"markup--strong markup--pre-strong\">let books = List();<\/strong>\n  \n  function add(book) {\n    return books.push(book);\n  }\n  \n  function remove(books, book) {\n    const index = books.findIndex(matchesProperty(\"id\", book.id));\n    return books.delete(index);\n  }<\/pre>\n<pre id=\"be5d\" class=\"graf graf--pre graf-after--pre\">  return Object.freeze({\n   add,\n   remove\n  });\n}<\/pre>\n<pre id=\"ce57\" class=\"graf graf--pre graf-after--pre\">const bookStore = BookStore();\nbookStore.add({ id: 1, title: \"How JavaScript Works\" });<\/pre>\n<p id=\"dbc1\" class=\"graf graf--p graf-after--pre\">The state in this example is a list of <code class=\"\" data-line=\"\">books<\/code>. It can only be modified through the <code class=\"\" data-line=\"\">add()<\/code> and <code class=\"\" data-line=\"\">remove()<\/code> methods of the <code class=\"\" data-line=\"\">bookStore<\/code> object. State is encapsulated.<\/p>\n<h4 id=\"a00c\" class=\"graf graf--h4 graf-after--p\">Encapsulate with a\u00a0library<\/h4>\n<p id=\"f379\" class=\"graf graf--p graf-after--h4\">A better way is to encapsulate the impure code behind a library. Consider the same store implemented with the <code class=\"\" data-line=\"\">Store()<\/code> utility function from a library:<\/p>\n<pre id=\"db58\" class=\"graf graf--pre graf-after--p\">import { List } from \"immutable\";\nimport Store from \".\/Store-toolbox\";\nimport partial from \"lodash\/partial\";\nimport matchesProperty from \"lodash\/matchesProperty\";<\/pre>\n<pre id=\"17b0\" class=\"graf graf--pre graf-after--pre\">function add(books, book) {\n  return books.push(book);\n}<\/pre>\n<pre id=\"03ab\" class=\"graf graf--pre graf-after--pre\">function remove(books, book) {\n  const index = books.findIndex(matchesProperty(\"id\", book.id));\n  return books.delete(index);\n}<\/pre>\n<pre id=\"de1c\" class=\"graf graf--pre graf-after--pre\">export default <strong class=\"markup--strong markup--pre-strong\">Store({\n  state: List(),\n  setters: { add, remove }\n})<\/strong>;<\/pre>\n<p id=\"f26b\" class=\"graf graf--p graf-after--pre\">Now let\u2019s create the <code class=\"\" data-line=\"\">bookStore<\/code> object:<\/p>\n<pre id=\"cb16\" class=\"graf graf--pre graf-after--p\">import BookStore from \".\/BookStore\";<\/pre>\n<pre id=\"640f\" class=\"graf graf--pre graf-after--pre\">const bookStore = BookStore();\nbookStore.add({ id: 2, title: \"Functional-Light JavaScript\" });<\/pre>\n<p id=\"e3cd\" class=\"graf graf--p graf-after--pre\">This time I wrote only pure functions, <code class=\"\" data-line=\"\">add()<\/code> and <code class=\"\" data-line=\"\">remove()<\/code>, and let the library do the impure part.<\/p>\n<p id=\"7e8e\" class=\"graf graf--p graf-after--p\">For the full code take a look at <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/how-to-create-a-store-using-pure-functions-2c19b678552f\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/how-to-create-a-store-using-pure-functions-2c19b678552f\">How to create a store using pure functions<\/a>.<\/p>\n<h3 id=\"0863\" class=\"graf graf--h3 graf-after--p\">Final Thoughts<\/h3>\n<p id=\"faac\" class=\"graf graf--p graf-after--h3\">Taking all these in consideration, it becomes clear that pure functions make code easier to read and understand. Nevertheless, we should not lose the importance of making pure functions small, do one thing and have an intention revealing names.<\/p>\n<p id=\"969f\" class=\"graf graf--p graf-after--p\">We should aim for purity as much as we can and encapsulate side effects. The purpose it to have a big percent of code pure and a low percent impure. This way we end up with a bigger part of the code that is easier to reason about and less code that can cause problems.<\/p>\n<p id=\"4485\" class=\"graf graf--p graf-after--p\">The more pure code the better.<\/p>\n<p id=\"5b9c\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">For more on the JavaScript\u2019s functional side take a look at:<\/strong><\/p>\n<p id=\"ddda\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.com\/@cristisalcescu\/learn-immutability-with-javascript-6a67e4a48d7f\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/medium.com\/@cristisalcescu\/learn-immutability-with-javascript-6a67e4a48d7f\">Learn immutability with JavaScript<\/a><\/p>\n<p id=\"be47\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/lets-experiment-with-functional-generators-and-the-pipeline-operator-in-javascript-520364f97448\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/lets-experiment-with-functional-generators-and-the-pipeline-operator-in-javascript-520364f97448\">Let\u2019s experiment with functional generators and the pipeline operator in JavaScript<\/a><\/p>\n<p id=\"7556\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/discover-functional-programming-in-javascript-with-this-thorough-introduction-a2ad9af2d645\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/discover-functional-programming-in-javascript-with-this-thorough-introduction-a2ad9af2d645\">Discover Functional Programming in JavaScript with this thorough introduction<\/a><\/p>\n<p id=\"7b94\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/how-point-free-composition-will-make-you-a-better-functional-programmer-33dcb910303a\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/how-point-free-composition-will-make-you-a-better-functional-programmer-33dcb910303a\">How point-free composition will make you a better functional programmer<\/a><\/p>\n<p id=\"da2c\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/how-to-make-your-code-better-with-intention-revealing-function-names-6c8b5271693e\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/how-to-make-your-code-better-with-intention-revealing-function-names-6c8b5271693e\">How to make your code better with intention-revealing function names<\/a><\/p>\n<p id=\"5e0a\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/here-are-a-few-function-decorators-you-can-write-from-scratch-488549fe8f86\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/here-are-a-few-function-decorators-you-can-write-from-scratch-488549fe8f86\">Here are a few function decorators you can write from scratch<\/a><\/p>\n<p id=\"f79c\" class=\"graf graf--p graf-after--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/why-you-should-give-the-closure-function-another-chance-31253e44cfa0\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/why-you-should-give-the-closure-function-another-chance-31253e44cfa0\">Why you should give the Closure function another chance<\/a><\/p>\n<p id=\"4ef7\" class=\"graf graf--p graf-after--p graf--trailing\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/medium.freecodecamp.org\/make-your-code-easier-to-read-with-functional-programming-94fb8cc69f9d\" target=\"_blank\" rel=\"noopener nofollow\" data-href=\"https:\/\/medium.freecodecamp.org\/make-your-code-easier-to-read-with-functional-programming-94fb8cc69f9d\">Make your code easier to read with Functional Programming<\/a><\/p>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<footer class=\"u-paddingTop10\">\n<div class=\"container u-maxWidth740\">\n<div class=\"row\">\n<div class=\"col u-size12of12\">\n<div class=\"postMetaInline postMetaInline--acknowledgments u-paddingTop5 u-paddingBottom20 js-postMetaAcknowledgments\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/footer>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p class=\"excerpt\">Pure functions are easier to read, understand, test, debug and munch more. Source: Learn pure functions with JavaScript \u2013 Cristi Salcescu \u2013 Medium<\/p>\n<p class=\"more-link-p\"><a class=\"more-link\" href=\"https:\/\/monodes.com\/predaelli\/2019\/02\/17\/learn-pure-functions-with-javascript-cristi-salcescu-medium\/\">Read more &rarr;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"link","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"activitypub_content_warning":"","activitypub_content_visibility":"","activitypub_max_image_attachments":4,"activitypub_interaction_policy_quote":"anyone","activitypub_status":"","footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[72,50],"tags":[],"class_list":["post-5254","post","type-post","status-publish","format-link","hentry","category-documentations","category-javascript","post_format-post-format-link"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6daft-1mK","jetpack-related-posts":[{"id":5128,"url":"https:\/\/monodes.com\/predaelli\/2019\/01\/15\/removing-javascripts-this-keyword-makes-it-a-better-language-heres-why\/","url_meta":{"origin":5254,"position":0},"title":"Removing JavaScript\u2019s \u201cthis\u201d keyword makes it a better language. Here\u2019s why.","author":"Paolo Redaelli","date":"2019-01-15","format":false,"excerpt":"Removing JavaScript\u2019s \u201cthis\u201d keyword makes it a better language. Here\u2019s why. Removing JavaScript\u2019s \u201cthis\u201d keyword makes it a better language. Here\u2019s\u00a0why. Cristi Salcescu Jan this is of course the source of much confusion in JavaScript. The reason being that this depends on how the function was invoked, not where the\u2026","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1614,"url":"https:\/\/monodes.com\/predaelli\/2016\/06\/01\/javascript-factory-functions-vs-constructor-functions-vs-classes-javascript-scene-medium\/","url_meta":{"origin":5254,"position":1},"title":"JavaScript Factory Functions vs Constructor Functions vs Classes \u2014 JavaScript Scene \u2014 Medium","author":"Paolo Redaelli","date":"2016-06-01","format":"link","excerpt":"https:\/\/medium.com\/javascript-scene\/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e#.13avjf4lk","rel":"","context":"In &quot;Senza categoria&quot;","block_context":{"text":"Senza categoria","link":"https:\/\/monodes.com\/predaelli\/category\/senza-categoria\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3971,"url":"https:\/\/monodes.com\/predaelli\/2018\/04\/01\/sheer-pure-evil\/","url_meta":{"origin":5254,"position":2},"title":"Sheer, pure evil","author":"Paolo Redaelli","date":"2018-04-01","format":false,"excerpt":"JavaScript: Can (a==1 && a==2 && a==3) ever evaluate to true?\u00a0Yes, it can. Understand how in this article! That's pure sheer evil, in my humble opinion as it tricks most people. Eiffel forbids this evilness, but I shall explain it better. Recently, an interesting code snippet has been making the\u2026","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":5130,"url":"https:\/\/monodes.com\/predaelli\/2019\/01\/15\/intuitive-asynchronous-javascript-edwin-yung-medium\/","url_meta":{"origin":5254,"position":3},"title":"Intuitive Asynchronous Javascript \u2013 Edwin Yung \u2013 Medium","author":"Paolo Redaelli","date":"2019-01-15","format":false,"excerpt":"Escape callback hell! Source: Intuitive Asynchronous Javascript \u2013 Edwin Yung \u2013 Medium \u00a0 Asynchronous Javascript Explained Simply and Intuitively Edwin Yung Dec 29, 2017 Escape callback hell with this\u00a0article! Asynchronous Javascript is difficult to wrangle. The following is my quick attempt to elucidate their inner workings. Before we get started,\u2026","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":9317,"url":"https:\/\/monodes.com\/predaelli\/2022\/04\/28\/7-more-killer-one-liners-in-javascript-by-tapajyoti-bose-apr-2022-medium\/","url_meta":{"origin":5254,"position":4},"title":"7 More Killer One-Liners in JavaScript | by Tapajyoti Bose | Apr, 2022 | Medium","author":"Paolo Redaelli","date":"2022-04-28","format":false,"excerpt":"7 More Killer One-Liners in JavaScript | by Tapajyoti Bose | Apr, 2022 | Medium This is a continuation of the previous list of JavaScript one-liners. If you haven\u2019t checked out the article, you are highly encouraged to accomplish so. Let\u2019s crack on with the new list! 1. Sleep Function\u2026","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":5536,"url":"https:\/\/monodes.com\/predaelli\/2019\/05\/01\/inspecting-one-of-the-most-famous-javascript-bugs-of-all-time\/","url_meta":{"origin":5254,"position":5},"title":"Inspecting one of the most famous JavaScript bugs of all time","author":"Paolo Redaelli","date":"2019-05-01","format":"link","excerpt":"One fine day evening, after writing a handful of beautiful JavaScript code, sipping your coffee, you smile\u200a\u2014\u200athe code looks especially\u2026 After reading Inspecting one of the most famous JavaScript bugs of all time one may wonder how such flaws does not \"explode\" in the face of every developer, subtle as\u2026","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/5254","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/comments?post=5254"}],"version-history":[{"count":0,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/5254\/revisions"}],"wp:attachment":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/media?parent=5254"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/categories?post=5254"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/tags?post=5254"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}