<?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 Sagiv Ben Giat on Medium]]></title>
        <description><![CDATA[Stories by Sagiv Ben Giat on Medium]]></description>
        <link>https://medium.com/@sagiv.bengiat?source=rss-5d3a1aa409f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OCx288v3x-3Mu1VrLh3pww.jpeg</url>
            <title>Stories by Sagiv Ben Giat on Medium</title>
            <link>https://medium.com/@sagiv.bengiat?source=rss-5d3a1aa409f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:50:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagiv.bengiat/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[JavaScript — The prototype chain in depth]]></title>
            <link>https://medium.com/@sagiv.bengiat/javascript-the-prototype-chain-in-depth-347f10288f9f?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/347f10288f9f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 14:35:02 GMT</pubDate>
            <atom:updated>2019-11-25T14:35:02.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xvohVmeRrhYk8RGKopDs3A.png" /></figure><h3>JavaScript — The prototype chain in depth</h3><h4>Learn the concept of inheritance with the prototype chain</h4><p>Originally posted at my personal blog <a href="https://www.debuggr.io/js-prototype-in-depth/">debuggr.io</a></p><p>In this article we will learn about JavaScript’s prototype chain. We will see how objects connect to other objects and how we can implement “inheritance” and relationships between these objects.</p><h4>Our Goal</h4><p>As developers, our main task when we write code is usually to manipulate data. We get the data and store it some where, then we run functionality on that data. Wouldn’t it be nice to have the functionality and the relevant data bundled together on the same place? this would make it a lot easier for us.</p><p>Imagine a Player object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197f9c280600adf6ea2a28fab3bb1cd2/href">https://medium.com/media/197f9c280600adf6ea2a28fab3bb1cd2/href</a></iframe><p>What if we want to run functionality on that object, like changing the score. Where would we put a setScore method?</p><h4>Objects</h4><p>when we want to store related data we usually use objects, we use it like a box and we put inside it relevant peices. Before we dive in, lets first understand what an Object is and explore some of the ways we can create objects.</p><h4>Object Literal</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23b5299becc756b806898a90bfa463d/href">https://medium.com/media/f23b5299becc756b806898a90bfa463d/href</a></iframe><p>Objects with literal notation (or “Object initializer”) are an expression, each object initializer results in a new object being created whenever the statement in which it appears is executed.</p><p>We can also create or access the object’s properties with a dot notation or bracket notations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde2a94beac33f80f785e02b673ee032/href">https://medium.com/media/bde2a94beac33f80f785e02b673ee032/href</a></iframe><h4>Object.create</h4><p>Another option to create an Object is using the Object.create method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369b62bdba39681847729741a2365243/href">https://medium.com/media/369b62bdba39681847729741a2365243/href</a></iframe><p>Object.create will <strong>always</strong> return a new <strong>empty</strong> object, but we will get a bonus feature if we pass a different object to it. We will get back to it later on.</p><h4>Automating</h4><p>Obviously we wouldn’t want to create these object by hand every time, we might want to automate this operation. So lets create a function that will create a Player object for us.</p><h4>Factory Functions</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15b8f55de04346179d953fe7242b4fd4/href">https://medium.com/media/15b8f55de04346179d953fe7242b4fd4/href</a></iframe><p>This pattern is usually referred to as “Factory Functions”, as in sort of a conveyor belt in a factory that outputs objects, we pass in the relevant arguments and get back the Object we need.</p><p>what happens if we run this function twice?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c9d16a4421b9086a21fb4367e35d737/href">https://medium.com/media/8c9d16a4421b9086a21fb4367e35d737/href</a></iframe><p>we will get 2 objects with this shape:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb392de2c94e061c9c0b5bef09e437a6/href">https://medium.com/media/bb392de2c94e061c9c0b5bef09e437a6/href</a></iframe><p>Did you notice some duplications? Our setScore is stored for each instance, this is breaking the D.R.Y (Don&#39;t Repeat Yourself) principle.</p><p>What if we could store it somewhere else, once, and still be able to access it via the object instance: player1.setScore(1000)?</p><h4>OLOO — Objects Linked To Other Objects</h4><p>Let’s get back to Object.create, we said that it will <strong>always</strong> create an <strong>empty</strong> object but we will get a bonus feature if we pass an object to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0504bb54037b1e36b9c740b6559ff049/href">https://medium.com/media/0504bb54037b1e36b9c740b6559ff049/href</a></iframe><p>This code works exactly like our previous code with one important difference, our new object instance doesn’t hold the setScore method, it has a <strong>link</strong> to it in playerFunctions.</p><p>It turns out, that <strong>ALL</strong> objects in javascript have a special hidden property called __proto__ (pronounced &quot;dunder proto&quot;), and if that property is pointing to an object then the engine will treat this object&#39;s properties as if they were on the instance itself. In other words, every object can link to another object via the __proto__ property and access it&#39;s properties like they were it&#39;s own.</p><h4>️️⚠️ Note</h4><p>Don’t confuse __proto__ with the prototype property, prototype is a property that only exists on functions. __proto__ on the other hand is a property that <strong>only</strong> exists on objects. To make it more confusing, The __proto__ property is called [[Prototype]] in the <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots">EcmaScript specifications</a>.</p><p>We will comeback to that later on 🤔</p><p>Lets see an example with our code for a better visualization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64afa7e6b7925073c870910e59bb0a00/href">https://medium.com/media/64afa7e6b7925073c870910e59bb0a00/href</a></iframe><p>This will output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7cdc30ee94896885fbd70182d4d09f7/href">https://medium.com/media/c7cdc30ee94896885fbd70182d4d09f7/href</a></iframe><p>Which means, both player1 and player2 have access to the properties of playerFunctions, meaning they both can run setScore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be65603e26cba2e1c92f009c8bc522d8/href">https://medium.com/media/be65603e26cba2e1c92f009c8bc522d8/href</a></iframe><p>We achieved our goal here, we have objects with data and functionality attached to them and we didn’t break the D.R.Y principle.</p><p>But this seems like a lot of effort to put just for creating linked objects:</p><ol><li>We need to create the object.</li><li>We need to create a different object that holds our functionality.</li><li>We must use Object.create to link the __proto__ property to the functionality object.</li><li>We need to populate the new object with properties.</li><li>We need to return the new object.</li></ol><p>What if some of these tasks could be done for us?</p><h4>The new operator - A.K.A Constructor function</h4><p>In the previous example we saw that we have some “tasks” to do in order to create our linked object inside the factory function. JavaScript can do some of these tasks for us if we just use the new operator with a function invocation.</p><p>But before we see that in action, let’s make sure we are on the same page regarding what a function is.</p><h4>What is a function really?</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd84048f6f9408c37d2e818c086fbac5/href">https://medium.com/media/dd84048f6f9408c37d2e818c086fbac5/href</a></iframe><p>We all know what a function is right? We can declare it, then invoke it with parentheses (). But looking at the code above, we can also read or create properties on it, exactly like we can do with objects. So my conclusion here is that functions in JavaScript are not <em>just</em> functions, they are sort of a &quot;function &amp; object combination&quot;. Basically <strong>every</strong> function can be invoked <strong>AND</strong> can be treated like an object.</p><p>The prototype property</p><p>It turns out, that all functions (with the exception of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Use_of_prototype_property">arrow functions</a>) have a .prototype property on them.</p><p>Yeah, here is the warning again:</p><blockquote>Not __proto__ or [[Prototype]], but prototype.</blockquote><p>Now lets get back to the <strong>new operator</strong>.</p><p>Invoking with the new operator</p><p>This is how our function might look like with the new operator:</p><p>⚠️ If you are not 100% sure you understand how the this key word works, you might want to read <a href="https://www.debuggr.io/js-this-in-depth/">JavaScript - The &quot;this&quot; key word in depth</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caa24f7f14ce589207251553186fdd6b/href">https://medium.com/media/caa24f7f14ce589207251553186fdd6b/href</a></iframe><p>And this is the output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18331574cb3d27071d94bd92a834df5b/href">https://medium.com/media/18331574cb3d27071d94bd92a834df5b/href</a></iframe><p>Lets walk through that code (execution phase)</p><p>We are executing the Player function with the new operator, note that i changed the name of the function from createPlayer to Player, only because this is a convention among developers. This is a way to signal to the consumer of the Player function that this is a &quot;Constructor Function&quot; and should be invoked with the new operator.</p><p>When we invoke a function with the new operator, JavaScript will do 4 things for us:</p><ol><li>It will create a new Object.</li><li>It will assign the new Object to the this context.</li><li>It will linked the __proto__ property of that new object to the prototype property of the function. Player.prototype in our case.</li><li>It will return this new object, unless you return a different object.</li></ol><p>If we would write the automated steps done by JavaScript it might look like the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f122b74d3f04fb034e95c95c701e7cfc/href">https://medium.com/media/f122b74d3f04fb034e95c95c701e7cfc/href</a></iframe><p>Lets look at step #3:</p><blockquote>It will linked the __proto__ property of that new object to the prototype property of the function...</blockquote><p>Meaning we can put any methods on Player.prototype and they will be available to our newly created object.</p><p>And this is exactly what we did:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82957659a0dcc2682b10a79f160a24e7/href">https://medium.com/media/82957659a0dcc2682b10a79f160a24e7/href</a></iframe><p>So this is how we can create objects linked to other objects with the Constructor functions.</p><p>By the way, if we didn’t use the new operator, JavaScript wouldn&#39;t do these tasks for us, we would just end up mutating or creating some properties on the this context. Remember this option, we will use this trick when we will do sub-classing.</p><p>There are ways to make sure the function was called with the new operator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e9fe47d2e225b619d0cd9738c5ae711/href">https://medium.com/media/4e9fe47d2e225b619d0cd9738c5ae711/href</a></iframe><p>Again, for an in depth explanation about the this key word you can read <a href="http://localhost:8000/js-this-in-depth/">JavaScript - The &quot;this&quot; key word in depth</a>.</p><h4>Class</h4><p>If you don’t like to write factory functions by hand or you don’t like the constructor function syntax or manually checking if the function was called with the new operator, JavaScript also provides a class (since ES2015). Keep in mind though, that classes are <strong>mostly</strong> a syntactic sugar over functions and they are very different from the traditional classes in other languages, we are still using a &quot;prototypal inheritance&quot;.</p><p>A quote from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">MDN</a>:</p><blockquote>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.</blockquote><p>Lets convert our “constructor function” to a class step by step:</p><h4>Declare a class</h4><p>We use the class key word and name our class the same way we named our constructor function from the previous section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5afc7387951b9f54db22f9d23d8230c2/href">https://medium.com/media/5afc7387951b9f54db22f9d23d8230c2/href</a></iframe><h4>Create a constructor</h4><p>We will take the constructor function’s body from the previous section and create a constructor method for our class with it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a1a77153e21cdcdc65d82fb26cc8087/href">https://medium.com/media/2a1a77153e21cdcdc65d82fb26cc8087/href</a></iframe><h4>Add methods to the class</h4><p>Every method we want to attach to the Player.prototype can be simply declared as a class method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006831382d9c702dc455a96615b96627/href">https://medium.com/media/006831382d9c702dc455a96615b96627/href</a></iframe><p>Now the entire code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d52cbade4281a9403afcf4cd08f8e3/href">https://medium.com/media/32d52cbade4281a9403afcf4cd08f8e3/href</a></iframe><p>When we run the code, we get the same output as before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e542b1b2500e6701c37f540b1eef1ad9/href">https://medium.com/media/e542b1b2500e6701c37f540b1eef1ad9/href</a></iframe><p>As you can see, class works and behave the same as a function with a prototype chain, its just a different syntax. You also get a built-in check that the class function was invoked with the new operator.</p><h4>Sub-Classing — A.K.A Inheritance</h4><p>What if we wanted a special kind of Player, maybe a paid user Player who has unlocked features that a regular Player doesn&#39;t have, such as the ability to change the user-name.</p><p>So lets see what our goal here:</p><ul><li>We want that a regular player will have a userName, a score and a setScore method.</li><li>We also want a paid user player that will have all the things a regular player has + a setUserName method, but obviously we don&#39;t want the regular player to have this ability.</li></ul><p>Before we dive into it, lets visualize a chain of linked objects:</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a806b0d750cf0b645f95f4dd253421e4/href">https://medium.com/media/a806b0d750cf0b645f95f4dd253421e4/href</a></iframe><p>We know that if a property is not directly on the object, the engine will look for this property on the linked object (if exists) via the __proto__ property. But what happens if the property we are looking for is not there as well? Well as we previously learned, <strong>all</strong> objects have a __proto__ property, so the engine will check the next linked object via the __proto__ property, and if the property we are looking for is not there? well i think you get it, the engine will keep going up the chain via the __proto__ property until it hits a dead end, i.e a null reference, which is basically the Object.prototype.__proto__.</p><p>So if we step through the code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07901479f8613bbcb3606d00805b065d/href">https://medium.com/media/07901479f8613bbcb3606d00805b065d/href</a></iframe><ol><li>double has no toString method ✖️.</li><li>Go through double.__proto__</li><li>double.__proto__ is pointing to Function.prototype which is an object that contains the toString method. Check ✔️</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050117f77c1906d541560f58c06b2eba/href">https://medium.com/media/050117f77c1906d541560f58c06b2eba/href</a></iframe><ol><li>double has no hasOwnProperty method ✖️.</li><li>Go through double.__proto__</li><li>double.__proto__ is pointing to Function.prototype.</li><li>Function.prototype has no hasOwnProperty method ✖️.</li><li>Go through Function.prototype.__proto__.</li><li>Function.prototype.__proto__ is pointing to Object.prototype.</li><li>Object.prototype is an object that contains the hasOwnProperty method. Check ✔️</li></ol><p>Here is a small animated gif to demonstrate the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ucRHHqoAcx48me7L.gif" /><figcaption>Showing the steps of the prototype chain</figcaption></figure><p>Now back to our task of creating a paid user entity. We will go all the way again, we will implement this feature with the “OLOO pattern”, “Constructor Functions” pattern and with classes. This way we will see the tradeoffs for each pattern and feature.</p><p>So lets dive in to sub-classing. 💪</p><h4>OLOO — Sub Classing</h4><p>This is the implementation of our task with the OLOO and factory function pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd1286a3279e442074d28ca8096e0333/href">https://medium.com/media/dd1286a3279e442074d28ca8096e0333/href</a></iframe><p>This will output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5e7b83b9587e51b33169b4e96991d4e/href">https://medium.com/media/b5e7b83b9587e51b33169b4e96991d4e/href</a></iframe><p>As you can see, our createPlayer function implementation didn&#39;t change, but with the createPaidPlayer function we needed to pull some tricks.</p><p>In createPaidPlayer we are using the createPlayer to create the initial new object so we won&#39;t need to duplicate the logic of creating a new player, but unfortunately its linking our __proto__ to the wrong object, so we need to fix that with the Object.setPrototypeOf method. We pass it the target object (the newly created object that we need to fix it&#39;s __proto__ pointer) and we pass it the correct object we want it to point to, e.g paidPlayerFunctions.</p><p>We are not done yet though, because now we broke the linkage to the playerFunctions object which holds the setScore method. This is why we needed to link between paidPlayerFunctions and playerFunctions, again with Object.setPrototypeOf. This way we make sure our paidPlayer is linked to paidPlayerFunctions and then from there to playerFunctions.</p><p>This is a lot of code for a 2 level chaining, imagine the hassle for 3 or 4 levels of chaining.</p><h4>Constructor Functions — Sub Classing</h4><p>Now lets implement the same thing with constructor functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c645c6d91debeccc688b5bf410ecaaf/href">https://medium.com/media/1c645c6d91debeccc688b5bf410ecaaf/href</a></iframe><p>And we should get similar output to the previous implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6def9a49d857002665c7b667896b5075/href">https://medium.com/media/6def9a49d857002665c7b667896b5075/href</a></iframe><p>This is effectively the same results that we got with the factory function patten but with some stuff that were automated for us by the new operator. It might saved us some lines of code but it did introduce some other challenges.</p><p>Our first challenge was how do we use the Player function to get the logic of creating the initial Player. We did this by calling it without the new operator (against all our instincts!) and using the .call method which allowed us to explicitly pass a reference for this, this way the Player function is not operating as a constructor method so it won&#39;t create a new object and assign it to this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c457e603c0260bb7de2f4964c12c7c63/href">https://medium.com/media/c457e603c0260bb7de2f4964c12c7c63/href</a></iframe><p>We are only using Player here to mutate our passed in this which is basically the newly created object inside the context of PaidPlayer.</p><p>Another challenge we have, is to link the instance returned by PaidPlayer to the functionality that instances of Player have, we did that with Object.setPrototypeOf and we linked PaidPlayer.prototype to Player.prototype.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61d9687099aa1b1bccd2326fff9a11c/href">https://medium.com/media/c61d9687099aa1b1bccd2326fff9a11c/href</a></iframe><p>As you can see, the more things our engine is doing for us the less code we need to write, but as the amount of abstraction grow its harder for us to keep track about what is happening under the hood.</p><h4>Class — Sub Classing</h4><p>With classes we get much, much more abstraction, this means less code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/477669bc6984b5a59badbfe1ca0355cf/href">https://medium.com/media/477669bc6984b5a59badbfe1ca0355cf/href</a></iframe><p>And we get the same output as we got with the constructor functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a92f31c551700bfb2617b18f86d181a/href">https://medium.com/media/1a92f31c551700bfb2617b18f86d181a/href</a></iframe><p>So as you see, classes are nothing but a syntactic sugar over the constructor functions. Well sort of 🤔</p><p>Remember this line from the docs:</p><blockquote>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance…</blockquote><p>Yeah, <strong>primarily</strong>.</p><p>When we used the extends key word, we needed to use the super function, why?</p><p>Remember this (strange) line from the “Constructor Functions” section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac192d6fc1c9a7391c201060d98e3e17/href">https://medium.com/media/ac192d6fc1c9a7391c201060d98e3e17/href</a></iframe><p>so super(userName, score) is kind of a way to mimic it.</p><p>Well if we want to be a bit more accurate here, under the hood it uses a new feature that introduced with ES2015: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct">Reflect.construct</a>.</p><p>Quoting from the docs:</p><blockquote>The static Reflect.construct() method acts like the new operator, but as a function. It is equivalent to calling new target(…args). It gives also the added option to specify a different prototype.</blockquote><p>So we don’t need to “hack” the constructor functions anymore. Basically under the hood the super is implemented with Reflect.construct. Its also important to mention that when we extend a class, inside the constructor body we can&#39;t use this before we run super(), because this is uninitialized yet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/278306285ec2b5afd9592d93784845ce/href">https://medium.com/media/278306285ec2b5afd9592d93784845ce/href</a></iframe><h4>Wrapping up</h4><p>We learned about the the different ways we can connect objects, attaching data and logic and bundle it all together. We saw how “inheritance” works in JavaScript, chaining objects to other objects via the __proto__ property, sometimes with multiple levels of chaining.</p><p>We see it again and again, the more abstraction we get the more “stuff” are going on under the hood, which makes it harder for us to keep track on whats going on with our code.</p><p>Each pattern has it’s pros and cons:</p><ul><li>With Object.create we need to write more code but we have a more fine-grained control over our objects. Though it becomes tedious to do deep level chaining.</li><li>With the constructor functions we get some automated tasks done by JavaScript but the syntax may look a bit strange. We also need to make sure that our functions get invoked with the new key word or we will face nasty bugs. Deep level chaining isn&#39;t that great as well.</li><li>With classes we get a cleaner syntax and a built-in check that it was invoked with the new operator. Classes shines the most when we do &quot;inheritance&quot;, we just use the extends key word and invoking super() instead of jumping hoops with the other patterns. The syntax is also closer to other languages and it looks like an easy thing to learn. Though this is also a downside because as we saw, its so different than classes in other languages, we still use the old &quot;Prototypal Inheritance&quot; with a lot of layers of abstractions over it.</li></ul><p>Hope you found this article helpful, if you have something to add or any suggestions or feedbacks I would love to hear about them, you can tweet or DM me <a href="https://mobile.twitter.com/sag1v">@sag1v</a>. 🤓</p><p>For more articles you can visit <a href="https://www.debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=347f10288f9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React race condition bug]]></title>
            <link>https://medium.com/@sagiv.bengiat/react-race-condition-bug-61704f4e79de?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/61704f4e79de</guid>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Sat, 26 Oct 2019 21:52:00 GMT</pubDate>
            <atom:updated>2019-10-29T16:53:42.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*hGrFd_91ozAME-t8hA2ASQ.png" /></figure><h4>The bug that you don’t even know you have</h4><p><em>Originally posted on my personal blog </em><a href="https://www.debuggr.io/react-race-condition/"><em>debugger.io</em></a></p><p>If your application is depended on a state that gets updated asynchronously, there is a good chance you have a bug. The bad news is that its hard or even almost impossible to reproduce in production. The good news is that you now know about it and we will learn how to reproduce it and fix it.</p><p>In this article I will use a demo application that I used in a previous article <a href="https://debuggr.io/react-update-unmounted-component">React state update on an unmounted component</a>. Although reading it is not a prerequisite, I do think it is a good idea to read it.</p><p><em>👀 I’ve uploaded a </em><a href="https://github.com/sag1v/react-race-conditions-debuggrio"><em>starter repo to github</em></a><em> so you won’t have to copy paste the code. You can clone and run it locally or use the </em><strong><em>import</em></strong><em> feature of </em><a href="https://codesandbox.io/s/"><em>codesandbox.io</em></a></p><p>This is how our application looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*M4B9k3I-3NGYFaXu.gif" /><figcaption>Showing a drop down of pets and selecting a dog or cat</figcaption></figure><p>Basically we are selecting a pet and showing some info that we “fetch” from the server.</p><p>This is how the Pets component looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e48d962e4686df26831741db0c31a1/href">https://medium.com/media/46e48d962e4686df26831741db0c31a1/href</a></iframe><p>Our Pets component uses the useReducer hook to store some state. Lets see the petsReducer and the initial state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e52acc8c2acd7d3991350f3775189ea6/href">https://medium.com/media/e52acc8c2acd7d3991350f3775189ea6/href</a></iframe><p>As you can see theres nothing special here, a simple reducer that manage our state.</p><p>The Pets component also use the useEffect hook for some side effects like fetching the data of our selected pet, we invoke the getPet function which returns a Promise and we dispatch the FETCH_PET_SUCCESS action with the returned data as the payload to update our state.</p><p>Note that getPet is not really hitting a server end-point, its just a function that simulate a server call. This is how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d3820641962f73eda117e9e175c0695/href">https://medium.com/media/3d3820641962f73eda117e9e175c0695/href</a></iframe><p>As you see, its nothing but a setTimeout inside a Promise.</p><h4>The bug</h4><p>So far everything looks great, we chose a pet type from the Drop-down and we get the info 1000ms later. Though when we are dealing with asynchronous operations we can&#39;t determine at what point of time exactly we are running our code, moreover we need to handle 2 or more operations simultaneously. What happens when the first operation is slower than the second operation? How are we dealing with the results?</p><p>Imagine this scenario:</p><ol><li>The user select the Cats option.</li><li>We are fetching the Cats data from the server.</li><li>The user now select the Dogs option.</li><li>We are fetching the Dogs data from the server.</li><li>for some reason, the Dogs data received before the Cats data (yeah it happens!).</li><li>We display the Dogs data on the screen.</li><li>Couple of milliseconds later, the Cats data is received.</li><li>We display the Cats data on the screen, but the Drop-down still shows the Dogs as selected.</li></ol><p>This is how it looks like on the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*E7NF17p-ce9fxyDY.gif" /><figcaption>showing the bug, selecting cats then dogs and displaying cats data</figcaption></figure><p>How did we managed to do it? just a hard-coded longer delay for the cats type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da42b5917d71b88397705f32f4f17ec8/href">https://medium.com/media/da42b5917d71b88397705f32f4f17ec8/href</a></iframe><h4>The problem</h4><p>Why is that happening? lets revisit our data fetching logic in useEffect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/617d34e278c6faad3421d28e0978ad46/href">https://medium.com/media/617d34e278c6faad3421d28e0978ad46/href</a></iframe><p>As you can see, our state update (using dispatch) is running inside the .then() function. It will run only when the Promise returned by getPet is resolved. When the user select a different option before the Promise is resolved, we trigger getPet again with its own .then() function. When the second (but faster) call is resolved, we run the function passed to .then() and updating the state with the passed in data object (Dogs data). When the first call is resolved, we run the function passed to it&#39;s .then() and updating the state with the passed in data object, a <strong>WRONG</strong> and none relevant data! Yes, the one with the cats 🙀🙀🙀</p><h4>The solution</h4><p>One possible solution is to cancel the first request, we can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort">AbortController.abort()</a> (⚠️ experimental technology) or we can implement a <a href="https://github.com/facebook/react/issues/5465#issuecomment-157888325">Cancelable promise</a>.</p><p>If you can’t or don’t want to use these solutions, there is another solution. Basically our problem is that we store a key for the selected pet but we update the data object without checking that the data correspond to that key. If we will check that the key and the data correspond and only then we will trigger the update, we will not have this problem.</p><p>Let’s see how can we do that.</p><h4>Trial #1 (❌)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9c0dd1ead1d55415603586c0ef4b5cf/href">https://medium.com/media/c9c0dd1ead1d55415603586c0ef4b5cf/href</a></iframe><p>Here we are storing the selectedPet key in a different temp variable _previousKey and then inside the .then() function we check if the &quot;current&quot; selectedPet matches _previousKey.</p><p>This won’t work! We just override the _previousKey variable each time the useEffect is running, so we end up matching the same value over and over. This is also true if we were to declare the _previousKey variable outside the useEffect at the function component level scope, because it will run on each render.</p><h4>Trial #2 (❌)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7a1be9a4fb4be1641e99685dd440fbd/href">https://medium.com/media/d7a1be9a4fb4be1641e99685dd440fbd/href</a></iframe><p>Here we are declaring the _previousKey outside the component&#39;s scope, this way we always get the latest value and not overriding it on each render or effect call.</p><p>Although it seems to be working fine and our problem is solved, we introduce a new bug. If we will have 2 different instances of Pets rendered, they will &quot;share&quot; this variable and will override it to each other.</p><h4>Trial #3 (✔️)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0702e68f5e207152c3614c30f1bacd3d/href">https://medium.com/media/0702e68f5e207152c3614c30f1bacd3d/href</a></iframe><p>In trial #2 we made some progress but we ended up with kind of a “global” variable. What was missing is a variable attached to the instance of our component. In class components we would use the this key word to reference the instance -- this._previousKey. In function components the this key word doesn&#39;t reference the component&#39;s instance because there is no instance (you can read more about the this key word in <a href="https://www.debuggr.io/js-this-in-depth/">JavaScript - The &quot;this&quot; key word in depth</a>). React solved the lack of instance issue with the useRef hook. Think of it as a mutable state object for your component that doesn&#39;t trigger a re-render when you update it (unlike useState or useReducer).</p><p>This way we can safely store the _previousKey and compare it to the current selectedPet and only if they match, update our state with the relevant data object. If you run the code now you will see that we fixed our bug 🙌</p><h4>Trial #3.5 (✔️)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e56eb3197c19da6fc268e7eddae6e21f/href">https://medium.com/media/e56eb3197c19da6fc268e7eddae6e21f/href</a></iframe><p>This is another possible solution. Instead of keeping track on the matching values, we can just use a simple flag that indicates if we should keep with our update state operation. Every time the effect runs we are initialising the abort variable with false, inside the cleanup function of the effect we set it to true. the effect will only run at first render and every time one of the values passed to the dependencies array is changed. The cleanup function will run just before each cycle of the effect and when the component is unmounted.</p><p>This works great and probably the preferred solution for some people, but keep in mind that now your effect can’t have other none related logic with none related dependencies in the array (and it shouldn’t have!), because then the effect will re-run if those dependencies change and will trigger the cleanup function which will flip the abort flag.</p><p>Nothing is stopping you from having multiple useEffect functions, one for each logic operation.</p><h4>Good news</h4><p>Note that this is not a react specific problem, this is a challenge that most if not all of the UI libraries or framework are facing, due to the nature of asynchronous operations and state management. The good news is that the react team is working on a great feature called <a href="https://reactjs.org/docs/concurrent-mode-intro.html">Concurrent Mode</a> and one of its features is <a href="https://medium.com/suspense">Suspense</a> which should cover this issue out of the box.</p><h4>Wrapping up</h4><p>We saw that a simple component with a state and asynchronous operation can produce a nasty bug, we might not even know it’s there until we face it in production. My conclusion is that whenever we update a state (can be local or in a state manager) inside an asynchronous callback, we must check if the arguments that we passed to the asynchronous function is corresponding to the data we received in the callback.</p><p>Hope you found this article helpful, if you have a different approach or any suggestions I would love to hear about them, you can tweet or DM me <a href="https://mobile.twitter.com/sag1v">@sag1v</a>. 🤓</p><p>For more articles you can visit <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61704f4e79de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React state update on an unmounted component]]></title>
            <link>https://medium.com/@sagiv.bengiat/react-state-update-on-an-unmounted-component-79d44e41bba5?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d44e41bba5</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Fri, 25 Oct 2019 20:19:50 GMT</pubDate>
            <atom:updated>2019-10-26T10:46:23.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZbOQgB1rfosFw9do0TWhw.png" /></figure><h4>90% of react developers faced this warning at least once</h4><p><em>Originally posted on my personal blog </em><a href="https://www.debuggr.io/react-update-unmounted-component/"><em>debugger.io</em></a></p><p>If you are a react developer, there is a good chance that you faced this warning at least once:</p><blockquote>Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</blockquote><p>In order to understand how to fix this warning, we need to understand why it is happening. We will need to reproduce it in a consistent way.</p><p><em>⚠️ Note that in this article i use react hooks, if you are using react class components you may see in the warning a reference to componentWillUnmount instead of the useEffect cleanup function.</em></p><h4>Reproduce the warning</h4><p><em>👀 I’ve uploaded a </em><a href="https://github.com/sag1v/react-async-state-debuggrio"><em>starter repo to github</em></a><em> so you won’t have to copy paste the code. You can clone and run it locally or use the </em><strong><em>import</em></strong><em> feature of </em><a href="https://codesandbox.io/s/"><em>codesandbox.io</em></a></p><p>If we look at the warning again, we can see that there are 2 main parts playing a role here:</p><ol><li>A React state update</li><li>An unmounted component</li></ol><p>In order to create these, we will build this simple drop-down with asynchronous data fetching</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*S02RuLRQZ7N3iDep.gif" /><figcaption>Showing a drop down of pets and selecting a dog or cat</figcaption></figure><h4>State updates</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ede1121e0bc0cb01662041bc7ee3bc3/href">https://medium.com/media/7ede1121e0bc0cb01662041bc7ee3bc3/href</a></iframe><p>Here we have the Pets component, it uses the useReducer hook to store some state. Lets see the petsReducer and the initial state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d3612fee8b880eab8c96c1a8832c1c/href">https://medium.com/media/09d3612fee8b880eab8c96c1a8832c1c/href</a></iframe><p>As you can see theres nothing special here, a simple reducer that manage our state.</p><p>The Pets component also use the useEffect hook for some side effects like fetching the data of our selected pet, we invoke the getPet function which returns a Promise and we dispatch the FETCH_PET_SUCCESS action with the returned data as the payload to update our state.</p><p>Note that getPet is not really hitting a server end-point, its just a function that simulate a server call. This is how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/861af8ad86e7d35acb859c64df201080/href">https://medium.com/media/861af8ad86e7d35acb859c64df201080/href</a></iframe><p>As you see, its nothing but a setTimeout inside a Promise .</p><p>Our App is basically just rendering this Pets component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62f86f1ef369ebfc845de8e0afcbba76/href">https://medium.com/media/62f86f1ef369ebfc845de8e0afcbba76/href</a></iframe><p>Ok first part of our problem is accomplished, thats the React state update , now we need to create the 2nd part - An unmounted component .</p><h4>Un-mounting a component</h4><p>This is relatively easy to accomplish using a state and a conditional rendering, we will store a boolean flag at the App level and we will render the &lt;Pets /&gt; component accordingly while using a toggle button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f4f8095880aee274f7b8424cef0ea0/href">https://medium.com/media/e4f4f8095880aee274f7b8424cef0ea0/href</a></iframe><p>This is how our application should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*07CUYefjVcbiQ8BX.gif" /><figcaption>application with a toggle button that show or hide a drop down</figcaption></figure><h4>Reproduction</h4><p>Ok, now that we have both conditions for the warning to appear lets try it. If we look again at the warning:</p><blockquote>Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</blockquote><p>Lets focus on this line here:</p><blockquote>React state update on an unmounted component</blockquote><p>If we select a pet, we know that it will take our getPet at least 1 second to return our data. After our data is returned we are updating the state, if we will un-mount the Pet component before that 1 second (before our data is received) we will trigger an update on an unmounted component.</p><p>So this is how you do it: *If you can’t make it with a 1 second delay, try to increase the timeOut in the getPet function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kER1MPadAIcZeyO0.gif" /><figcaption>showing the error</figcaption></figure><p>OK this is part one of our task, now we need to fix it.</p><h4>The fix</h4><p>You may be surprised but the fix for this issue is actually the easy part. React is providing a clear and a very helpful message, with a guidance to the solution:</p><blockquote>To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</blockquote><p>Well, we may not exactly subscribing to anything here, but we do have an asynchronous tasks, remember the getPet asynchronous function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e40dc2b77908694633b0ba8014f31ce/href">https://medium.com/media/5e40dc2b77908694633b0ba8014f31ce/href</a></iframe><p>So basically we just need to <strong>NOT</strong> update the state in the callback if the component is not mounted already.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b11219e4d135e41dca5d61cbe87dcde/href">https://medium.com/media/7b11219e4d135e41dca5d61cbe87dcde/href</a></iframe><p>Every time our effect will run, we are setting a local variable mounted to true, we set it to false on the cleanup function of the effect (like suggested by react). And most importantly, we are updating the state if and only if that value is true, that is if the component is un-mounted meaning our variable is set to false, it wont enter the if block.</p><p>So this is it, we are no longer receiving the warning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*rSyGNm6xcBe_DTmx.gif" /><figcaption>the fixed application with no warning</figcaption></figure><h4>Bonus Tip</h4><p>We set a local variable inside the useEffect scope, if we want to re-use this variable inside another useEffect we can use useRef, which is sort of a none rendering state for components.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ae9217c514c095685a7eda176f6303f/href">https://medium.com/media/9ae9217c514c095685a7eda176f6303f/href</a></iframe><p>The great thing about hooks is that we can extract this tiny logic to a custom hook and reuse it across components. One possible implementation can be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ba3475970b9e18aac63f06825e049a/href">https://medium.com/media/42ba3475970b9e18aac63f06825e049a/href</a></iframe><h4>Wrapping up</h4><p>We saw how a simple component with an asynchronous state update may yield this common warning, think about all those components you have with a similar case. Make sure you check if the component is actually mounted before you perform a state update.</p><p>Hope you found this article helpful, if you have a different approach or any suggestions i would love to hear about them, you can tweet or DM me <a href="https://mobile.twitter.com/sag1v">@sag1v</a>. 🤓</p><p>For more articles you can visit <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d44e41bba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript — The “this” key word in depth]]></title>
            <link>https://medium.com/@sagiv.bengiat/javascript-the-this-key-word-in-depth-b5e94b4f9764?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e94b4f9764</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 21:30:56 GMT</pubDate>
            <atom:updated>2019-10-26T10:47:36.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript — The “this” key word in depth</h3><h4>Follow these 5 rules to determine what “this” is bound to</h4><p>Originally posted on <em>my personal blog </em><a href="https://www.debuggr.io/js-this-in-depth/">debuggr.io</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*sqysAFfGmnLqYPgbcZJgfQ.png" /></figure><p>In this article we will learn how to identify and recognize what this refers to in a given context and we will explore what rules and conditions are taken under consideration by the engine to determine the reference of the this key word.</p><h3><strong>The challenge</strong></h3><p>One of the most challenging concepts in JavaScript is the this key word, maybe because it is so different than other languages or maybe because the rules to determine it’s value are not that clear.</p><p>Lets quote a paragraph from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">MDN</a>:</p><blockquote>In most cases, the value of this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called…</blockquote><p>Challenging indeed, on one hand it says that this is determined at run-time — i.e, a dynamic binding. but on the other hand it says <em>In most cases…</em>, meaning it can be statically bound. How doe’s something can be both static and dynamic and how can we be sure which one it is at a given context? This is exactly what we are going to find out now!</p><h3><strong>What is static?</strong></h3><p>Let’s look at an example of something static in JavaScript, like the “Local variable environment” — often refers to as scope.</p><p>Every time a function is invoked, a new execution context is created and pushed to the top of the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Call_stack">call-stack</a> (when our application starts, there is already a default execution context which is often referred to as the global-context).<br>Each execution context contains a “Local variable environment” which usually referred to as the local-scope (or global-scope in the global execution context).<br> <br>Given this code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f860359be47aaa529f85bb544de4c0c/href">https://medium.com/media/5f860359be47aaa529f85bb544de4c0c/href</a></iframe><p>Just by looking at foo’s declaration, we know what scope message belongs to — the local scope of the foo function execution-context. Because var statement <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">declares a function-scoped variable</a>.</p><p>Another example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c689f97b4a95bb2ca9d67f856a002e8/href">https://medium.com/media/9c689f97b4a95bb2ca9d67f856a002e8/href</a></iframe><p>Notice how inside the block we get a different result than outside of it, that’s because let statement <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">declares a block scope local variable</a>.</p><p>We know what to expect just by looking at the deceleration of the function because scope in JavaScript is statically determined (lexical), or at “Design time” if you will. <br>No matter where and how we will run the function, it’s local scope won’t change.<br>In other words, we can say that the scope of a variable is depended on <strong>where</strong> the variable<strong> was</strong> declared.</p><h3><strong>What is dynamic?</strong></h3><p>If static means “<strong>WHERE</strong> something <strong>WAS</strong> declared”, we might say dynamic means “<strong>HOW</strong> something <strong>WILL</strong> run”.</p><p>Lets imagine for a moment that scope was dynamic in JavaScript:<br><em>note, this is not a real syntax </em>⚠️</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3c85a7810e53ec4dcde276a9c2bcd2/href">https://medium.com/media/8f3c85a7810e53ec4dcde276a9c2bcd2/href</a></iframe><p>As you can see, in contrast to the static scope example we now <strong>can’t</strong> determine the final value of message just by looking at the declaration of foo, we will need to see where and how its being invoked. That’s because the value of the message variable is determined upon the execution of foo with a set of conditions. <br>It may look strange but this is not that far away from the truth when we are dealing with the this context, every time we run a function the JavaScript engine is doing some checks and conditionally set the reference of this.</p><p>There are some rules, and <strong>order matters</strong>. <br>You know what, lets just write them out as if we are writing the engine ourselves:<br><em>note, this is not a real syntax</em> ⚠️</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf7b6318f736480606a3d9a4b405d1b/href">https://medium.com/media/fdf7b6318f736480606a3d9a4b405d1b/href</a></iframe><p>Seems a bit cumbersome and complex, maybe this flow chart will provide a better visualization:</p><figure><img alt="A flow chart to determine what this refers to" src="https://cdn-images-1.medium.com/max/919/1*8OSdlQn6g3ynMizt95O-ag.png" /></figure><p>As you can see we can split the flow into two parts:</p><ol><li><strong>Static</strong> binding — The arrow function</li><li><strong>Dynamic</strong> binding — The rest of the conditions</li></ol><p>Lets walk them through:</p><ol><li><strong>Is it an </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this"><strong>arrow function</strong></a><strong>?</strong> —<br> If the relevant execution context is created by an arrow function then do nothing, meaning this will be whatever it was set by the wrapping execution context.</li><li><strong>Was the function called with </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><strong><em>new</em></strong></a><strong>?</strong> — <br>When invoking a function with the new key word the engine will do some things for us:<br><strong>a</strong>. Create a new object and set this to reference it.<br><strong>b</strong>. Reference that object’s __proto__ (called [[Prototype]] in the <a href="https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots">spec</a>) to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">function’s </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">prototype object</a>.<br><strong>c</strong>. Return the newly created object (this).<br>So for our purpose to determine what this is, we know it will be a new object that was created automatically just by invoking the function with the new key word.</li><li><strong>Was the function called with </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call"><strong><em>call</em></strong></a><strong> / </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply"><strong><em>apply</em></strong></a><strong> or </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind"><strong><em>bind</em></strong></a><strong>?</strong> — <br>Then set this to whatever passed as the first argument.</li><li><strong>Was the function called as an </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions"><strong>object method</strong></a><strong>? </strong>— <br>Then set this to the object left to the dot or square brackets.</li><li><strong>Is </strong><strong><em>strict mode </em>on?</strong> — <br>Then this is <em>undefined</em></li><li><strong>default case</strong> — <br>this will reference the global<strong><em> </em></strong>/ window<strong><em> </em></strong>object.</li></ol><h3><strong>The Quiz</strong></h3><p>The best way to measure our understanding is to test ourselves, so lets do a quiz. open the flowchart on a new tab and walk through it from top to bottom for each question (<strong>answers are listed below</strong>):</p><p><em>Try to answer what will be printed to the console</em>.</p><p><strong>Question #1</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd81980521b3554107f9385083dbd3ea/href">https://medium.com/media/fd81980521b3554107f9385083dbd3ea/href</a></iframe><p><strong>Question #2</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011b4b87723ea0e4a137ff13b95d2ae3/href">https://medium.com/media/011b4b87723ea0e4a137ff13b95d2ae3/href</a></iframe><p><strong>Question #3</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/743af77a4770c4e017eed1741a8a8580/href">https://medium.com/media/743af77a4770c4e017eed1741a8a8580/href</a></iframe><p><strong>Question #4</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc1a1892857e9df3ecceb1040b6aad1c/href">https://medium.com/media/bc1a1892857e9df3ecceb1040b6aad1c/href</a></iframe><p><strong>Question #5</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e0b431f5d286719e2f140707c6edb4/href">https://medium.com/media/61e0b431f5d286719e2f140707c6edb4/href</a></iframe><p><strong>Question #6</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f94b2689ba979bd1aa269b57edec662b/href">https://medium.com/media/f94b2689ba979bd1aa269b57edec662b/href</a></iframe><p><strong>Question #7</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1deb1664db4f1532a4a7e8ba3b66dfc/href">https://medium.com/media/f1deb1664db4f1532a4a7e8ba3b66dfc/href</a></iframe><p><strong>Question #8</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734dfdd95ff0b69020cd4d37ad942a2f/href">https://medium.com/media/734dfdd95ff0b69020cd4d37ad942a2f/href</a></iframe><p><strong>Question #9</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1879db56256b1881b98753a2ff25babe/href">https://medium.com/media/1879db56256b1881b98753a2ff25babe/href</a></iframe><p><strong>Question #10</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0e85a836c81c36a2915348c1603c98e/href">https://medium.com/media/d0e85a836c81c36a2915348c1603c98e/href</a></iframe><h3><strong>Bonus questions</strong></h3><p><strong>Question #11</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6cda8d83cd5f007a648b84b7b910625/href">https://medium.com/media/d6cda8d83cd5f007a648b84b7b910625/href</a></iframe><p><strong>Question #12</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c497982b9e6ed0f80afa7546b09e799/href">https://medium.com/media/7c497982b9e6ed0f80afa7546b09e799/href</a></iframe><h3><strong>Answers</strong></h3><p><strong>Answer #1</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd81980521b3554107f9385083dbd3ea/href">https://medium.com/media/fd81980521b3554107f9385083dbd3ea/href</a></iframe><p>Result — myObj.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with new? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>No</strong>.</li><li>Was logThis called as an object method? — <strong>Yes</strong>, myObj is left to the dot.</li></ol><p><strong>Answer #2</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011b4b87723ea0e4a137ff13b95d2ae3/href">https://medium.com/media/011b4b87723ea0e4a137ff13b95d2ae3/href</a></iframe><p>Result — window.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with <strong><em>new</em></strong>? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>No</strong>.</li><li>Was logThis called as an object method? — <strong>No</strong>.</li><li>Is <strong><em>strict mode</em></strong> on? — <strong>No</strong>.</li><li>default case — window (or global).</li></ol><p><strong>Answer #3</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/743af77a4770c4e017eed1741a8a8580/href">https://medium.com/media/743af77a4770c4e017eed1741a8a8580/href</a></iframe><p>Result — window.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>Yes</strong>, whatever this was set in the wrapping context. In this case the wrapping context is the “<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Global_context">Global execution context</a>” which inside it this refers to the window<strong> </strong>/ global<strong> </strong>object.</li></ol><p><strong>Answer #4</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc1a1892857e9df3ecceb1040b6aad1c/href">https://medium.com/media/bc1a1892857e9df3ecceb1040b6aad1c/href</a></iframe><p>Result — myObj.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with <strong><em>new</em></strong>? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>Yes</strong>, whatever passed in as the first argument — myObj<strong> </strong>in this case.</li></ol><p><strong>Answer #5</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e0b431f5d286719e2f140707c6edb4/href">https://medium.com/media/61e0b431f5d286719e2f140707c6edb4/href</a></iframe><p>Result — window.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>Yes</strong>, whatever this was set in the wrapping context. In this case the wrapping context is the “<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Global_context">Global execution context</a>” which inside it this refers to the window<strong> </strong>/ <em>global</em><strong> </strong>object.</li></ol><p>Answer #6</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f94b2689ba979bd1aa269b57edec662b/href">https://medium.com/media/f94b2689ba979bd1aa269b57edec662b/href</a></iframe><p>Result — <strong>The object created by </strong>logThis.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with <strong><em>new</em></strong>? — <strong>Yes</strong>, then this is an auto created object inside the function.</li></ol><p><strong>Answer #7</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1deb1664db4f1532a4a7e8ba3b66dfc/href">https://medium.com/media/f1deb1664db4f1532a4a7e8ba3b66dfc/href</a></iframe><p>Result — undefined.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with new? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>No</strong>.</li><li>Was logThis called as an object method? — <strong>No</strong>.</li><li>Is strict mode on? — <strong>Yes</strong>, this is undefined.</li></ol><p><strong>Answer #8</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734dfdd95ff0b69020cd4d37ad942a2f/href">https://medium.com/media/734dfdd95ff0b69020cd4d37ad942a2f/href</a></iframe><p>Result — window.<br>Explanation:</p><ol><li>Is logThisan arrow function? — <strong>No</strong>.</li><li>Was logThis called with new? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>No</strong>.</li><li>Was logThis called as an object method? — <strong>No</strong>.</li><li>Is strict mode on? — <strong>No</strong>.</li><li>default case — window (or global).</li></ol><p><strong><em>Answer #9</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1879db56256b1881b98753a2ff25babe/href">https://medium.com/media/1879db56256b1881b98753a2ff25babe/href</a></iframe><p>Result — The object created by myClass.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with new? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>Yes</strong>, whatever passed in as first argument. OK, but we are passing this! what is this refers to inside the logThat execution context?<br>Lets check:<br>3.1. Is logThat an arrow function? — <strong>No</strong>.<br>3.2. Was logThat called with new? — <strong>No</strong>.<br>3.3. Was logThat called with call / apply / bind? — <strong>No</strong>.<br>3.4. Was logThat called as an object method? — <strong>Yes</strong>, this is the object left to the dot — The auto created object inside myClass in this case.</li></ol><p><strong>Answer #10</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0e85a836c81c36a2915348c1603c98e/href">https://medium.com/media/d0e85a836c81c36a2915348c1603c98e/href</a></iframe><p>Result — The object created by myClass.<br>Explanation:</p><ol><li>Is logThis an arrow function? — <strong>Yes</strong>, then this refers to whatever the wrapping context set it, myClass in this case.<br>Lets check what this refers to in the wrapping context:<br> 1.1. Is <em>myClass</em> an arrow function? — <strong>No</strong>.<br> 1.2. Was myClass called with new? — <strong>Yes</strong>, then this refers to the newly created object (the instance).</li></ol><p><em>note that we are using class fields which is a </em><a href="https://github.com/tc39/proposal-class-fields#class-field-declarations-for-javascript"><em>proposal currently in stage 3</em></a></p><p><strong>Answer #11</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6cda8d83cd5f007a648b84b7b910625/href">https://medium.com/media/d6cda8d83cd5f007a648b84b7b910625/href</a></iframe><p>Result — The btn element.<br>Explanation:<br>This is a tricky question because we never talked about event handlers attached to DOM elements. You can look at event handlers that are attached to DOM elements as if the function is a method inside the element’s object, In our case the btn object. We can look at it as if we invoked btn.click() as btn.logThis(). Note that this is not exactly whats going on under the hood, but this visualization of the invocation of the handler can help us with the formation of our “mental model” regarding the setting of this. <br>You can read more about it on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_a_DOM_event_handler">MDN</a></p><p>Now lets walk through the flow:</p><ol><li>Is logThis an arrow function? — <strong>No</strong>.</li><li>Was logThis called with new? — <strong>No</strong>.</li><li>Was logThis called with call / apply / bind? — <strong>No</strong>.</li><li>Was logThis called as an object method? — <strong>Yes </strong>(sort of), in our case btn is left to the dot.</li></ol><p><strong>Answer #12</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c497982b9e6ed0f80afa7546b09e799/href">https://medium.com/media/7c497982b9e6ed0f80afa7546b09e799/href</a></iframe><p>Result — window.<br>Explanation</p><ol><li>Is <strong>logThis</strong> an arrow function? — <strong>Yes</strong>, whatever <strong>this</strong> was set in the wrapping context. In this case the wrapping context is the “Global execution context” which inside it this refers to the window / global object.</li></ol><h3><strong>Wrapping up</strong></h3><p>We now understand that the assignment of this can be both dynamic and static (lexical).</p><ul><li>Arrow functions will make it static and won’t even bother to mutate this at all. which means we will need to understand what this was set to in the wrapping execution context.</li><li>Plain Functions will make it dynamically, meaning it depends on how the function was invoked.</li></ul><p>It may look intimidating and complex now, you probably thinking how would you remember the flow chart. Well you don’t need to, you can save or print this flow-chart or maybe even make your own. Every time you need to know what this refers to in your code just look at it and start going through the conditions. Rest assure, you will need to look at the this flow-chart less and less as time goes by.</p><p>I hope it was informative and helpful, if you have any further clarifications or corrections, feel free to comment or DM me on twitter (<a href="https://twitter.com/sag1v">@sag1v</a>).</p><p>You can read more of my articles at my blog <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e94b4f9764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Answering StackOverflow questions can make you better]]></title>
            <link>https://medium.com/appsflyerengineering/answering-stackoverflow-questions-can-make-you-better-d946594e2788?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d946594e2788</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 13:03:49 GMT</pubDate>
            <atom:updated>2020-01-14T10:21:24.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>Answering StackOverflow questions can make you a better programmer</h3><h4>~8 reasons why you should answer StackOverflow questions</h4><p>Originally posted on <em>my personal blog </em><a href="https://www.debuggr.io/answering-so-questions.md/">debuggr.io</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*5omofRFy4Rslm1vwa2_arw.png" /><figcaption>The StackOverflow Logo</figcaption></figure><h4><strong>Why should I bother?</strong></h4><p>Why should we bother ourselves to try and solve other people’s challenges? We have our own challenges and sometimes are up against a tight deadline. I’m often asked this by friends and peers, so here is a list I made of the reasons that motivate me to answer <a href="https://stackoverflow.com/">StackOverflow</a> questions <em>(not in a particular order)</em>:</p><h4><strong>The Motivation List</strong></h4><p><em>- Points, Credit, Prestige<br>- Kindness, giving back to the community <br>- Gain experience with real world challenges<br>- Keep up with the race and stay ahead of the game<br>- Learning new things “by mistake”<br>- Improve tech communication skills<br>- Improve English skills (as a second language)<br>- Document your solutions</em></p><p><em>I’m mostly mentioning </em><a href="https://stackoverflow.com/">StackOverflow</a><em> here because I think it’s the most comfortable platform to share knowledge, but everything I write here is relevant to any other platform.</em></p><h3>Points, Credit &amp; Prestige</h3><p>Well, I wanted to start with this one because it’s kind of “The elephant in the room”. Most of us like getting credit for the things we do and who doesn’t <strong>LOVE</strong> points and ratings? I sure do!<br>So yeah, I think it’s a motivation, although likely the most selfish item on my list. Is it at the top of the list? Nope. Read on and you may realize that it’s actually the least rewarding one (but still, rewarding).</p><h3>Kindness and giving back to the community</h3><p>OK, it’s a cliche. I know! But it can’t be helped, in most cases when we help someone it makes us feel good and satisfied. I gain so much knowledge from the “<em>internet</em>” (which is basically a bunch of people that help me whether they know it or not), so it’s only natural to want to give something back.</p><p>As a developer, <a href="https://stackoverflow.com/">StackOverflow</a> is and still is one of the best tools I have.<br>“Giving back to the community” may be a cliche but this is the foundation stones which our community (should I write society?) is built upon. <br>So if you have the chance and the ability, Give Back To The Community, do it with kindness and respect. And eventually you’ll find that what can be a small effort on your end, can have a big impact for the person sitting on the other side.</p><p><em>You may notice that this item on my motivation list is the only “none 100% selfish” motivation, I mean this is the only motivation that addresses the actual benefits gained by others, and not myself.</em></p><blockquote>Engineering our culture, as much as our products, since 1824. &gt;&gt;<a href="http://bit.ly/382jyey">View Open Roles</a></blockquote><h3>Gain experience with real world challenges</h3><p>Consider the following scenario: You are learning a new language / technology / feature / design pattern, you have probably been watching some online courses and following some tutorials. I would even reckon, most if not all of them, provide simple examples under controlled laboratory conditions. But alas, none of us has the privilege to work under these conditions, we live in the real world.</p><p>The great thing about trying to answer questions on <a href="https://stackoverflow.com/">StackOverflow</a> is that you accept a <strong><em>”real world”</em></strong> challenge.</p><p>As a beginner to the subject, you may not be able to provide a high-quality answer fast enough before the coveted great shiny check-mark was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/36/1*dsfEtnoY40Q59N15egRlRA.png" /><figcaption>StackOverflow’s green check-mark sign</figcaption></figure><p>And another answer was marked as accepted. That’s OK, though we do love points (as stated above) we are not here just for them, we also want to gain some experience. Rest assured, you have already gained experience - not only with a real world problem but we have also been lucky enough to see the solution.</p><p>We also gained experience with debugging, experience with solving (or trying to solve) hard and complex problems. Maybe the problem wasn’t that hard after all, but there wasn’t enough information provided by the <a href="https://meta.stackoverflow.com/questions/253162/what-is-an-op-when-referring-to-stack-exchange">OP</a> (Original Poster), so you gained the experience of asking the right questions to lead the OP to a “purified” version of the problem, cleaning up the noise and revealing the exact and accurate problem the OP was really facing. This is a huge value gained as a problem-solver, it’s beyond learning a new feature or a language, this is you becoming a better engineer.</p><p>I consider this as a bit of a hack, in a “normal” way, we gain experience through time (x years of experience). So basically experience is measured like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*gTm4iiHKP3mEBMrh1O5_cQ.png" /></figure><p>And here we are kind of fast-tracking our hands-on experience through multi-threading, and not from our actual day job. So we are basically gaining the experience of others, and we do it in a relatively short period of time — the power of concurrency (we’re scaling our skill set).</p><h3>Keep up with the race and stay ahead of the game</h3><p>As opposed to the previous item on the list (which mostly addressed beginners) this one is mostly relevant for experienced developers. As an experienced developer you probably want to keep up with all the new stuff that coming out, or maybe you want to be that go-to person when people need help with new stuff. Maybe the tech you are working with isn’t the newest thing out there or maybe the version is a bit outdated.</p><p>Answering questions on StackOverflow may help you keep up with new technologies as they emerge, and sharpen your skills, enabling you to gain experience with that new feature that just came out last month.</p><h3>Learning new things “by mistake”</h3><p>Sometimes when you are trying to answer a question, you’ll notice that the <a href="https://meta.stackoverflow.com/questions/253162/what-is-an-op-when-referring-to-stack-exchange">OP </a>(Original Poster) is using a stack or a library you are not experienced with. I mean, you know the tech the OP is using, but there is a cool library or feature you never tried. In order to help, you may need to read the basics and look through the DOCS or maybe even try an API you never tried.</p><p>This is awesome, because you just learned a new thing, and learning is part of our lives as developers. And maybe this new thing you just learned may even end up in one of your next projects. Who knows? 🤷‍♂️</p><h3>Improve tech communication skills</h3><p>One of the most important skills for developers is the “tech communication skill”, it allows you to articulate a problem or a solution which the other side (other team members) can easily understand. The ability to execute something that “lives” in your head is hard enough, but to explain it to others so they can be part of the operation… that’s a skill, a <strong>great</strong> skill to have on your tool-belt.</p><p>To be able to write a high quality answer (or question, by the way) will require you to “stretch” that skill, this will let you enhance it.</p><p>If there is one common thing for all of the best answers (and questions!) on StackOverflow is that they are all well-phrased and the author managed to easily convey their idea to the reader. Some use humor, others use analogies and some use dry facts, it doesn’t matter as long as the reader gets the idea.</p><h3>Improve English skills (as a second language)</h3><p>Well this one is very personal and maybe considered as a niche, but English may not be your native language, well it’s not my native language and you probably already picked that up 😏 ). With English being the universal language of technologists around the globe, and not all are born native speakers, this is a good way to gain confidence in your English skills, and can ultimately carry over to getting involved in others ways — such as contributing code or documentation to open source projects.</p><h3>Document your solutions</h3><p>You have taken the time to write great and useful solutions, why not document and preserve them somewhere? StackOverflow can be a great place to store your solutions, you get a free space <strong>AND</strong> a great searching tool to track them later, you can basically see it as your own personal wiki.</p><p>Another cool thing about it is that you can use your StackOverflow profile page as a “portfolio of case studies”. I mean attaching it to a CV or including it in your LinkedIn account gives future recruiters a chance to see how you approach problems, and how you communicate solutions with others. Not to mention that it’s always good to be perceived as a person who helps others. 😊</p><h3>Summing it up</h3><p>As you can see, there are a lot of reasons that should motivate you to be active as a StackOverflow user (or any other similar platform).</p><p>While some are for your own personal benefit and some can benefit your environment, all of them are eventually rewarding and satisfying.</p><p>With that said, make sure it doesn’t interrupt your job or daily tasks. What works for me is to allocate a specific time for that within my free time and make sure I don’t exceed it.</p><p>I hope this was a good read and if you have any more “motivation items” to add to the list or any feedback please share, I would love to read it.</p><p>You can read more of my articles at my blog <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d946594e2788" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsflyerengineering/answering-stackoverflow-questions-can-make-you-better-d946594e2788">Answering StackOverflow questions can make you better</a> was originally published in <a href="https://medium.com/appsflyerengineering">AppsFlyer Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Frontends - Integrate React with other applications and frameworks]]></title>
            <link>https://medium.com/@sagiv.bengiat/integrate-react-with-other-applications-and-frameworks-94d443e3cc3f?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d443e3cc3f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Sat, 17 Nov 2018 20:26:35 GMT</pubDate>
            <atom:updated>2019-10-26T10:48:22.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*plk4lC_IFMEaJo1AuE9Afg.png" /></figure><h3>Micro Frontends — <strong>Integrate React with other applications and frameworks.</strong></h3><h4>Allow a react application to be part of a micro frontends architecture</h4><p>Originally posted on <em>my personal blog</em> <a href="https://www.debuggr.io/react-micro-frontends/">debuggr.io</a></p><p>This is a followup article for this tweet</p><h3>sagiv ben giat on Twitter</h3><p>I just realized that some people don&#39;t know this about @reactjs so i&#39;m sharing. You can call ReactDOM.render multiple times. Not only that but it actually won&#39;t re-mount the entire application, instead it will trigger a diffing. 1/3 https://t.co/4zAVi3TFWf #reactjs #javascript</p><p>This may address only specific use cases, like already existing applications or mini applications that you can’t or won’t rewrite, or stand-alone application which you need to provide to others to implement on their websites and you want to provide an API to interact with your application.</p><p>In this article / tutorial we will build a very basic react “widget” (a Counter!) and a very basic react application. we will see what problems we face when we try to interact with the two applications and how <a href="https://reactjs.org/docs/react-dom.html#render">ReactDOM.render</a> API help us to pass data in and out the applications while keeping the great unidirectional flow.</p><p><em>Note: you can implement this with any view framework / library,<br>I just chose to do it with 2 react applications because i mostly work with react, but you can pass and get data from a react app with angular / vue / jQuery or vanilla JS. it doesn’t matter.</em></p><h3>Lets Code</h3><p>To make it easy to start and not waste time on building the “widget” and main application, <a href="https://github.com/sag1v/react-external-integration-starter">i published a repository</a> that will save you the time and hassle.</p><p><a href="https://github.com/sag1v/react-external-integration-starter">sag1v/react-external-integration-starter</a></p><p>This repo holds 2 folders:<br>1. main-app (the main application project) <br>2. counter-app (our counter widget project)</p><p><em>Both of them built using </em><a href="https://github.com/facebook/create-react-app"><em>create-react-app</em></a><em> (because it’s easy, it’s fast and it’s just works)</em></p><p><em>Note that you don’t have to do it with create-react-app, you may already have a js build system running on your existing application.<br>You may want to read </em><a href="https://reactjs.org/docs/add-react-to-a-website.html"><em>Add React to a Website</em></a><em> from the DOCS</em></p><h3><strong>Clone</strong></h3><p>clone the repository to your local drive</p><pre>git clone <a href="https://github.com/sag1v/react-external-integration-starter.git">https://github.com/sag1v/react-external-integration-starter.git</a></pre><h3>Install And Run</h3><p>main-app</p><pre>cd main-app<br>npm install<br>npm start</pre><p>counter-app</p><pre>cd counter-app<br>npm install<br>npm start</pre><p>You may have prompted with this message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*8cA6QBDtAM_X9dI4G_pa5w.jpeg" /><figcaption>a message of “Something is already running on port 3000”</figcaption></figure><p>Just confirm with “y” and press enter.</p><p>If both applications are running fine, you should see something similar to this</p><p>main-app page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*7cUAmRlYJnAuPq6z8k8Big.jpeg" /><figcaption>main app starter page</figcaption></figure><p>counter-app page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*D1Hkwku4kxP6xCq_45BGdQ.jpeg" /><figcaption>counter app starter page</figcaption></figure><p>In our main-app there’s nothing special going on right now, but lets look at the counter-app</p><p>counter-app/src/Counter.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/952c8b8b37d7bf8eb371c4e41755129e/href">https://medium.com/media/952c8b8b37d7bf8eb371c4e41755129e/href</a></iframe><p>counter-app/src/index.js</p><pre>const el = document.getElementById(&#39;counter-app&#39;);<br>ReactDOM.render(&lt;Counter /&gt;, el);</pre><p>As you can see, there’s nothing fancy here. just a counter with 2 buttons.<br>The only thing we want to focus on is our props.<br>We want to be able to pass props from the outside, props likeinitialCount,onCountUpdate and title. This is easy when we are inside the context of the Counter react app, but we want to be able to do that outside of that, from a different application.</p><p>But before we solve our problem, lets see what is our problem. lets render the Counter inside our main-app.</p><p>To do that, we will need to run a build of our counter and include the bundled files of the counter-app in the index.html file of our main-app.</p><p>In your command line, make sure you are at the /counter-app folder and run</p><pre>npm run build</pre><p>This will generate the js and CSS files for production.<br><em>Note: for simplicity and ease, i tweaked the build process of the </em><em>counter-app.<br>Every time we run build, the generated files will be placed in:</em></p><pre>main-app/public/counter_dist</pre><p><em>This will make it easier for us to see the changes to the code as we go, so we don’t need to manually copy and paste the files there.</em></p><p>If all went well you should see these files in your main-app folder:</p><pre>-main-app<br> -public<br>  -counter_dist<br>   -static<br>    -css<br>     react-counter.css<br>    -js<br>     react-counter.js</pre><p>Now go to</p><pre>main-app/public/index.html</pre><p>Make sure you include the CSS and JS files of the counter , we also need to render a div with the counter-app id</p><pre>&lt;div id=&quot;counter-app&quot;&gt;&lt;/div&gt;</pre><p>Your index.html should end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/386b106485ff591fb26de12edbfd41dc/href">https://medium.com/media/386b106485ff591fb26de12edbfd41dc/href</a></iframe><p>And this is how our page should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*-1HyMDxPQlJVPwukVirIyQ.jpeg" /></figure><p>So now we have both our main-app and Counter on the same <strong>page</strong>, but this is not what wanted. we want the Counter <strong>inside </strong>the main-app.<br>We could render the counter-app div inside our App component instead of just throwing it in the index.html file, but this won’t work.</p><p><strong>In fact, lets see why it won’t work</strong><br>Remove this from index.html</p><pre>&lt;div id=&quot;counter-app&quot;&gt;&lt;/div&gt;</pre><p>And move it to App.js (main-app/src/App.js)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7763edd6dcd40e533fd76f2d2ebc2b97/href">https://medium.com/media/7763edd6dcd40e533fd76f2d2ebc2b97/href</a></iframe><p>After you hit save, you can see the Counter is no longer displayed on our screen. In fact we have an invariant 200 error in console with a link to <a href="https://reactjs.org/docs/error-decoder.html/?invariant=200">https://reactjs.org/docs/error-decoder.html/?invariant=200</a></p><blockquote><strong>Target container is not a DOM element.</strong></blockquote><p>In other words, our counter-app div container is not there.</p><p>But wait, didn’t we just render it inside our App.js?<br>This message is coming from our Counter application, from these lines:</p><pre>const el = document.getElementById(&#39;counter-app&#39;);<br>ReactDOM.render(&lt;Counter /&gt;, el);</pre><p>What happens here is that our Counter application is running <strong>before </strong>our main-app application. So App.js didn’t run yet and we didn’t pass a valid second argument to ReactDOM.render.</p><h3>Our First Real Challenge</h3><p>So this is the first challenge we need to solve, we want to control the order of the scripts or moreover the order of the function calls.<br>Of course this is one of the oldest challenges we have in JavaScript and the solution to that is modules, bundlers etc.<br>Our script tag is at the end of the body block but the problem here is that webpack is injecting the main-app scripts in run-time to the end of the body block as well. This is why we can’t run Counter after the main-app scripts.<br>We could hack around with the async / defer attributes of the script tag but that won’t solve our problem, even if it did solve the ordering, it won’t solve our real problem: get data in and out of the Counter and control it.</p><h3>First Part Of The Solution</h3><p>Maybe, instead of just running this code</p><pre>const el = document.getElementById(&#39;counter-app&#39;);<br>ReactDOM.render(&lt;Counter /&gt;, el);</pre><p>We will wrap it inside a function, and expose it globally. this way, other applications can decide when to run it and will do it explicitly.</p><p>Before we dive in to the actual implementation, we also want to enable an un-mount of our widget. ReactDOM has another method just for that <a href="https://reactjs.org/docs/react-dom.html#unmountcomponentatnode">unmountComponentAtNode</a></p><p>So we need a reference to the counter-app container for both methods. <br>lets modify our index.js of count-app to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91bbe111cfa351ba6ce12d75b36eeece/href">https://medium.com/media/91bbe111cfa351ba6ce12d75b36eeece/href</a></iframe><p>As you can see, we expose a global object ReactCounter with 2 methods:<br>1. mount<br>2. unmount</p><p>Both will use ReactDOM under the hood.</p><p>Now lets build counter-app with our command (make sure you are in /counter-app folder)</p><pre>npm run build</pre><p>If we refresh the page of main-app we won’t see the counter but we also won’t get an error, as we never tried to render to a none existing element. that’s good.</p><p>Now we can call our mount function inside App.js.<br>Lets do that after the first render of App.js with the <a href="https://reactjs.org/docs/react-component.html#componentdidmount">componentDidMount</a> life cycle method, this way we are sure the counter-app div is already rendered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1b56e0753cc58bd985689b1068b95c2/href">https://medium.com/media/a1b56e0753cc58bd985689b1068b95c2/href</a></iframe><p>After you hit save you can see our counter below the react logo, <strong>INSIDE</strong> our App.js! 👊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*H4zVLVjyNYNdiuoLdZQXOg.jpeg" /></figure><p>We know we can un-mount it as well, so just for fun lets toggle it with a click on the react logo.<br>Lets make these changes in our App.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38214aef3df36689aece9891cf3bd657/href">https://medium.com/media/38214aef3df36689aece9891cf3bd657/href</a></iframe><p>As you can see, we added a state with a showCounter key.<br>we replaced <a href="https://reactjs.org/docs/react-component.html#componentdidmount">componentDidMount</a> with <a href="https://reactjs.org/docs/react-component.html#componentdidupdate">componentDidUpdate</a> so we can react to changes of the satet, and we conditionally call ReactCounter.mount or ReactCounter.unmount based on showCounter .<br>We also added a toggleCounter handler and attached it to the onClick prop of the logo’s &lt;img/&gt; element.</p><p>You should end up with this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*bBPbDmdsf67UcYDhQgcVSw.gif" /></figure><h3>Passing props</h3><p>While this is nice, we also want to pass data to our Counter . if we look at our mount function, there’s nothing stopping us to pass it parameters and it will pass parameters to the &lt;Counter/&gt; component.<br>In counter-app/src/index.js you should change your code to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de0a36e10a634872c767974df6b4007/href">https://medium.com/media/4de0a36e10a634872c767974df6b4007/href</a></iframe><p>After you build counter-app with npm run build you can go to main-app/src/App.js and pass an object props to mount.<br>I passed {title: ‘Whaaa! cool’}</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b93f47b1fe53ee4b646ddbffb47bc455/href">https://medium.com/media/b93f47b1fe53ee4b646ddbffb47bc455/href</a></iframe><p>And this is how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*RLUNhTXe1ZBH-ZqC4hf6SQ.jpeg" /></figure><h3>It’s like the render you know and love!</h3><p>Now lets revisit a quote from my tweet above:</p><blockquote>You can call ReactDOM.render multiple times. Not only that but it actually won’t re-mount the entire application, instead it will trigger a diffing…</blockquote><p>Now we know it won’t re-mount the entire application, that’s what ReactDOM.render and ReactDOM.<a href="https://reactjs.org/docs/react-dom.html#unmountcomponentatnode">unmountComponentAtNode</a> are for. but what do we mean by “trigger a diffing”?</p><p>Well it’s like the render method of our class components in this case. when the life cyclerender method is invoked, it will trigger the <a href="https://reactjs.org/docs/reconciliation.html">Reconciliation</a> process. ReactDOM.render will do the same.</p><p>Lets put it to test, we can store the title value in the state of our App.js , change it with an input and see if our Counter can get the updated values.</p><p>In our App.js we will change to this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7062e6b32d7e58f9b8903339758d984/href">https://medium.com/media/a7062e6b32d7e58f9b8903339758d984/href</a></iframe><p>And this is how it should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*zyDrik0_nTEbF3WdWRR3oA.gif" /></figure><h3>Get data back</h3><p>Well, we also wanted to get data back from our widget, if you remember we can pass onCountUpdate callback to get the current count . So if we can pass props as an object, nothing is stopping us from passing functions inside that object.</p><p>Lets add a div in our App.js that will show the current count.<br>We will need to pass a handler to the Counter and store the current count in App.js ‘s state as well.</p><p>Lets change App.js to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdf54c4cbe966bde14d523afe6303d2a/href">https://medium.com/media/bdf54c4cbe966bde14d523afe6303d2a/href</a></iframe><p><em>Note that we also pass the </em><em>initialCount prop with a value of </em><em>3 to the </em><em>Counter.</em><br>And this is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*4JKkap2CiDY798z03guhng.gif" /></figure><p>We did it! we are communicating with an “isolated” react application, we pass data to it and able to get data back from it. but we are not done yet! we may have solved our general challenge but if we think about it, we still have 2 major issues. we can’t create multiple instances and our code is imperative as hell. Let’s make it more “react’ish”.</p><h3>The multiple instances challenge</h3><p>Looking at our Counter’s API in index.js :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de0a36e10a634872c767974df6b4007/href">https://medium.com/media/4de0a36e10a634872c767974df6b4007/href</a></iframe><p>We can see that we have a problem, the Counter forces us to use the same id for its container. If we think about it, this is not the Counter’s responsibility to decide what kind of container to render itself, and maybe it should not even do the job of querying the DOM to get the container. maybe the Counter should just get a reference to the element? Lets try it.</p><p>In counter-app/src/index.js change to this code:<br><em>don’t forget to run </em><em>npm run build after the change.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/674aedcf6e272e47b44f3477ae459c0a/href">https://medium.com/media/674aedcf6e272e47b44f3477ae459c0a/href</a></iframe><p>In main-app/src/App.js change to this code:<br><em>note how we omit the &quot;counter-app”</em><em>id attribute from our </em><em>div’s</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b782731a4a1093200b88c378bce717d6/href">https://medium.com/media/b782731a4a1093200b88c378bce717d6/href</a></iframe><p>You should see a similar result to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*GgaKNUs3yCZGpahGoBwXZQ.gif" /></figure><p>What we did here is that we passed a reference to the actual element to the mount and unmount methods. we could instead pass a selector like .myClass or #myId and use document.querySelector, but i think passing the element itself is respecting the separation of concerns in a better way.<br>Yay, we now have multiple instances support! 💪</p><h3>The imperative code challenge</h3><p>One of the core concepts and methodology of react is a Declarative way to write UI’s. we do it with Components.<br>If we look at our code in App.js we see a mess, its an imperative hell (i remind you that this is only a simple Counter and not a real world app!).<br>What if we wrap this entire code in a reusable component, lets say we call it… &lt;ReactCounter /&gt; so its easy to distinguish it from the real Counter.js.</p><p>Lets see how such component would look like:<br><em>You can create the new file </em><em>main-app/src/ReactCounter.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48c628046e7e1b5e8fe0ca87740c06d5/href">https://medium.com/media/48c628046e7e1b5e8fe0ca87740c06d5/href</a></iframe><p>Look how clean and concise it is.<br><em>note that we are using a </em><a href="https://reactjs.org/docs/react-api.html#reactpurecomponent"><em>React.PureComponent</em></a><em> here, you may need a regular </em><em>React.Component.</em></p><p>Lets look on how App.js is using this new component:<br><em>Don’t forget to </em><em>import ReactCounter from ‘./ReactCounter’</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ddc769b756f643ab9eb953d21a6d60/href">https://medium.com/media/10ddc769b756f643ab9eb953d21a6d60/href</a></iframe><p>Now this looks much better, we can’t even tell that ReactCounter is an external stand-alone application. it looks and behave like any other component.</p><p>Of course the page should look the same as before, we just improved our code.</p><h3>Wrapping up</h3><p>We observed on how we can interact with a separate and isolated react application, i chose to use another react application to interact with it but this is not limited only to react. you can call our mount function and pass it the props object with any framework you work with, these are just JavaScript functions.<br>As i mentioned at the top, this may solve a specific problem. This is not the “normal” way we write our applications, but it’s good to know we can do that when we need it, thanks to the flexible and solid API of react and ReactDOM.</p><p>Thank you for your patience, I hope it helped you in some way.<br>If you have any comments / suggestions or questions, please feel free to comment.</p><p>I would love to see some examples of this approach with other frameworks, take the bundled files of the counter-app and interact with other frameworks / libraries.</p><h3><strong>References</strong></h3><p>It’s highly recommended to read <a href="https://reactjs.org/docs/integrating-with-other-libraries.html#integrating-with-other-view-libraries">Integrating with Other View Libraries</a> from the react DOCS.</p><p>You can read more of my articles at my blog <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d443e3cc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript == VS === The truth]]></title>
            <link>https://medium.com/@sagiv.bengiat/javascript-vs-the-truth-45992607c27?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/45992607c27</guid>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[comparison]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 12:19:20 GMT</pubDate>
            <atom:updated>2019-10-26T10:48:42.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2UEEcR-tKQamc9eHNn2-xA.png" /><figcaption>JavaScript equality code example</figcaption></figure><h4>The truth behind the double and triple equal in JavaScript</h4><p>Originally posted on <em>my personal blog </em><a href="https://www.debuggr.io/javascript-tripple-doubl-equal/">debuggr.io</a></p><p>Some of the most frequently-asked interview questions of Front-End are about Equality comparisons and sameness in JavaScript (ECMAScript).</p><p>And the queen of these questions is:</p><blockquote>What is the difference between the “double equals” and the “triple equals”?</blockquote><p>Well, we all know the answer for that. The triple equal checks for types while the double equal isn’t.</p><p>That could be a short and nice answer for this question but unfortunately it is <strong>FALSE</strong>.</p><p>As per the specs, <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">7.2.14 Abstract Equality Comparison</a> you can clearly see at the first check:</p><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(x) is the same as <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(y), then</blockquote><blockquote>Return the result of performing <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Strict Equality Comparison</a> x === y.</blockquote><p>Well there we have it, the “double equal” should check the type in both sides of the operator and if they are the same, it will delegate the rest of the work to the “triple equal” (Strict Equality Comparison).</p><p>Ok then, is the “triple equal” checking for types then?</p><p>YUP! we can see it on the <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">first line</a>:</p><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(x) is different from <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(y), return false.</blockquote><p>Ouch, so what is the difference then?</p><p>The right answer to this question is that the “double equal” allows type coercion while the “triple equal” won’t allow it.</p><p>The “Double equal” a.k.a “Abstract Equality” or “Loose equality” will use every trick in the ECMAScript specifications book to coerce a type conversion in order to perform an equality comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*04qYlc58heWAQGQZ" /></figure><p>The “Triple equal” a.k.a “Strict equality” will immediately return false if the two sides are not of the same type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*1dVbliLaELRB-6nH" /></figure><h3>*Bonus tip.</h3><p>What will happen if we will run this block of code:</p><pre>var x = 2;</pre><pre>if(x == true){<br>	console.log(&#39;x is truthy!&#39;);<br>}</pre><pre><em>//</em></pre><p>Hmm, nothing is printed to the console.</p><p>But we know that 2 is not a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">“falsy” value</a>, so it should be loosely equal to true, Should it?</p><p>OK, maybe we are way off and 2 is a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">“Falsy” value</a>:</p><pre>var x = 2;</pre><pre>if(x == false){<br>  console.log(&#39;x is falsy!&#39;);<br>}</pre><pre><em>//</em></pre><p>Nothing again! Huh?!</p><p>How is it possible that a value with a type of Number is not truty or falsy?</p><p>Have you noticed these 2 crazy rules in the “Abstract Equality” spec:</p><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(x) is Boolean, return the result of the comparison ! <a href="https://tc39.github.io/ecma262/#sec-tonumber">ToNumber</a>(x) == y.</blockquote><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(y) is Boolean, return the result of the comparison x == ! <a href="https://tc39.github.io/ecma262/#sec-tonumber">ToNumber</a>(y).</blockquote><p>You see, the specs says that if one of the sides is of type Boolean, the engine should perform the <a href="https://tc39.github.io/ecma262/#sec-tonumber">Abstract ToNumber</a> on it, but it doesn’t say that the engine should do anything to the other side’s type.</p><p>So,</p><ul><li>false becomes 0</li><li>true becomes 1</li><li>x is still 2</li></ul><p>Hence none of our conditions is fulfilled =&gt; 2 != 0 &amp;&amp; 2 != 1.</p><p>But what if we just want to check that (x) holds a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">“Truthy” value</a>? we could just do this:</p><pre>var x = 2;</pre><pre>if(x){<br>  console.log(&#39;x is truthy!&#39;);<br>}</pre><pre><em>// x is truthy!</em></pre><p>Success!</p><h3>Take Away</h3><p>Never ever perform a “loosely” comparison (double equal) when one side is an explicit Boolean type.</p><h3>Recap</h3><ul><li>Both the “double equal” and “triple equal” perform a type check, while the former allows a type coercion and the latter doesn’t.</li><li>Never use a “double equal” when you want to explicit compare against a Boolean.</li></ul><p>You can read more of my articles at my blog <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45992607c27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux is dead! long live react’s context API(?)]]></title>
            <link>https://medium.com/@sagiv.bengiat/redux-is-dead-long-live-reacts-context-api-d0180f4278da?source=rss-5d3a1aa409f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0180f4278da</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Sagiv Ben Giat]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 22:42:21 GMT</pubDate>
            <atom:updated>2019-10-26T10:49:01.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*XzUAfYBw9ZUvmq8XdhOUEg.png" /><figcaption>Can not be compared</figcaption></figure><h4>Can we really compare react’s context with redux?</h4><p>Well, do not let the title mislead you, it is only meant to lure you in :) <br>Redux is not dead. on the contrary it is very alive and is far from being irrelevant.</p><p>Originally posted on <em>my personal blog </em><a href="https://www.debuggr.io/redux-vs-react-context/">debuggr.io</a></p><h3>So what are you doing here?</h3><p>This post is meant to be a “counter attack” against all of the blog-posts / articles / tutorials / tweets / stories that sprang up like mushrooms after the rain when react v16.3 released and the announce about the <a href="https://reactjs.org/blog/2018/03/29/react-v-16-3.html">New Context API</a>.<br>And shockingly this is not a passing trend, people still write and post about this match-up.</p><p>Posts that shared a similar title like this post or something like:<br>“Redux Vs React’s new context API”</p><p>**Spoiler alert!!!**<br>Most of them will tell you it depends on how big is your app.</p><p>I have nothing against any of the authors of these posts, but I do think this should stop. Really, THIS MUST BE STOPPED!</p><p>I think this is one of the most misleading and confusing topics for developers that are either new to react or new to Redux. <br>When people start to learn react they get flooded with topics like npm, babel, ES6, webpack, node.js, express, Redux and the list goes on.</p><p>Not only are these topics not mandatory for learning react but also may lead to confusion. Especially if it leads them to think that Redux is just a way to pass data down to react’s child components and now there’s a better way, called the new react context API.</p><p>This bothers me so much that i had to put down my smartphone and write my first medium article :)</p><p>It is impossible to compare the two, you know what? let’s try.</p><h3>Trial #1 — Redux Vs The new context API</h3><ul><li><strong>Redux </strong>is a state-manager, it helps you manage a big JavaScript object that holds the state of your application.<br>It’s doing it with style though, in a beautiful functional way with pure functions (reducers), plain and serializable objects as actions, great middle-ware support and an amazing pub/sub architecture.<br>By the way, Redux has nothing to do with react. OK, one of the authors of Redux is working at facebook and surprisingly at the react team. but really, Redux has no opinions about which framework or library you should use.<br>You can use it with AngularJS or Angular10, you can use it with jQuery or vanilla JS, you can even use it with react! Its “just” a javascript state-manager library.<br>Actually let’s quote the <a href="https://redux.js.org/">docs</a>:<br>“<em>Redux is a predictable state container for JavaScript apps.”</em></li><li><strong>The new context API</strong> is not even a new feature in react, it was there the whole time and it just got a new face. Well a new <strong>A</strong>pplication-<strong>P</strong>rogram-<strong>I</strong>nterface. Think of it for a moment, if it’s not new why people compare it now? (OK maybe it was a taboo :) )<br>Don’t get me wrong, it’s a great improvement for the API (using the <a href="https://reactjs.org/docs/render-props.html">render props</a>) and a very important feature, but it’s not a new feature.<br>It allows you to expose data as a <strong>Provider </strong>(remember this word, we will bump into it again later on) and allows you as a <strong>Consumer </strong>to get a hold of this data.<br>Now get this, no matter how deeply nested the <strong>Consumer </strong>is as a child component it has access to the Provider’s data as if it is <strong>connected </strong>to it. This means you can pass data from a parent to a great-grandchild without the use of props.<br>It enables you to dodge the bullet of <a href="https://blog.kentcdodds.com/prop-drilling-bb62e02cb691">prop drilling</a>, and the best thing about the new context API is that you wont pay the price of magical data that popped out from nowhere (well, mostly).<br>So basically, react’s context feature is really just another way to pass data down to children.</li></ul><p><em>Note: if you’re tired of prop-drilling don’t forget you don’t have to encapsulate child components inside their parents, you can go for the </em><a href="https://reactjs.org/docs/composition-vs-inheritance.html#containment"><em>Containment</em></a><em> pattern and just render the {children}.</em></p><p>Well we are trying to compare a “State manager for JavaScript applications” with yet another way of react to pass data from a parent component down to it’s children.</p><p>We are trying to compare a Car with a Wheel, Impossible to compare the two.</p><p><strong>Provider</strong>, <strong>Consumer</strong>, passing down data no matter how deeply nested, <strong>connect </strong>them together…. Did we actually want to compare <a href="https://redux.js.org/basics/usage-with-react">react-redux</a> with the new context API and not Redux itself?</p><p>Well lets try…</p><h3>Trial #2 — react-redux Vs The new context API</h3><ul><li>react-redux is an abstraction, a way to bind your Redux store to react.<br>Let’s remember what we need to do in order to bind Redux to react without react-redux.<br>in order to bind Redux to react you need to do couple of things:<br>1. <strong>The first </strong>is not really directly related to react, I’m talking about the subscription to the store with the <a href="https://redux.js.org/api-reference/store#subscribe-listener">store.subscribe()</a> method, this is done inside a <a href="https://redux.js.org/basics/usage-with-react#implementing-container-components">Container component</a>.<br>2. <strong>The second</strong> is to pass the store object down the tree as a prop up until you get to the <strong>Container</strong> component that holds the subscription logic (it needs the actual store object to run methods like subscribe, dispatch etc…)<br>WoooHaaa, prop drilling!</li></ul><p>OK, so basically react-redux is doing all of this for us (and probably doing a better job than we would do <a href="https://redux.js.org/basics/usage-with-react#presentational-and-container-components">performance wise</a>).</p><ul><li><strong>The connect HOC<br></strong>A High Order Component that creates the <strong>Container Component</strong> for us with all the subscription logic + great functions to pass portions of the store and action-creators to its children as props (mapStateToProps &amp; mapDispatchToProps).</li><li><strong>Provider<br></strong>A Component that will hold and pass down our store.</li></ul><p>WAIT! how exactly the <strong>Provider </strong>and the <strong>connect HOC </strong>are connected? how is the data being passed from the <strong>Provider </strong>to the <strong>Container?</strong></p><p>This is where react’s context API plays a big and important role,<br>The <strong>Provider </strong>is exposing the store as a context.<br>The <strong>Container</strong> created by <strong>connect</strong> is grabbing this context.<br>Yes, via the context API.</p><p><em>Note: as for the date this post was written, react-redux is using the </em><a href="https://reactjs.org/docs/legacy-context.html"><strong><em>legacy context API</em></strong></a><em>. </em><br><em>spooky…</em></p><p>So lets say that react’s context feature is like 10% - 20% of the logic react-redux is doing for us.</p><p>We are trying to compare a 4-Wheel-Drive with a Wheel, Impossible to compare the two.</p><p>So bottom line, don’t try to compare the new context API with Redux or react-redux. it’s just wrong, and misleading others.<br>If new comers are wrongly refer to Redux as react-redux or vise versa, don’t do the same in your articles, posts, tweets. it will just keep them from learning the real differences.</p><p>You can read more of my articles at my blog <a href="https://debuggr.io/">debuggr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0180f4278da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>