<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Darren Scerri on Medium]]></title>
        <description><![CDATA[Stories by Darren Scerri on Medium]]></description>
        <link>https://medium.com/@darrenscerri?source=rss-855cebc68178------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*atl-pp-gwn3TqdsfGZtVQg.jpeg</url>
            <title>Stories by Darren Scerri on Medium</title>
            <link>https://medium.com/@darrenscerri?source=rss-855cebc68178------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:50:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darrenscerri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Higher Order Components for Dummies]]></title>
            <link>https://medium.com/@darrenscerri/higher-order-components-for-dummies-ccdc233d5a1f?source=rss-855cebc68178------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccdc233d5a1f</guid>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Darren Scerri]]></dc:creator>
            <pubDate>Mon, 09 Jan 2017 23:09:49 GMT</pubDate>
            <atom:updated>2017-01-11T09:21:13.286Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Higher Order Components</em>, <em>Higher Order Functions</em>, <em>Functional Programming</em>, <em>Composition </em>are fancy terms for very simple yet extremely useful concepts. Instead of keeping on adding functionality inside a function or component, adding bloat, this functionality is split into atomic and generic wrappers that can be <strong>mix</strong>ed (<a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750#.iiwv4tbxe">mixins</a> anyone?) together, or rather, applied on top one another. Higher Order Functions/Components are practically useless on their own, but define behaviour or properties when used.</p><p>Higher Order Functions/Components (HOFC) are reusable wrappers, usually very simple and with concise implementation such as for example a simple memoizing function:</p><pre>var memoize = fn =&gt; {<br>  var cache = {};<br>  return arg =&gt; {<br>    if (arg in cache) {<br>      return cache[arg];<br>    }<br>    return cache[arg] = fn(arg);<br>  }<br>};</pre><p>This function takes a function as an argument and memoizes the first argument of the function, speeding up function invocation for repeated calls with the same argument.</p><p>So if we have a function that looks like this:</p><pre>var slowFn = x =&gt; {<br>  var result = // Do something very slow;<br>  return result;<br>};</pre><p>We can create a new function, that wraps around the slow function that will run much faster for subsequent calls with the same argument:</p><pre>var memoizedFn = memoize(slowFn);</pre><pre>memoizedFn(1); // slow<br>memoizedFn(1); // FAST!</pre><pre>memoizedFn(2); // slow<br>memoizedFn(2); // FAST!</pre><pre>memoizedFn(1); // FAST!</pre><p>A Higher-Order Component in React would look something like this:</p><pre>var AddUniqueId = Component =&gt; class extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.uniqueId = uniqueId++;<br>  }<br>  render() {<br>    return &lt;Component {...this.props} uniqueId={this.uniqueId}/&gt;<br>  }<br>}</pre><p>AddUniqueId takes a React Component as an argument and returns a new React Component that renders the initial component but adds a uniqueId as a prop. The initial component is not modified but instead we have a new <a href="http://survivejs.com/react/appendices/understanding-decorators/">decorated</a> component that has additional functionality. The beauty of this concept is the Higher Order Component adds the same functionality to any arbitrary component. HOFC can be chained together so for example:</p><pre>var LogClicks = Component =&gt; {<br>  class extends React.Component {<br>    onClick(...args) {<br>      console.log(&#39;Received click&#39;);<br>      this.props.onClick(...args);<br>    }<br>    render() {<br>      return &lt;Component {...this.props} onClick={this.onClick}/&gt;;<br>    }<br>  }<br>}</pre><pre>class MyComponent extends React.Component {<br>  render() {<br>    return (<br>      &lt;button onClick={this.props.onClick}&gt;<br>        Hello World {this.props.uniqueId}<br>      &lt;/button&gt;<br>    );<br>  }<br>}</pre><pre>var MySuperComponent = AddUniqueId(LogClicks(MyComponent));</pre><p>Now, MySuperComponent is a new component, that has a unique id passed as a prop, and logs clicks for that component, without actually modifying our original component MyComponent. We have <a href="https://github.com/acdlite/recompose">composed</a> a new component from a number of other components and each component renders the next component, starting from AddUniqueId, down to MyComponent until there are no more components left to render.</p><p>If you want to learn more about HOFC and composability in detail you can read more <a href="https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.asnfpkfx8">here</a> and <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750#.iiwv4tbxe">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccdc233d5a1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Babel and ES6]]></title>
            <link>https://medium.com/@darrenscerri/demystifying-babel-and-es6-98a9e6624573?source=rss-855cebc68178------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a9e6624573</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babeljs]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Darren Scerri]]></dc:creator>
            <pubDate>Sat, 07 Jan 2017 16:20:09 GMT</pubDate>
            <atom:updated>2017-04-25T19:18:21.403Z</atom:updated>
            <content:encoded><![CDATA[<p>This may not be the first time you heard the terms <em>Babel</em> and <em>ES6</em>, or <em>transpilation</em>. You may know what these terms refer to and you may already use these technologies at your workplace or have used them some way or another. We’ll dive a bit deep into these terms and try to open and see what’s inside these black boxes and explain the magic behind Babel.</p><p>Let’s start with transpilation. Transpilation is a very important and widely used concept, especially in more recent times. You may have heard of compilers, which are programs that take source-code as input and translates it into a (typically) lower level language, may it be assembly or simply machine code, for example. Transpilers are types of compilers that translate source code into functionally equivalent source code in another language. The main difference between a traditional compiler and a transpiler is that traditional compilers translates code to a lower level of abstraction while a transpiler translates code between languages that operate at more or less the same level of abstraction.</p><p>In a more technical sense, all <a href="https://en.wikipedia.org/wiki/Turing_completeness">turing-complete</a> languages can be transpiled between each other. A program written in a particular language can theoretically be translated into another program written in another turing-complete language. In other words, for every source code written in a particular programming language, there exists an equally functional source code in <strong>all</strong> turing-complete languages.</p><p>Javascript is 21 years old, so it’s definitely not a new language. Javascript is standardized by ECMAScript, which is a formal language specification that Javascript tracks. ES6 is one version of the spec that was finalised in June 2015. The very latest finalized version is ES7 and was finalised one year later in June 2016.</p><p>ES6 is also known as ES2015 (ECMAScript 2015) and is a significant update from ES5 containing major language feature updates. ES6 was a long awaited update after the almost 6 year post-ES5 hiatus. <a href="https://github.com/tc39/ecma262">New features are actively being worked</a> on under the ES.Next dynamic name and it looks like new features are to be <a href="http://www.2ality.com/2015/11/tc39-process.html">expected much faster than ever before</a>.</p><p>Since Javascript is an <a href="https://en.wikipedia.org/wiki/Interpreted_language">interpreted</a> language, programs can only be distributed as source code and therefore an <a href="https://en.wikipedia.org/wiki/Interpreter_%28computing%29">interpreter</a> or a <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation">JIT-compiler</a> is needed to execute the program.</p><p>These interpreters (more commonly called <em>engines</em>) are found mostly in web browsers or runtime environments (Node.js) and are <a href="http://kangax.github.io/compat-table/es6/">practically never fully compatible</a> with the latest ECMAScript specification.</p><p><a href="https://developers.google.com/v8/">V8</a> is one of the most popular Javascript engines, and is used in Google Chrome and Node.js, along with Chakra (Microsoft) and SpiderMonkey (Mozilla). Although all modern browsers are <a href="https://www.techopedia.com/definition/31094/evergreen-browser">evergreen</a> (automatically updating without user intervention), Javascript engines still lag behind spec updates, and when engines are updated, there is still a delay until the browsers or runtime environments update the engine that they use. For example, the very latest Node.js version v7.4.0 (at the time of writing) still uses V8 5.4.500.45, while the latest stable V8 version is 5.5.</p><p>Full ES5 support is very common, including all non-obsolete browsers and runtime environments. Therefore writing our code in ES5 would be quite a safe bet to ensure that it will run correctly across practically all modern devices. Having learned about transpilation, we can now realise that we can write our program in any ECMAScript version we want as long as we have a transpiler that transpiles the code down to ES5. We can even use non-standardised features (<a href="https://github.com/tc39/proposal-decorators">decorators</a>), or any new feature as long as we find a way to transpile it down to ES5.</p><p>Babel transpiles our ES6 code down to ES5. So, whenever you write something ES6 specific, this code is translated to functionally equivalent code in ES5; that’s the only magic involved!</p><p>Let’s start with the very basic.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><strong>Arrow Functions</strong></a></p><pre>// ES6<br>var x = () =&gt; {};</pre><pre>// ES5<br>var x = function() {};</pre><pre>==========================================================</pre><pre>// ES6<br>var x = x =&gt; x + 2;</pre><pre>// ES5<br>var x = function x(_x) {<br>  return _x + 2;<br>};</pre><pre>==========================================================</pre><pre>// ES6<br>var x = x =&gt; x =&gt; x + 2;</pre><pre>// ES5<br>var x = function x(_x) {<br>  return function (x) {<br>    return x + 2;<br>  };<br>};</pre><pre>==========================================================</pre><pre>// ES6<br>var x = function() {<br>  this.x = 2;<br>  return () =&gt; this.x;<br>};</pre><pre>// ES5<br>var x = function x() {<br>  // Keep reference to `this`<br>  var _this = this;<br>  this.x = 2;</pre><pre>return function () {<br>    // Use the referenced `this`<br>    return _this.x;<br>  };<br>};</pre><p>Since arrow functions do not create their own this context, we need to keep references to this for any subsequent closures.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><strong>Block-scoped variables</strong></a></p><pre>// ES6<br>if (x === 5) {<br>  let y = 2;<br>  doSomething(y);<br>}</pre><pre>if (x === 10) {<br>  let y = 3;<br>  doSomething(y);<br>}</pre><pre>==========================================================</pre><pre>// ES5<br>if (x === 5) {<br>  var y = 2;<br>  doSomething(y);<br>}</pre><pre>if (x === 10) {<br>  var _y = 3;<br>  doSomething(_y);<br>}</pre><p>To achieve block-scoped variables in ES5, the solution is to change variable names. In the example, we are defining two block-scoped variables y, and using them separately in two different if statement blocks. In the ES5 example, the variables are renamed so they refer to two different variables. Even though the code is semantically different, its behaviour is exactly retained with no side-effects.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"><strong>Template Literals</strong></a></p><pre>// ES6<br>var world = `world`;<br>var x = `Hello ${world}! The year is ${new Date().getFullYear()}!`</pre><pre>// ES5<br>var world = &#39;world&#39;;<br>var x = &#39;Hello &#39; + world +&#39;! The year is &#39; + new Date().getFullYear() + &#39;!&#39;;</pre><p>This is a very simple transformation, where parameters are extracted and normal string concatenation is used.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer"><strong>Enhanced Object Properties</strong></a></p><p>Shorthand properties and methods</p><pre>// ES6<br>var a = &#39;a&#39;, b = &#39;b&#39;;<br>var x = { a, b };</pre><pre>// ES5<br>var a = &#39;a&#39;, b = &#39;b&#39;;<br>var x = { a: a, b: b };</pre><pre>==========================================================</pre><pre>// ES6<br>var x = {<br>  a(b) {<br>    return b + 2;<br>  }<br>};</pre><pre>// ES5<br>var x = {<br>  a: function a(b) {<br>    return b + 2;<br>  }<br>};</pre><p>Computed properties</p><pre>// ES6<br>var x = {<br>  a: &#39;a&#39;,<br>  [new Date().getFullYear()]: 1<br>};</pre><pre>// ES5<br>var x = {<br>  a: &#39;a&#39;,<br>};<br>x[new Date().getFullYear()] = 1;</pre><pre>// Babel ES5<br>function _defineProperty(obj, key, value) {<br>  if (key in obj) {<br>    Object.defineProperty(obj, key, {<br>      value: value,<br>      enumerable: true,<br>      configurable: true,<br>      writable: true<br>    });<br>  } else {<br>    obj[key] = value;<br>  }<br>  return obj;<br>}</pre><pre>var x = _defineProperty({<br>  a: &#39;a&#39;<br>}, new Date().getFullYear(), 1);</pre><p>Things here start to get interesting. Babel has a number of helper functions to perform common tasks. In this case _defineProperty is a helper function that ensures that a defined property is always <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">enumerable, configurable and writable</a>, even if the property already exists. Using _defineProperty here is not explicitly necessary as computed properties can only be used when initializing an object and properties are set by default to be enumerable, configurable and writable:</p><pre>var x = { a: &#39;a&#39; };<br>var d = Object.getOwnPropertyDescriptor(x, &#39;a&#39;);</pre><pre>// true<br>d.enumerable &amp;&amp; d.configurable &amp;&amp; d.writable</pre><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator"><strong>Spread Syntax</strong></a></p><p>Function Calls and Simpler apply</p><pre>// ES6<br>var x = [1,2,3];<br>var y = (a, b, c) =&gt; { return a + b + c; }<br>var sum = y(...x);</pre><pre>// ES5<br>var x = [1, 2, 3];<br>var y = function y(a, b, c) { return a + b + c; };<br>var sum = y.apply(undefined, x);</pre><pre>==========================================================</pre><pre>// ES6<br>var x = [1,2,3];<br>var a = {<br>  y: (a, b, c, d, e) =&gt; { return a + b + c + d + e; }<br>};<br>var sum = a.y(0, ...x, 4);</pre><pre>// ES5<br>var x = [1, 2, 3];<br>var a = {<br>  y: function y(a, b, c) { return a + b + c; }<br>};<br>var sum = a.y.apply(a, [0].concat(x, [4]));</pre><pre>==========================================================</pre><pre>// ES6<br>var args = [1, 2], last = [4], x = (a, b, c, d, e) =&gt; {};<br>x(0, ...args, 3, ...last);</pre><pre>// ES5<br>var args = [1, 2], last = [4], x = function x(a, b, c, d, e) {};<br>x.apply(undefined, [0].concat(args, [3], last));</pre><p>Spread Properties</p><pre>// ES6<br>var x = { a: 1, b: 2 };<br>var y = { ...x, c: 3 };<br>// y === { a: 1, b: 2, c: 3 };</pre><pre>// ES5<br>var _extends = Object.assign; // Babel also polyfills Object.assign</pre><pre>var x = { a: 1, b: 2 };<br>var y = _extends({}, x, { c: 3 });</pre><p>Spreading objects is extremely useful and have interesting use-cases. Shallowly copying an object becomes as easy as:</p><pre>var original = { a: 1, b: 2 };<br>var copy = { ...original };</pre><p>For immutability, one can create a copy of an object and modify properties as easy as:</p><pre>var state = { id: 1, name: &#39;Bob&#39; };<br>return { ...state, name: &#39;Bobby&#39; };</pre><p>Create an object with default values:</p><pre>var defaults = { a: 1, b: 2};<br>var obj = { b: 3, c: 4 };<br>var merged = { ...defaults, ...obj };<br>// merged === { a: 1, b: 3, c: 4 }</pre><p>These are all possible by using Object.assign .</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></p><pre>// ES6<br>var x = (a, b, ...rest) =&gt; { return rest.map(x =&gt; a + b + x); }</pre><pre>// ES5<br>var x = function x(a, b) {<br>  for (var _len = arguments.length, rest = Array(_len &gt; 2 ? _len - 2 : 0), _key = 2; _key &lt; _len; _key++) {<br>    rest[_key - 2] = arguments[_key];<br>  }</pre><pre>return rest.map(function (x) {<br>    return a + b + x;<br>  });<br>};</pre><p>In this case, rest will be an array of all the arguments passed after a and b. rest is first initialized as an array with the length of all arguments subtracted by the number of fixed arguments (in this case 2). The array is then filled with the rest of the arguments one by one in the for loop.</p><p><strong>Classes</strong></p><p>Classes might be the most misunderstood concept in ES6. Javascript is a prototype-based language and ES6 classes are simply syntactic sugar over prototypical inheritance. There is no extra magic in classes apart from simple transformations that result in a clearer and simpler syntax, and a more standard way to deal with Object-Oriented Programming.</p><pre>// ES6<br>class Person {<br>  constructor(name) {<br>    this.name = name;<br>  }<br>  sayHi() {<br>    return `Hello, I&#39;m ${this.name}`;<br>  }<br>}</pre><pre>// ES5<br>var Person = function(name) { this.name = name; };</pre><pre>Person.prototype.sayHi = function() {<br>  return &#39;Hello, I\&#39;m &#39; + this.name;<br>};</pre><p>Babel produces a much more complicated transpilation.</p><pre>&quot;use strict&quot;;</pre><pre>var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i &lt; props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (&quot;value&quot; in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();</pre><pre>function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(&quot;Cannot call a class as a function&quot;); } }</pre><pre>var Person = function () {<br>  function Person(name) {<br>    _classCallCheck(this, Person);</pre><pre>this.name = name;<br>  }</pre><pre>_createClass(Person, [{<br>    key: &quot;sayHi&quot;,<br>    value: function sayHi() {<br>      return &quot;Hello, I&#39;m &quot; + this.name;<br>    }<br>  }]);</pre><pre>return Person;<br>}();</pre><p>The base semantics are practically the same but offers a stricter way to define classes in-line with the spec. For example, _classCallCheck ensures that the class is never called as a function (without new).</p><p><strong>New Built-In Methods</strong></p><p>ES6 also defines a number of additional methods in built-in objects such as String, Array and Object. These can be transpiled simply by defining the function as a polyfill.</p><pre>// String.prototype.repeat</pre><pre>// ES6<br>&quot;na&quot;.repeat(3);</pre><pre>// ES5<br>String.prototype.repeat = function(count) {<br>  var repeated = &#39;&#39;;<br>  for (var i = 0; i &lt; count; i++) {<br>    repeated += this;  <br>  }<br>  return repeated;<br>};</pre><p>This article should have given you a clearer picture of what is transpilation and why we need it. It’s not just there to ensure support older browsers, but also to write our code in whatever flavour of syntactic sugar we prefer without any worry for compatibility issues. After all, every programming language is just syntactic sugar over 1’s and 0&#39;s.</p><p>If you’re interested in how compilers/transpilers and Babel works internally or building your own Babel plugin, you should read the <a href="https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md">official Babel Plugin Handbook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a9e6624573" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>