<?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 Arfat Salman on Medium]]></title>
        <description><![CDATA[Stories by Arfat Salman on Medium]]></description>
        <link>https://medium.com/@arfatsalman?source=rss-74153188d515------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XlXXqHloUtRiunAJV5_ryw.jpeg</url>
            <title>Stories by Arfat Salman on Medium</title>
            <link>https://medium.com/@arfatsalman?source=rss-74153188d515------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 01:43:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arfatsalman/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[Deeply Understanding JavaScript Async and Await with Examples]]></title>
            <link>https://medium.com/bitsrc/understanding-javascript-async-and-await-with-examples-a010b03926ea?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/a010b03926ea</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 01 May 2019 13:48:47 GMT</pubDate>
            <atom:updated>2019-05-31T16:31:13.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kAwfTZXxNynBOB5O6VQtg.jpeg" /></figure><p>In the beginning, there were callbacks. <strong>A callback is nothing special but a function that is executed at some later time.</strong> Due to JavScript’s asynchronous nature, a callback is required in many places, where the results are not available immediately.</p><p>Here’s an example of reading a file in Node.js (asynchronously) —</p><pre>fs.readFile(__filename, &#39;utf-8&#39;, <strong>(err, data) =&gt; {<br>  if (err) {<br>    throw err;<br>  }<br>  console.log(data);<br>}</strong>);</pre><p>Problems arise when we want to do multiple async operations. Imagine this hypothetical scenario (where all operations are async) —</p><ul><li>We query our database for the user Arfat. We read the profile_img_url and fetch the image from someServer.com.</li><li>After fetching the image, we transform it into a different format, say PNG to JPEG.</li><li>If the transformation is successful, we send the user an email.</li><li>We log this task in our file transformations.log with the timestamp.</li></ul><p>The code for something like this would like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*uYstZyc0A4ZSO2Xxh-ASIg.png" /><figcaption>Example of Callback hell.</figcaption></figure><p><strong>Note the nesting of callbacks and the staircase of </strong>})<strong> at the end.</strong> This is affectionately called as <a href="http://callbackhell.com/"><strong>Callback Hell</strong></a><strong> </strong>or <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)"><strong>Pyramid of Doom</strong></a> due to its namesake resemblance. Some disadvantages of this are —</p><ul><li>The code becomes harder to read as one has to move from left to right to understand.</li><li>Error handling is complicated and often leads to bad code.</li></ul><p>To overcome this problem, JavaScript gods created <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>Promises</strong></a>. <strong>Now, instead of nesting callbacks inward, we can chain them.</strong> Here’s an example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*RMxmAiwD-QFKspkHx_nKmA.png" /><figcaption>Using Promises</figcaption></figure><p>The flow has become a familiar <em>top-to-bottom</em> rather than <em>left-to-right</em> as in callbacks, which is a plus. However, Promises still suffer from some problems —</p><ul><li>We still have to give a callback to every .then.</li><li>Instead of using a normal try/catch, we have to use .catch for error handling.</li><li><strong>Looping over multiple promises in a sequence is challenging and non-intuitive.</strong></li></ul><p>As a demonstration of the last point, <strong>try this challenge</strong>!</p><h4>The Challenge</h4><p><em>Let’s assume that we have a </em><em>for loop that prints 0 to 10 at random intervals (0 to n seconds). We need to modify it using promises to print sequentially 0 to 10. For example, if 0 takes 6 seconds to print and 1 takes two seconds to print, then 1 should wait for 0 to print and so on.</em></p><p>Needless to say, don’t use async/await or .sort function. We’ll have a solution towards the end.</p><p>Tip: <strong>Build more modular JavaScript software</strong>. Use tools like <a href="https://bit.dev/"><strong>Bit</strong></a> (<a href="https://github.com/teambit/bit">GitHub</a>) to develop, share and sync modular components between your projects. Modular software is faster to build, easier to maintain and simpler to reuse. Try it:</p><p><a href="https://bitsrc.io/">Share reusable code components as a team · Bit</a></p><h3>Async Functions</h3><p>Introduced in <strong>ES2017</strong>(ES8), async functions make working with promises much easier.</p><ul><li><strong>It is important to note the async functions work on top of promises.</strong></li><li>They are not a fundamentally different concept.</li><li>They can be thought of as an alternate way of writing promise-based code.</li><li>We can<strong> avoid chaining promise </strong>altogether using async/await.</li><li>They allow asynchronous execution while <strong>maintaining a regular, <em>synchronous</em> feel</strong>.</li></ul><p>Hence, an <strong>understanding of promises is required</strong> before you can fully understand async/await concepts.</p><h4>Syntax</h4><p>They consist of two main keywords- async and await. <strong>async is used to make a function asynchronous.</strong> It <strong>unlocks</strong> the use of await inside these functions. Using await in any other case is a syntax error.</p><pre><strong>// With function declaration</strong></pre><pre><strong>async</strong> function myFn() {<br>  // <strong>await</strong> ...<br>}</pre><pre><strong>// With arrow function</strong></pre><pre>const myFn = <strong>async</strong> () =&gt; {<br>  // <strong>await</strong> ...<br>}</pre><pre>function myFn() {<br>  // <strong>await</strong> fn(); (<strong>Syntax Error </strong>since no async) <br>}</pre><p>Notice the use of async keyword <strong>at the beginning</strong> of the function declaration. In the case of arrow function, async is put after the = sign and before the parentheses.</p><p>Async functions can also be put on an object as methods, or in class declarations as follows.</p><pre><strong>// As an object&#39;s method</strong></pre><pre>const obj = {<br>  <strong>async</strong> getName() {<br>    return fetch(&#39;https://<a href="http://www.google.com&/#39;">www.example.com&#39;</a>);<br>  }<br>}</pre><pre><strong>// In a class</strong></pre><pre><strong>class</strong> Obj {<br>  <strong>async</strong> getResource() {<br>    return fetch(&#39;<a href="https://www.example.com&/#39;">https://www.example.com&#39;</a>);<br>  }<br>}</pre><p><strong>Note: Class constructors and </strong><a href="https://blog.bitsrc.io/diving-deeper-in-javascripts-objects-318b1e13dc12"><strong>getters/setters</strong></a><strong> <em>cannot</em> be async.</strong></p><h3>Semantics and Evaluation Rules</h3><p>Async functions are normal JavaScript functions with the following differences —</p><h4>An async function always returns a promise.</h4><pre><strong>async</strong> function fn() {<br>  return &#39;hello&#39;;<br>}</pre><pre><strong>fn()</strong>.then(console.log)<br>// hello</pre><p>The function fn returns &#39;hello&#39;. Because we have used async, the return value &#39;hello&#39; is <strong>wrapped in a promise</strong> (via Promise constructor).</p><p>Here’s an <strong>alternate representation</strong> without using async —</p><pre>function fn() {<br>  return Promise.resolve(&#39;hello&#39;);<br>}</pre><pre>fn().then(console.log);<br>// hello</pre><p>In this, we are <strong>manually returning a promise</strong> instead of using async.</p><p>A slightly more accurate way to say the same thing — <strong>The body of an async function is always wrapped in a new </strong><strong>Promise.</strong></p><p>If the return value is primitive, async functions return a<strong> promise-wrapped version of the value.</strong> However, when the return value is a promise object, <strong>its resolution is returned in a new promise. </strong><em>[See </em><a href="https://medium.com/@mikolaj.stankowiak/i-do-not-think-this-is-accurate-a05e9bc55af9"><em>this</em></a><em> comment]</em></p><pre><strong>// in case of primitive values</strong></pre><pre>const p = Promise.resolve(&#39;hello&#39;)<br><strong>p instanceof Promise</strong>; <br><strong>// true</strong></pre><pre><strong>// p is returned as is it</strong></pre><pre>Promise.resolve(p) === p; <br><strong>// true</strong></pre><p><strong>What happens when you <em>throw an error</em> inside an async function?</strong></p><p>For example —</p><pre><strong>async</strong> function foo() {<br>  <strong>throw Error(&#39;bar&#39;);</strong><br>}</pre><pre>foo().<strong>catch</strong>(console.log);</pre><p>foo() will return a <strong><em>rejected</em></strong> promise if the error is <strong>uncaught</strong>. Instead of Promise.resolve, Promise.reject wraps the error and is returned. See E<em>rror Handling</em> section later.</p><p>The net effect is that you return whatever you want, <strong>you will always get a promise out of an async function</strong>.</p><h4>Async functions pause at each await &lt;expression&gt;.</h4><p>An await acts on an <em>expression. </em>When the expression is a promise,<strong> the evaluation of the async function halts until the promise is resolved. </strong>When the expression is a non-promise value, it is converted to a promise using Promise.resolve and then resolved.</p><pre><strong>// utility function to cause delay<br>// and get random value</strong></pre><pre>const <strong>delayAndGetRandom</strong> = (ms) =&gt; {<br>  return new Promise(<strong>resolve</strong> =&gt; setTimeout(<br>    () =&gt; {<br>      const val = Math.trunc(Math.random() * 100);<br>      <strong>resolve(val);</strong><br>    }, ms<br>  ));<br>};</pre><pre><strong>async</strong> function fn() {<br>  const a = <strong>await</strong> 9;<br>  const b = <strong>await</strong> delayAndGetRandom(1000);<br>  const c = <strong>await</strong> 5;<br>  await delayAndGetRandom(1000);<br>  <br>  <strong>return a + b * c;</strong><br>}</pre><pre>// Execute fn<br>fn().then(console.log);</pre><p>Let’s examine the function fn line by line —</p><ul><li>When fn is executed, the first line to be evaluated is const a = await 9;. It is <strong>internally transformed</strong> into const a = await Promise.resolve(9);.</li><li>Since we are using await, fn <strong>pauses until the variable</strong> a gets a value. In this case, the <strong>promise resolves it to</strong> 9.</li><li>delayAndGetRandom(1000) causes fn to pause until the function delayAndGetRandom is resolved which is after 1 second. So, fn effectively pauses for 1 second.</li><li>Also, delayAndGetRandom resolves with a random value. Whatever is passed in the resolve function, that is assigned to the variable b.</li><li>c gets the value of 5 similarly and we delay for 1 second again using await delayAndGetRandom(1000). We don’t use the resolved value in this case.</li><li>Finally, we compute the result a + b * c which is wrapped in a Promise using Promise.resolve. This wrapped promise is returned.</li></ul><p><strong>Note: </strong>If this pause and resume are reminding you of ES6 <a href="https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5"><strong>generators</strong></a>, it’s because there are <a href="https://github.com/tj/co"><strong>good reasons</strong></a> for it.</p><h4>The Solution</h4><p>Let’s use async/await for the hypothetical problem listed at the beginning of the article —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*AUT5DU_0gzjWMTT00Yc0zw.png" /><figcaption>Using async/await</figcaption></figure><p>We make an async function finishMyTask and use await to wait for the result of operations such as queryDatabase, sendEmail, logTaskInFile etc.</p><p>If we contrast this solution with the solutions using promises above, we find that <strong>it is roughly the same line of code</strong>. However, async/await has made it simpler in terms of syntactical complexity.<strong> There aren’t multiple callbacks and </strong><strong>.then /</strong><strong>.catch to remember.</strong></p><p>Now, let’s solve the <strong>challenge of numbers</strong> listed above. Here are two implementations —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/838fa903e2b12a383ec4750933bc50b6/href">https://medium.com/media/838fa903e2b12a383ec4750933bc50b6/href</a></iframe><p>If you want, you can run them yourself at <a href="https://repl.it/@ArfatSalman1/blogsequentialnumbers"><em>repl.it</em><strong> console</strong></a>.</p><p>If you were allowed async function, the task would have been much simpler.</p><pre><strong>async</strong> function printNumbersUsingAsync() {<br>  for (let i = 0; i &lt; 10; i++) {<br>    <strong>await</strong> wait(i, Math.random() * 1000);<br>    console.log(i);<br>  }<br>}</pre><p>This implementation is also provided in the <em>repl.it</em> <a href="https://repl.it/@ArfatSalman1/blogsequentialnumbers"><strong>console</strong></a>.</p><h3>Error Handling</h3><p>As we saw in the <strong>Semantics</strong> section, an <strong>uncaught</strong> Error() is wrapped in a rejected promise. However, we can use try-catch in async functions to <strong>handle errors</strong> <strong>synchronously</strong>. Let’s begin with this utility function —</p><pre><strong>async</strong> function canRejectOrReturn() {<br><strong>  // wait one second</strong><br>  await new Promise(res =&gt; setTimeout(res, 1000));</pre><pre><strong>// Reject with ~50% probability</strong><br>  if (Math.random() &gt; 0.5) {<br>    throw new Error(&#39;Sorry, number too big.&#39;)<br>  }</pre><pre>return &#39;perfect number&#39;;<br>}</pre><p>canRejectOrReturn() is an async function and it will either<strong> resolve with</strong> &#39;perfect number&#39; or <strong>reject with</strong> Error(&#39;Sorry, number too big&#39;).</p><p>Let’s look at the code example —</p><pre><strong>async</strong> function foo() {<br>  try {<br>    <strong>await</strong> canRejectOrReturn();<br>  } catch (e) {<br>    <strong>return</strong> &#39;error caught&#39;;<br>  }<br>}</pre><p>Since we are awaiting canRejectOrReturn, <strong>its own rejection will be turned into a throw</strong> and the catch block will execute. That is, foo will <strong>either resolve with</strong> undefined (because we are not returning anything in try) or <strong>it will resolve with</strong> &#39;error caught&#39;. It will never reject since we used a try-catch block to handle the error in the foo function itself.</p><p>Here’s another example —</p><pre><strong>async</strong> function foo() {<br>  try {<br>    <strong>return</strong> canRejectOrReturn();<br>  } catch (e) {<br>    return &#39;error caught&#39;;<br>  }<br>}</pre><p>Note that <strong>we are returning </strong>(and not awaiting) canRejectOrReturn from foo this time. foo will either <strong>resolve with </strong><strong>&#39;perfect number&#39;</strong> or <strong>reject with </strong>Error(&#39;Sorry, number too big&#39;). <strong>The </strong><strong>catch block will never be executed.</strong></p><p>It is because we <strong>return the promise returned</strong> by canRejectOrReturn. Hence, the resolution of foo becomes the resolution of canRejectOrReturn. You can break return canRejectOrReturn() into two lines to see clearly (<strong>Note the missing await </strong>in the first line)—</p><pre>try {<br>    const promise = canRejectOrReturn();<br>    return promise;<br>}</pre><p>Let’s see the usage of await and return together —</p><pre><strong>async</strong> function foo() {<br>  try {<br>    <strong>return</strong> <strong>await</strong> canRejectOrReturn();<br>  } catch (e) {<br>    return &#39;error caught&#39;;<br>  }<br>}</pre><p>In this case, foo <strong>resolves with either</strong> &#39;perfect number&#39; or <strong>resolve with</strong> &#39;error caught&#39;. <strong>There is no rejection.</strong> It is like the first example above with just await. Except, we <strong>resolve with the value that</strong> canRejectOrReturn produces rather than undefined.</p><p>You can break return await canRejectOrReturn(); to see the effect —</p><pre>try {<br>    const value  = <strong>await</strong> canRejectOrReturn();<br>    return value;<br>}<br>// ...</pre><h3>Common Mistakes and Gotchas</h3><p>Because of an intricate play of Promise-based and async/await concepts, there are some subtle errors that can creep into the code. Let’s look at them —</p><h4>Not using await</h4><p>In some cases,<strong> we forget to use</strong> the await keyword before a promise or return it. Here’s an example —</p><pre>async function foo() {<br>  try {<br>    <strong>canRejectOrReturn();</strong><br>  } catch (e) {<br>    return &#39;caught&#39;;<br>  }<br>}</pre><p>Note that we are not using await or return. foo <strong>will always resolve with </strong><strong>undefined without</strong> <strong>waiting for 1 second</strong>. However, the promise <strong>does start </strong>its execution. If there are side-effects, <strong>they will happen</strong>. If it throws an error or rejects, then UnhandledPromiseRejectionWarning will be issued.</p><h4>async functions in callbacks</h4><p>We often use async functions in .map or .filter as callbacks. Let’s take an example — Suppose we have a function fetchPublicReposCount(username) that fetched the number of public GitHub repositories a user has. We have three users whose counts we want to fetch. Let’s see the code —</p><pre>const url = &#39;<a href="https://api.github.com/users&#39;">https://api.github.com/users&#39;</a>;</pre><pre><strong>// Utility fn to fetch repo counts</strong><br>const fetchPublicReposCount = <strong>async</strong> (username) =&gt; {<br>  const response = <strong>await</strong> fetch(`${url}/${username}`);<br>  const json = <strong>await</strong> response.json();<br>  return json[&#39;public_repos&#39;];<br>}</pre><p>We want to fetch repo counts of [&#39;ArfatSalman&#39;, &#39;octocat&#39;, &#39;norvig&#39;]. We may do something like this —</p><pre>const users = [<br>  &#39;ArfatSalman&#39;,<br>  &#39;octocat&#39;,<br>  &#39;norvig&#39;<br>];</pre><pre>const counts = users.map(<strong>async</strong> username =&gt; {<br>  const count = <strong>await</strong> fetchPublicReposCount(username);<br>  return count;<br>});</pre><p>Note the async in the callback to the .map. We might expect that counts variable will contain the numbers of repos. However, as we have seen earlier, <strong>all async functions return promises.</strong> Hence, counts is actually <strong>an array of promises.</strong> .map calls the anonymous callback with every username, and a promise is returned with every invocation which .map keeps in the resulting array.</p><h4>Too sequential using await</h4><p>We may also think of a solution such as —</p><pre><strong>async</strong> function fetchAllCounts(users) {<br>  const counts = [];<br>  <strong>for (let i = 0; i &lt; users.length; i++)</strong> {<br>    const username = users[i];<br>    const count = <strong>await</strong> fetchPublicReposCount(username);<br>    counts.push(count);<br>  }<br>  return counts;<br>}</pre><p>We are manually fetching each count, and appending them in the counts array. The<strong> problem with this code</strong> is that until the first username’s count is fetched, <strong>the next will not start.</strong> At a time, <strong>only one repo count</strong> is fetched.</p><p>If a single fetch takes 300 ms, then fetchAllCounts will take ~900ms for 3 users. As we can see that time usage will linearly grow with user counts. Since the <strong>fetching of repo counts is not co-dependent</strong>, we can <strong>parallelize the operation.</strong></p><p>We can fetch users concurrently instead of doing them sequentially. We are going to utilize .map and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all"><strong>Promise.all</strong></a>.</p><pre><strong>async</strong> function fetchAllCounts(users) {<br>  const promises = users.map(<strong>async</strong> username =&gt; {<br>    const count = <strong>await</strong> fetchPublicReposCount(username);<br>    return count;<br>  });<br>  <strong>return Promise.all(promises);</strong><br>}</pre><p>Promise.all receives an array of promises as input and returns a promise as output. The returned promise resolves with <strong>an array of all promise resolutions or rejects with the first rejection. </strong>However, it may not be feasible to start all promises at the same time. Maybe you want to complete promises in batches. You can look at <a href="https://github.com/sindresorhus/p-map"><strong>p-map</strong></a><strong> </strong>for limited concurrency.</p><h3>Conclusion</h3><p>Async functions have become really important. With the introduction of <a href="https://github.com/tc39/proposal-async-iteration">Async Iterators</a>, async functions will see more adoption. It is important to have a good understanding of them for modern JavaScript developer. I hope this article sheds some light on that. :)</p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/11-javascript-animation-libraries-for-2018-9d7ac93a2c59">11 JavaScript Animation Libraries For 2019</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-faster-development-in-react-676f134050f2">5 Tools for Faster Development in React</a></li><li><a href="https://blog.bitsrc.io/9-web-component-ui-libraries-you-should-know-in-2019-9d4476c3f103">9 Web Components UI Libraries You Should Know in 2021</a></li><li><a href="https://github.com/teambit/bit">GitHub - teambit/bit: A tool for component-driven application development.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a010b03926ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/understanding-javascript-async-and-await-with-examples-a010b03926ea">Deeply Understanding JavaScript Async and Await with Examples</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Deeper in JavaScripts Objects]]></title>
            <link>https://medium.com/bitsrc/diving-deeper-in-javascripts-objects-318b1e13dc12?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/318b1e13dc12</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 15:52:11 GMT</pubDate>
            <atom:updated>2019-04-01T09:20:54.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZGZsLvPF4dPZtp1xu7CNg.jpeg" /></figure><h4>A Closer Look at JavaScript Object Descriptors</h4><p>JavaScript objects pack more things than their terse and concise syntax would naturally exhibit. <strong>Creating and using objects in JavaScript is so easy, effortless, and so flexible that a lot of developers never realize that there is more to it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*BhxITgILKjRZU9HARJAqdQ.png" /><figcaption><a href="https://knowyourmeme.com/memes/we-need-to-go-deeper">We Need to Go Deeper</a></figcaption></figure><p>We are going to uncover some of the hidden layers and understand the intricacies of JavaScript objects. After reading this article, you should be able to answer the following questions —</p><ul><li><strong>How to make a property undeletable?</strong></li><li><strong>What are accessor properties and what are their features?</strong></li><li><strong>How to make a property immutable or hidden?</strong></li><li><strong>Why some properties do <em>not</em> appear in </strong><strong>for-in loops or </strong><strong>Object.keys and some do?</strong></li><li><strong>How to “protect” objects from modification?</strong></li><li><strong>How to make sense of code such as</strong></li></ul><pre>obj.id = 5;<br>console.log(obj.id)<br><strong>// =&gt; &#39;101&#39; ( 5 in binary )</strong></pre><p>If you want a refresher of the basics of JS objects, I have written <a href="https://blog.bitsrc.io/the-chronicles-of-javascript-objects-2d6b9205cd66">another article</a>.</p><p><a href="https://blog.bitsrc.io/the-chronicles-of-javascript-objects-2d6b9205cd66">The Chronicles of JavaScript Objects</a></p><p>Tip: Use <a href="https://github.com/teambit/bit"><strong>Bit</strong></a><strong> </strong>to organize and reuse your JS components. It will help you build faster, using components like Lego. Example: <a href="https://bit.dev/ramda/ramda">Ramda</a>, <a href="https://bit.dev/semantic-org/semantic-ui-react">Semantic-UI</a>. Try it out.</p><p><a href="https://bit.dev/">Bit. Composable software.</a></p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Yhkh7jbS5Mx9uP96Y88pZg.gif" /></a><figcaption>React spinners with Bit: discover, learn, reuse</figcaption></figure><h3>Types of Properties</h3><h4>Data Properties</h4><p>You must have made countless objects like these —</p><pre>const obj = {<br>  name: &#39;Arfat&#39;,<br>  id: 5<br>}</pre><pre>obj.name <br>// =&gt; &#39;Arfat&#39;</pre><p>In object obj, name and id properties are called <strong>Data Properties</strong>. These are the normal kind of properties that constitute most of the JavaScript code. <em>What is, then, the other type of property?</em></p><h4>Accessor Properties</h4><p>They can also be understood as <em>getters</em> and <em>setters</em> of other languages such as C# or Python. <strong>An accessor property is a combination of <em>two</em> functions: the </strong><strong>get and the </strong><strong>set function.</strong></p><p>Instead of using the traditional <strong><em>key: value </em></strong>syntax, we use the following syntax —</p><pre><strong>const</strong> accessorObj = {<br>  <strong>get</strong> name() {<br>    return &#39;Arfat&#39;;<br>  }<br>};</pre><pre>accessorObj.name;<br>// =&gt; &#39;Arfat&#39;</pre><pre>const dataObj = {<br>  name: &#39;Arfat&#39;,<br>};</pre><pre>dataObj.name;<br>// =&gt; &#39;Arfat&#39;</pre><p>Look at accessorObj and compare it with dataObj. Right now, they exhibit the same behavior. We use the get keyword and follow it with a function declaration. Reading accessor properties do not need to use parentheses to invoke the function. That is, accessorObj.name<strong>()</strong>; is wrong.</p><p>When we access(read) accessorObj.name, the name function is executed and its return value becomes the final value of the name key.</p><p>The <strong>get </strong>function is called a getter since it is involved in <em>getting</em> the value of a key. If you update accessorObj.name = &#39;New Person’;, the update won’t happen. This is because we don’t have a corresponding <em>setter </em>function for the name key. <em>Setter</em> functions help in setting values of <em>getter </em>properties.</p><pre>const accessorObj = {<br>  _name: &#39;Arfat&#39;,<br>  <strong>get name</strong>() {<br>    return this._name;<br>  },<br>  <strong>set name</strong>(<strong>value</strong>) {<br>    this._name = value;<br>  }<br>};</pre><p><strong>The <em>setter</em> function receives the assigned value as a parameter.</strong> Now, you can store the value in property or a global variable. In this case, we make a conventional “private” property _name and store the <strong>name </strong>value in it.</p><p>In the <em>getter</em> function, we can modify or override the property before returning its value. The following example should demonstrate this.<strong> It also answers one of the above questions.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90f3927ec9227c1fde03794423cbf86d/href">https://medium.com/media/90f3927ec9227c1fde03794423cbf86d/href</a></iframe><p><em>Why would anybody use accessor properties if normal data properties exist? </em>There are often cases where you need to log the property access or maintain a history of all the values that the property has had. <strong>Accessor properties give us the full power of a function with the ease of use of object properties.</strong> You can read more about accessor usage <a href="https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors">here</a>.</p><p><em>So how does JavaScript know which is an accessor property and which is a data property? </em>Let’s find out.</p><h3>Object Property Descriptors</h3><p>At first glance, it might look like there is a one-to-one mapping between keys and values of an object. However, that’s not entirely true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ValIFHKpLmEhbQpAkudz4w.gif" /><figcaption>These aren’t JS descriptors. 😉 Via <a href="http://gph.is/2l7gZDq">Giphy</a>.</figcaption></figure><h4>Property Attributes</h4><p><strong>Every key</strong> of an object contains a set of <strong>property</strong> <strong>attributes</strong> that define the characteristics of the value associated with the key. They can also be thought of as <em>meta-data</em> describing the key-value pair. In short, attributes are used to define and explain the state of object properties.</p><p><strong>The set of property attributes is called the property descriptor.</strong></p><p>In total, there are six property attributes. They are —</p><ul><li><strong>[[Value]]</strong></li><li><strong>[[Get]]</strong></li><li><strong>[[Set]]</strong></li><li><strong>[[Writable]]</strong></li><li><strong>[[Enumerable]]</strong></li><li><strong>[[Configurable]]</strong></li></ul><p><em>Why have we wrapped the attribute names in [[]]? </em>Double square brackets mark <strong>internal properties</strong> used by the ECMA specifications. These are properties that JS programmer cannot touch directly from within the code. To manipulate internal properties, we’d need to use methods provided to us by the language.</p><p>Let’s see an example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKJx57JU9sKdff-Os7upyA.png" /><figcaption>An image from the excellent <a href="https://mathiasbynens.be/notes/shapes-ics">tutorial</a> of Mathias Bynens</figcaption></figure><p>In the above image, the object has 2 keys: x and y. You can see the corresponding list of attributes associated with each property.</p><p><em>How can you get the same information in JavaScript? </em>We can use the function Object.getOwnPropertyDescriptor to get that information. It takes an object and a property name and returns an object containing the required attributes. Here’s a code sample —</p><pre>const object = {<br>  x: 5,<br>  y: 6<br>};</pre><pre><strong>Object.getOwnPropertyDescriptor</strong>(object, &#39;x&#39;);</pre><pre>/* <br>{ <br>  value: 5, <br>  writable: true, <br>  enumerable: true, <br>  configurable: true <br>}<br>*/</pre><p>Let’s see the attributes in more detail to know how they are helpful and then we’ll revisit the image.</p><h4>[[Value]]</h4><p>It stores the <strong>value</strong> retrieved by a get access of the property. Which means that when we do object.x in the above example, we actually retrieve its <strong>[[Value]] </strong>attribute. Any <em>dot-access</em> or <em>square-bracket</em> access of a <strong>Data property</strong> will work in this way.</p><h4>[[Get]]</h4><p><strong>It stores the reference to the function that we declare while making a <em>getter</em> property.</strong> It is called with an empty arguments list to retrieve the property value each time a get access of the property is performed.</p><h4><strong>[[Set]]</strong></h4><p>It stores the reference to the function that we declare while making a <em>setter</em> property. <strong>It is called with an arguments list containing the assigned value as </strong>its sole argument each time a set access of the property is performed.</p><pre>const obj = {<br>  set x(<strong>val</strong>) {<br>    console.log(val) <br>    <strong>// =&gt; 23</strong><br>  }<br>}</pre><pre>obj.x = <strong>23</strong>;</pre><p>In the above example, the right-hand-side of the assignment is passed as the val argument to a <em>setter</em> function. You can see this <a href="https://gist.github.com/ArfatSalman/07f8663adfd78ddc4af8ebea152cdbae">code</a> for a demonstration.</p><h4>[[Writable]]</h4><p><strong>This is a boolean value. </strong>It tells whether we can overwrite the value or not. <strong>If false, </strong>attempts to change the property’s value will not succeed.</p><h4><strong>[[Enumerable]]</strong></h4><p>This is also a boolean value. This attribute dictates whether the property is going to appear in for-in loops or not. <strong>If true,</strong> the for-in loop will be able to iterate on this property.</p><h4>[[Configurable]]</h4><p>This is a boolean too.</p><p><strong>When it is false —</strong></p><ul><li>Attempts to <strong>delete</strong> the property will fail.</li><li>Also, converting a <strong>Data Property</strong> to be an <strong>Accessor Property</strong> or vice-versa will fail too. That is, inter-conversion between two property types will not be possible.</li><li>It will also prevent further <strong>changing the attributes values</strong>. That is, current values of enumerable, configurable, get or set will become fixed.</li></ul><p>The effect of this property is also dependent on the property type. Apart from the above effects, it also does the following.</p><ul><li>When the property is a <strong>Data Property, </strong>you can only set writable from true to false.</li><li>Before writable becomes false, you can also change its [[Value]] attribute. However, once writable is false, and configurable is false too, <strong>the property becomes unwritable, undeletable and unchangeable.</strong></li></ul><p>All six properties do not exist for each property type.</p><ul><li>For <strong>Data Properties</strong>, only value, writable, enumerable and configurable exists.</li><li>For <strong>Accessor Properties</strong>, instead of value and writable, we have get and set.</li></ul><h3>Working with Descriptors</h3><p>Having learned about these descriptors, <em>how can we set or update them on our own objects?</em> There are a couple of functions in JavaScript that can be used to work with these descriptors. Let’s see them —</p><h4>Object.getOwnPropertyDescriptor</h4><p>We have seen this function above. It takes an existing object, and a property name. It returns either undefined or an object containing the descriptors.</p><h4>Object.defineProperty</h4><p>It’s a static method on Object that can define or modify a new property on a given object. It takes three arguments — the object, the property name, and descriptors. It returns the modified object. Let’s see an example —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711c29764bd1a812334e37d11a585855/href">https://medium.com/media/711c29764bd1a812334e37d11a585855/href</a></iframe><p>It seems like a long example but it’s simple. Let’s go step by step —</p><ul><li>On #3, we use defineProperty passing it obj, property name id and a descriptor containing only the <strong>[[Value]] </strong>field as value having an actual value of 42.</li><li>Remember that if you fail to specify any more property attributes such as enumerable or configurable, <strong>the default value is set to </strong><strong>false.</strong> In this case, id has writable, enumerable, and configurable all set to false.</li><li>On #7, we print obj. Since id property is not enumerable, it is not printed. However, it does exist as #10 shows.</li><li>On #13, we specify the full descriptor set. We set writable to false.</li><li>On #20 and #25, we print name property. However, we modify the value in between on line #23. Because of non-writability, it has no effect. Hence, we see the original value twice.</li><li>On #37, we try to delete id whose configurable is set to false. Line #39 proves that it is not deleted.</li><li>On #42, we use the batch version of defineProperty called Object.defineProperties.</li></ul><p>Object.defineProperty sets one property at a time. There is a different variant of this function that can set multiple properties with their descriptors at the same time. It is aptly named <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties">Object.defineProperties.</a></p><h3>Protecting Objects</h3><p>There are often cases where we don’t want anyone to tamper with our objects. Given the flexibility of JavaScript, it’s really easy to mistakenly re-assign properties of objects that we are not meant to touch. There are three major ways of protecting objects in JavaScript. Let’s look at them —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*HSs18xEY-IJ83YugQBju9g.gif" /><figcaption>Get ready! (via <a href="http://gph.is/2BeYGUR">Giphy</a>)</figcaption></figure><h4>Object.preventExtensions</h4><p>The Object.preventExtensions method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It takes an object and <strong>makes it non-extensible</strong>.</p><p><strong>Note that the properties <em>can</em> be deleted though.</strong></p><pre>const obj = {<br>  id: 42<br>};</pre><pre>Object.<strong>preventExtensions</strong>(obj);</pre><pre>obj.name = &#39;Arfat&#39;;</pre><pre>console.log(obj);<br>// =&gt; { id: 42 } </pre><p>You can check whether an object is non-extensible or not by using Object.isExtensible. If it returns true, you can add more properties to the object.</p><h4>Object.seal</h4><p>The seal method seals an object. It means —</p><ul><li>It prevents new properties from being added just like Object.preventExtensions.</li><li><strong>It marks all existing properties as non-configurable.</strong></li><li>Values of present properties can still be changed as long as they are writable.</li><li>In short, it prevents adding and/or removing properties.</li></ul><pre>const obj = {<br>  id: 42<br>};</pre><pre><strong>Object.seal</strong>(obj);</pre><pre><strong>delete obj.id </strong><br>// (does not work)</pre><pre><strong>obj.name = &#39;Arfat&#39;;</strong><br>// (does not work)</pre><pre>console.log(obj);<br>// =&gt; { id: 42 }</pre><pre><strong>Object.isExtensible</strong>(obj);<br>// =&gt; false</pre><pre><strong>Object.isSealed</strong>(obj);<br>//=&gt; true</pre><p>You can use Object.isSealed to test whether an object has been sealed or not.</p><h4>Object.freeze</h4><p>freeze is the maximum protection any object can have in JavaScript. It —</p><ul><li>seals the object using Object.seal</li><li>It also prevents <em>modifying</em> any existing properties at all.</li><li>It also prevents the descriptors from being changed as the object is already sealed.</li></ul><pre>const obj = {<br>  id: 42<br>};</pre><pre><strong>Object.freeze</strong>(obj);</pre><pre>delete obj.id <br>// (does not work)</pre><pre>obj.name = &#39;Arfat&#39;;<br>// (does not work)</pre><pre>console.log(obj);<br>// // =&gt; { id: 42 }</pre><pre>Object.isExtensible(obj);<br>// // =&gt; false</pre><pre>Object.isSealed(obj);<br>// //=&gt; true</pre><pre><strong>Object.isFrozen</strong>(obj);<br>// =&gt; true</pre><p>You can check whether an object is frozen or not using the Object.isFrozen function.</p><p>An important point to note is that these methods deal only with the direct properties of the objects. <strong>They do not modify nested objects.</strong></p><p>Here’s a table summarizing the same.</p><p><em>The operations are in terms of properties. </em>[CREATE] a new property, [READ] an existing property, [UPDATE] an existing property and [DELETE] an existing property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*z6mLOd1zFsXt3sMc3_1o-Q.png" /><figcaption>Credits: <a href="https://github.com/piecioshka/test-freeze-vs-seal-vs-preventExtensions">piecioshka</a></figcaption></figure><h3>Conclusion</h3><p>Given how pervasive objects are on JavaScripts, it is important to understand the true power of objects. I hope the article was able to convey that effectively to you. I also hope that now you are able to answer the questions listed at the beginning of the article. Thanks for reading.</p><ul><li><a href="https://blog.bitsrc.io/11-javascript-utility-libraries-you-should-know-in-2018-3646fb31ade">11 Javascript Utility Libraries you Should Know in 2019</a></li><li><a href="https://blog.bitsrc.io/good-engineering-practices-while-working-solo-ad872e727af4">Good Engineering Practices while Working Solo</a></li><li><a href="https://blog.bitsrc.io/solid-principles-every-developer-should-know-b3bfa96bb688">SOLID Principles every Developer Should Know</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318b1e13dc12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/diving-deeper-in-javascripts-objects-318b1e13dc12">Diving Deeper in JavaScripts Objects</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Chronicles of JavaScript Objects]]></title>
            <link>https://medium.com/bitsrc/the-chronicles-of-javascript-objects-2d6b9205cd66?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6b9205cd66</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 16:22:06 GMT</pubDate>
            <atom:updated>2019-04-01T10:28:37.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H2i1vBcjmvHnUWv8D583A.jpeg" /></figure><p>Objects are the foundation of JavaScript and permeate its every aspect. <strong><em>Almost </em></strong>everything in JavaScript is an object. In fact, only <strong>six</strong> things are <strong>not</strong> objects. They are — <strong><em>null</em></strong>,<strong><em>undefined</em></strong>, <strong><em>strings</em></strong>, <strong><em>numbers</em></strong>, <strong><em>boolean</em></strong>, and <strong><em>symbols</em></strong>. These are called primitive values or primitive types.</p><p>Anything that is not a primitive value is an <strong>Object</strong>. That includes <strong>arrays</strong>, <strong>functions</strong>, constructors, and objects themselves. Yes! Functions and arrays are objects too as we shall see later in the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dTpqwmJw7qU8uKfRL3xv8A.gif" /><figcaption>In JavaScript, <strong>it is </strong>😃<strong> </strong>! (via <a href="https://gph.is/1UO3fU1">Giphy</a>)</figcaption></figure><p><strong>Tip</strong>: Instead of rewriting code across projects, use <a href="https://bit.dev/"><strong>Bit</strong></a> to to share a component collection your team can discover and use to build new apps faster. Try it.</p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqRT9FOXRyCYMWB3WSUEjg.png" /></a></figure><p><a href="https://bit.dev/">Bit. Composable software.</a></p><h3>What are objects?</h3><p>Just like other primitive values, objects are values too and they serve the same purpose: <strong>Representing information or data</strong>. When we create a variable and assign a value to it, we are holding information in it for later retrieval and processing. For example —</p><pre>const <strong>firstName</strong> = &#39;Arfat Salman&#39;;</pre><p>In this case, firstName holds and represents the first name of a person. In a sense, strings are called <em>primitive</em> values because they can represent only one type of information. In this case, a collection of characters or a string.</p><p>What happens when we want to represent a person as a <strong><em>whole</em></strong>? That is, I want to hold on to <em>first name (String),</em> <em>last name (String)</em>, <em>date of birth (Date)</em>, and her <em>friends (Collection of Strings)</em>. If I create four variables for each datum, representing three persons would require <strong>4 * 3 = 12</strong> variable names. <em>That’s not good!</em></p><p>In some languages, this question would segue into a discussion about <strong>user-defined data types</strong> or <strong>custom data types</strong>. Constructs such as classes, <a href="https://en.wikipedia.org/wiki/Composite_data_type">structures</a>, unions types etc. can be used to achieve that. However, JavaScript does not have classes (even though it has a class keyword), or structures. It only has objects for creating custom data types and associating behavior.</p><p>In JavaScript, <strong>an object can be thought of as a distinct entity that can have <em>properties </em>associated with it.</strong> These properties define the object’s characteristics and behavior. In our person example, an object can have 4 properties describing it — first name, last name, DOB, and friends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*D1UgwSiO9I9dj818qu1Ujw.jpeg" /><figcaption>Here’s an example representation of “<strong>person”</strong> object.</figcaption></figure><p>Here’s how ECMA specification defines an object —</p><blockquote>An Object is logically a collection of properties.</blockquote><p>The <strong>properties</strong> are also known as <strong>key-value pairs</strong>. You may come across similar concepts in the form of <a href="https://en.wikipedia.org/wiki/Associative_array">Associative Arrays</a>, <strong>maps</strong>, and <strong>dictionaries </strong>in other languages. JavaScript objects embody those characteristics, but they also have a lot more to them as we shall see.</p><h3>Objects and Properties</h3><p>We are going to examine objects by the kind of operation we can perform on them. The operations are —</p><ul><li><strong>Creation</strong> — Creating a new object.</li><li><strong>Addition</strong> — Adding properties to an object.</li><li><strong>Reading/Retrieving</strong> — Reading the value associated with a key.</li><li><strong>Existence</strong> — Whether a property exists in an object.</li><li><strong>Updation</strong> — Updating the values of existing properties.</li><li><strong>Deletion</strong> — Deleting existing properties.</li><li><strong>Iteration</strong> <strong>(Enumeration)</strong> — Looping over an object’s keys and values.</li><li><strong>Comparison</strong> — Comparing two different objects.</li><li><strong>Copying</strong> — Making a copy of an existing object</li></ul><h3>Creation</h3><p>Properties of an object are just like variables. Let’s see how can we create objects and properties —</p><h4>Creating an object using “<strong>literal</strong>” notation.</h4><p>A <strong>literal</strong> is a notation for representing a fixed value in source code. For example, 5 or &quot;foo&quot;. They <em>literally</em> represent the value. An object is represented as —</p><pre>const obj = <strong>{ }</strong>; // <strong>Creating an object</strong> using literal notation</pre><p>The curly braces { } create a new object.</p><p>You can also specify properties to be inserted at the time of creation.</p><pre>const obj = {<br>  <strong>firstName</strong>: &#39;Alex&#39;,<br>  &#39;<strong>lastName&#39;</strong>: &#39;Martin&#39;, <strong>// Using string quotes</strong><br>  <strong>dateOfBirth</strong>: &#39;18th October&#39;,<br>  <strong>friends</strong>: [ &#39;Bob&#39;, &#39;Christine&#39; ]<br>};</pre><p>The property names are treated as strings. That is, firstName and &#39;firstName&#39; are same. An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string.</p><p><strong>Note that the values can be any value type. That is, both primitive types and an object can be used as values.</strong></p><pre>const obj = {<br>   <strong>nestedObj</strong>: {<br>      name: &#39;Alex&#39;<br>   }<br>}</pre><p>The nestedObj is a key that holds another object. <strong>The nesting can be arbitrary and cyclic too!</strong></p><h4>Creating objects using Object constructor</h4><pre>const obj = <strong>new Object();</strong></pre><p>This effect of this code and the literal notation is the same. However, <strong>it is advised not to use this pattern.</strong> You can read more about it <a href="https://stackoverflow.com/questions/4597926/what-is-the-difference-between-new-object-and-object-literal-notation">here</a>.</p><h4><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Computed Properties</a></h4><p>You can also use an expression that will be evaluated to a string using the new <strong>computed property</strong> syntax. As an example —</p><pre>const propertyName = &#39;firstName&#39;;<br>const obj = {<br>  <strong>[propertyName.toUpperCase()]</strong>: &#39;Alex&#39;,<br>}</pre><pre>// { FIRSTNAME: &#39;Alex&#39; } </pre><p>Note the variable propertyName. In obj, we wrap the expression propertyName.toUpperCase() in [ ] to make it a <em>computed property</em>. As expected, in the resulting output, the stringfirstName is turned into uppercase.</p><h4>Function as key values</h4><p>In an object, when we have a function as a value to a key, then the function is called a <strong>method</strong>. <strong>This is one of the most important features of objects</strong>. The methods have access to the key-value pairs of the object. <strong>They can specify behavior in an object.</strong></p><pre>const obj1 = {<br>  firstName: &#39;ALEX&#39;,<br>  lastName: &#39;MARTIN&#39;,<br>  <strong>printFullName</strong>() {<br>    return `${this.firstName} ${this.lastName}`<br>  }<br>};</pre><pre>obj1.printFullName();<br>//=&gt; &#39;ALEX MARTIN&#39;</pre><p>We add printFullName method on obj1. The method has access to the properties of the object using the this keyword. We return the full name formatted using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a>. In this case, the <strong>behavior</strong> is to print the full name. You can read more about methods <a href="https://blog.bitsrc.io/a-practical-guide-to-es6-arrow-functions-c16975100cf5">here</a>.</p><h3>Addition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*0wEWV9ae1-W_n6ejf8jqqQ.gif" /><figcaption>Via <a href="https://gph.is/28QOWhn">Giphy</a></figcaption></figure><p>After we have created our object, we can add properties to it. There are two distinct ways of adding properties —</p><h4><strong>Dot Notation</strong></h4><pre>obj.<strong>address</strong> = &#39;Earth&#39;;</pre><p>The object and the property name is separated by a . (dot). If a property with the same name exists, its value will be overwritten. <strong>Otherwise, a new property with property name </strong><strong>address will be added to the object</strong>.</p><p><strong>An object can only contain a single key with one value. We can’t have a single key having two different values.</strong></p><p><strong><em>Caveat</em>: </strong>Using the dot-notation, you can’t use property names that are <strong>numbers, or string that contain spaces, or special character, or dynamic properties</strong>. For example, these will throw a SyntaxError.</p><pre>obj.5 = &#39;five&#39;; // <strong>Using numbers as property names</strong><br>obj.first name = &#39;alex&#39; // <strong>Using spaces between property names</strong><br>obj.first-name = &#39;alex&#39; // <strong>Using special characters -</strong></pre><h4><strong>Bracket Notation</strong></h4><p>If you don’t want to be limited by the above caveats, you may consider using bracket notation.</p><pre>obj[<strong>&quot;address&quot;</strong>] = &#39;Earth&#39; // <strong>Note the quotes</strong> </pre><p>Here we are adding address property to the obj object.</p><p><strong>A few things to note —</strong></p><ul><li>The part between the brackets is an expression. That means we can use variables there. <em>See the example below.</em></li><li>The type of properties can be either astring or a<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">symbol</a>. If the property is an expression, it will be evaluated. If the property is of any other type, it will be coerced to a string value.</li></ul><pre>const propName = &#39;address&#39;;<br>obj[<strong>propName</strong>]  = &#39;Earth&#39; // No string quotes</pre><p>Executing obj.propName adds a property propName whereas obj[propName] adds a property after evaluating the variable propName. The content of propName is address, so a property address with the value Earth is added to obj.</p><p>Also, these are now valid —</p><pre>obj[5] = &#39;five&#39;; // <strong>5 is coerced to a string to make &#39;5&#39;</strong><br>obj[<strong>&#39;first name&#39;</strong>] = &#39;alex&#39;; // property as string<br>obj[<strong>&#39;first-name&#39;</strong>] = &#39;alex&#39;; // property as string</pre><h3>Reading/Retrieving</h3><p>Retrieving a property is by far the most complex to understand in JavaScript. Let’s see some simple examples —</p><pre>obj.address         // =&gt; &#39;Earth&#39;<br>obj[&#39;firstName&#39;]    // =&gt; &#39;Alex&#39;<br>obj[&#39;middleName&#39;]   // =&gt; undefined</pre><p>Like addition, we can use the dot-notation or bracket notation get the value of a property. If the property exists, we get its value. If the property does not exist, we get undefined. <em>Simple!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*zCoWGsnZzR0kjKY1Sa4PKQ.gif" /><figcaption>There is always one! (via <a href="http://gph.is/1SVccNv">Giphy</a>)</figcaption></figure><h4>A Primer on Prototypes</h4><p>Objects are not just containers of key-value pairs. They have one more very interesting property. <strong><em>They can have a parent</em>. </strong>That is, they store a link to another object. This <em>parent object </em>is also consulted when a property is read.</p><p>And not just that. <strong>That <em>parent</em> can also have a <em>parent</em>.</strong> And that grandparent object is consulted too when a property is read. This repeats until we reach an object that does not have any parent i.e the parent is null.</p><p>Here’s the rough algorithm used when we retrieve a property —</p><p><strong>Goal</strong>: Read middleName from the object obj. (Note that middleName does not exist in obj )</p><p>(Rough) Algorithm —</p><ul><li>Let <strong>CurrentObject</strong> = obj. Let <strong>CurrentKeyName</strong> = middleName.</li><li>If <strong>CurrentObject</strong> has <strong>CurrentKeyName</strong>, return associated value.</li><li>Else, let <strong>CurrentObject</strong> = parent of <strong>CurrentObject</strong>.</li><li>Check for <strong>CurrentKeyName </strong>again in <strong>CurrentObject. </strong>If found, return value.</li><li>If<strong> CurrentObject </strong>has no parent and does not have <strong>CurrentKeyName, </strong>return<strong> </strong>undefined<strong>.</strong></li></ul><p>In the last step, <strong>CurrentObject </strong>would contain the final <em>parent-less</em> object. By this time, we have checked every object in the <strong><em>chain</em></strong> and none of them have the property that we are looking for. <strong>If the property is found at any level</strong>, its value is returned.</p><p>This chain is called the “<strong>prototype”</strong> chain. By default, all objects have their parent as Object.prototype. There is <strong>no</strong> parent to Object.prototype. That’s where the chain ends, normally. Here’s a representation of it —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*e_WObAqRpRys8U7cE7qvQg.jpeg" /><figcaption>Prototype chain</figcaption></figure><p>The [[Prototype]] property keeps this reference to the parent object. It’s an <em>internal</em> property which means that we can’t access it directly. <strong>We can use </strong><strong>Object.getPrototypeOf function to get the parent (aka “prototype”) of an object.</strong></p><p><strong>An important point to note</strong> is that the <em>prototype chain</em> is consulted only while reading a value. <strong>It does not affect addition, updating or deletion of properties on parent objects. </strong>One way to look at this is — You have <strong>read-only</strong> access to all things your parent (and their parents) have.</p><h4>Undefined</h4><p><strong>If the property does not exist in an object(or its parents)</strong>, we get undefined. What happens when we intentionally set a property’s value to undefined?</p><pre>obj.<strong>firstName</strong> = <strong>undefined</strong>;</pre><p>In this case, we <em>have </em>the property but its value is purposely not defined. When we retrieve the value, we’ll get undefined. <strong>But how can we be sure that its value in <em>intentionally</em> </strong><strong>undefined or the property does not exist on the object?</strong></p><p>To ascertain that we need to show the existence of a property. <em>Keep reading!</em></p><h3>Existence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*xFFsgLM8gclT-jxbEZe18Q.gif" /><figcaption>Even with undefined. (via <a href="http://gph.is/2q02q2N">Giphy</a>)</figcaption></figure><p>Sometimes we don’t care what value a property has. We only want to know whether the given object has the given property or not. There are 2 ways to know that —</p><h4>in operator</h4><pre>&#39;firstName&#39; in obj;       // =&gt; <strong>true<br></strong>&#39;middleName&#39; in obj;      // =&gt; <strong>false</strong> <br>&#39;<strong>isPrototypeOf</strong>&#39; in obj;   // =&gt; <strong>true</strong></pre><p>The syntax is <strong>String (or Symbol) </strong><strong>in object</strong>. It will evaluate to true or false depending on whether the property exists.</p><p>Attentive readers may be surprised to see the last example ( &#39;isPrototypeOf<strong>&#39;</strong> in obj ) evaluate to true. This is the <em>gotcha </em>of in operator.</p><p>isPrototypeOf is a property of the parent of obj. Just like <strong>Reading </strong>a property, the entire <em>prototype chain</em> is consulted before true or false is returned. If the property is found at any level, true is returned.</p><p>What if we want our <strong><em>own</em></strong> properties? Properties that exist only on the current object in question irrespective of whether that same property exists on parents or not.</p><h4>hasOwnProperty</h4><p>It’s a function that can be accessed through an object because of <em>prototypes</em>. It takes string key name ( or symbol) as an argument.</p><pre>obj.<strong>hasOwnProperty</strong>(&#39;firstName&#39;);        // =&gt; true<br>obj.<strong>hasOwnProperty</strong>(&#39;middleName&#39;);       // =&gt; false<br>obj.<strong>hasOwnProperty</strong>(&#39;isPrototypeOf&#39;);    // =&gt; false</pre><p>This gives more predictable results. However, it’s not without its own set of <em>gotchas</em>. Read about them <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name">here</a>.</p><h3>Updation</h3><p>Updating is simple. It’s just like addition. You can use dot-notation or bracket-notation. Here’s an example —</p><pre>obj.<strong>firstName</strong> = &#39;Timothy&#39;<br>obj[&#39;<strong>firstName</strong>&#39;] = &#39;Timothy&#39;</pre><p>It has the side effect of creating a new property firstName and setting the value Timothy <strong>if the property did not exist</strong>. If you don’t want that, you should pair your code with <strong>existence</strong> checks.</p><p>Also, updating a property <em>always </em>affects the object on which it is performed. It does not modify any object in the <em>prototype chain</em>.</p><h3>Deletion</h3><p>Deletion is performed using thedelete operator. Again, we can use both the notations.</p><pre><strong>delete</strong> obj.firstName;      // =&gt; true<br><strong>delete</strong> obj[&#39;firstName&#39;];   // =&gt; true</pre><p><strong>The return value of </strong><strong>delete operator is </strong><strong>true if the property was successfully deleted. </strong>Else, it will be false. We can make properties un-deletable. So, it is important to check the output of delete.</p><p>Also, merely setting a property’s value to undefined won’t delete the said property.</p><h3>Iteration (Enumeration)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*nXdh-I5Grt5DkFJyyV0J-A.gif" /><figcaption><a href="https://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot</a> set (via <a href="https://gph.is/2z5HNuI">Giphy</a>)</figcaption></figure><p>An object is a collection of key-value pairs. Often times you want to process the set of all values or keys and create another object with transformed values or key names. <strong>Unlike arrays, you can’t simply iterate an object</strong>. Here are a few ways to iterate objects —</p><h4>for-in loops</h4><p>for-in loop is just like a normal for loop except that it <strong>iterates on an object. </strong>You get the properties one by one. Here’s an example using obj object —</p><pre><strong>for</strong> (const property <strong>in</strong> obj) {<br>  <strong>const value = obj[property]; // Read the value </strong><br>  console.log(property, value);<br>}</pre><pre>// firstName Alex<br>// lastName Martin<br>// dateOfBirth 18th October<br>// friends [ &#39;Bob&#39;, &#39;Christine&#39; ]</pre><p><strong>Note —</strong></p><ul><li><strong>The order of appearance of properties is not fixed in an object.</strong></li><li>for-in loop will return all <strong>string</strong> properties. It won’t give Symbol properties.</li><li><strong>The prototype chain <em>is </em>consulted</strong>, and all <strong><em>enumerable</em></strong> properties of parents are also returned. (In short, enumerable properties are those properties which are visible to looping constructs.)</li></ul><p>Because the prototype chain is consulted, we may get unwanted properties in a for-in loop. We can put an existence check using hasOwnProperty to only get <em>own </em>properties, but we have better ways to do the same thing now.</p><h4>Object.keys()</h4><p>Object.keys() is similar to for-in loop except that <strong>it only returns the object’s own keys in an array</strong>. That is, the prototype chain is not consulted. We can then iterate on this array using a for-of or a for loop. Here’s an example —</p><pre>const allProperties = <strong>Object.keys</strong>(obj); </pre><pre>// =&gt; [ &#39;firstName&#39;, &#39;lastName&#39;, &#39;dateOfBirth&#39;, &#39;friends&#39; ]</pre><pre><br><strong>for</strong> (const property <strong>of</strong> allProperties) {<br>  <strong>const value = obj[property];</strong><br>  console.log(property, value);<br>}</pre><p>Attentive readers will see that we have to <em>manually</em> read the value inside the loop using const value = obj[property];. What if we only want the <strong>values</strong>?</p><h4>Object.values()</h4><p>Object.values() has similar restrictions as Object.keys(), but it returns an array of <strong>values</strong> instead of the <strong>keys</strong>.</p><pre>const allValues = <strong>Object.values</strong>(obj);</pre><pre>// =&gt; [ &#39;Alex&#39;, &#39;Martin&#39;, &#39;18th October&#39;, [ &#39;Bob&#39;, &#39;Christine&#39; ] ]</pre><p>What if we want both <strong>values</strong> and <strong>properties</strong> at the same time?</p><h4>Object.entries()</h4><p>Same as .keys() and .values() except that we get an array of [key, value] pairs.</p><pre>const allEntries = <strong>Object.entries</strong>(obj);</pre><pre>// =&gt; <em>Output</em></pre><pre>[ [ &#39;firstName&#39;, &#39;Alex&#39; ],<br>  [ &#39;lastName&#39;, &#39;Martin&#39; ],<br>  [ &#39;dateOfBirth&#39;, &#39;18th October&#39; ],<br>  [ &#39;friends&#39;, [ &#39;Bob&#39;, &#39;Christine&#39; ] ] ]</pre><p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">array “destructuring”</a> and for-of loop to iterate entries very cleanly.</p><pre><strong>for</strong> (const <strong>[key, value]</strong> of <strong>Object.entries</strong>(obj)) {<br>  console.log(key, value);<br>}</pre><p>One restriction the above methods pose is that they only return <strong>string </strong>properties and not symbols in an object. <em>What if we want both?</em></p><h4>Reflect.ownKeys()</h4><p>ownKeys return <strong>both</strong> string-based and symbol properties. <strong>Note</strong> that we are using Reflect module, and not Object module.</p><h3>Comparison</h3><p>There are no good in-built of ways of comparing two objects. When you use the == or === operators, they only compare the <em>references </em>of the objects. References can be understood as “memory addresses” of the objects.<strong> Only primitives types are compared by values.</strong></p><p>Now, <strong>two</strong> objects can have the same <strong>key-values pairs </strong>but they <strong>can’t</strong> occupy the same location in memory or <strong>reference</strong>. The object is only equal to itself as the example shows us —</p><pre>const obj1 = {<br>  name: &#39;Alex&#39;,<br>}</pre><pre>const obj2 = {<br>  name: &#39;Alex&#39;,<br>}</pre><pre>obj1 === obj2    // =&gt; <strong>false</strong><br>obj1 === obj1    // =&gt; <strong>true</strong></pre><p>See <em>exercises </em>below for a solution to this.</p><h3>Copying</h3><p>This is another hard aspect of objects. When we use the = operator on an object, we merely copy its reference. Let’s see this by an example —</p><pre>const obj1 = {<br>  name: &#39;Alex&#39;,<br>}</pre><pre>const obj2 = obj1;</pre><p>We create an object obj1. When we do obj2 = obj1, obj2 does not get another new object with its own key-value pairs. Rather, it starts pointing to the object pointed by obj1. This is the core difference between <a href="https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy"><strong>shallow copy</strong></a> and a<strong> </strong><a href="https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy"><strong>deep copy</strong></a>. In deep copy, you would get <strong>another </strong>object with its own set of key-value pairs (having the same value as original ones).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*8zJzgrmz5HeWNcCPiYQ0XA.jpeg" /><figcaption>Shallow vs Deep Copy</figcaption></figure><p>There are multiple ways to do a deep copy —</p><h4>Object Spread Operator</h4><p>We can use ... operator to a top-level deep copy. Here’s an example —</p><pre>const obj1 = {<br>  <strong>name</strong>: &#39;Alex&#39;,<br>  <strong>nestedObj</strong>: {<br>    address: &#39;Earth&#39;<br>  }<br>}</pre><pre>const obj2 = {<br>  <strong>...obj1      // Spreading the properties of obj1</strong><br>}</pre><p>However, <strong>this is only effective for the top-level primitive properties.</strong> In this case, obj2 gets its own name property. However, nestedObj is still copied <strong><em>shallowly</em></strong>.</p><p>Also, if the <strong>value</strong> of a property is a function then we can’t create a copy of function reliably in JavaScript. Hence, the functions/methods have to be shared.</p><h4>JSON.stringify</h4><p>We take a JSON representation of an object and parse it again to create another object with the same key-value pairs. This has the nice property that nested objects are also deeply copied.</p><pre>const obj2 = <strong>JSON.parse</strong>(<strong>JSON.stringify</strong>(obj));</pre><p><strong>One drawback is that keys whose values are </strong><strong>undefined, or functions or a </strong><strong>Symbol are skipped</strong>. It has many more rules that you can read <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Exceptions">here</a>.</p><h4>Object.assign</h4><p>The assign function takes a source and a target object. It copies all the <em>enumerable, own </em>key-value pairs in the target from the source.</p><pre>const obj2 = <strong>Object.assign</strong>({}, obj1);</pre><p>In this case, the source is obj1 and the target is an empty object { } .</p><p>Just like <strong>object spread operator</strong>, assign does not copy deeply on all levels and both <strong>String</strong> and <strong>Symbol</strong> properties are copied.</p><h3>What about arrays?</h3><p>Arrays are objects too. The only difference is that the keys are predetermined to be whole numbers (+0 ≤ i &lt; 2³²–1). They are 0, 1, 2 … etc. by default. Also, while creating an array, the keys are automatically set. If we check using typeof [], we will get object.</p><pre>const arr = [&#39;Alex&#39;, &#39;Earth&#39;];</pre><pre><strong>typeof arr; </strong>      // =&gt; <strong>object</strong></pre><pre><strong>Object.entries</strong>(arr);  <br>// [ [ &#39;0&#39;, &#39;Alex&#39; ], [ &#39;1&#39;, &#39;Earth&#39; ] ]</pre><p>Arrays have length property denoting the number of items in the array that is managed by JavaScript. From the example, we can see that Object.entries return the <strong>key-value</strong> pairs of the arr <strong><em>object</em></strong>.</p><h3>And functions?</h3><p>They are objects too. Specifically, they are objects with <strong><em>internal (not accessible to us) </em>[[Call]]</strong> method. Let’s see —</p><pre>function <strong>func1</strong>() {<br>  return &#39;Alex&#39;;<br>}</pre><pre>typeof func1;    // =&gt; &#39;function&#39;</pre><pre>func1.name;      // =&gt; &#39;func1&#39;</pre><pre><strong>func1.address = &#39;Earth&#39;;</strong> <strong>// Setting our own property</strong></pre><pre>func1.address;      // =&gt; &#39;Earth&#39; <br>func1[&#39;address&#39;];   // =&gt; &#39;Earth&#39;</pre><p>We declare func1 as a function. If we do typeof func1, we get function instead of object. However, that is because the <a href="https://tc39.github.io/ecma262/#table-35">ECMA Specification says</a> so.</p><p>All functions have certain properties on them by default. name is one of them which stores the name of the function. In this case, name gives us func1 which was the original name of the declared function.</p><p>We can also add our own properties. In the example, address was added to func1 and later read like a normal property.</p><h3>Conclusion</h3><p>We have discussed quite a few things about objects. However, we have barely scratched the surface. There is another layer to JavaScript objects that we haven’t discussed. Hopefully, we’ll see that in a different article. In the meantime, here are a few exercises to cement your understanding of how objects work.</p><h4>Exercises</h4><ul><li>Given an object, make a copy of the object with all key names capitalized.</li></ul><pre>const obj = { name: &#39;Alex&#39; };<br>const newObj = <strong>capitalize</strong>(obj);</pre><pre>// =&gt; { NAME: &#39;Alex&#39; }</pre><ul><li>Create an equivalent of Array.map and Array.filter for objects. The callback will receive both key and value. See example below —</li></ul><pre>const obj1 = {<br>  firstName: &#39;ALEX&#39;,<br>  lastName: &#39;MARTIN&#39;<br>};</pre><pre><strong>const newObj = objectMap</strong>(obj1, (key, value) =&gt; {<br>  return [<br>    key.toUpperCase(),<br>    value.toLowerCase(),<br>  ];<br>});</pre><pre>// =&gt; { FIRSTNAME: &#39;alex&#39;, LASTNAME: &#39;martin&#39; }</pre><p>What happens when the keys are Symbols?</p><ul><li>Write a function to <a href="https://stackoverflow.com/questions/1068834/object-comparison-in-javascript">deep compare</a> two objects by value. What happens when the object’s values are functions? What about symbols?</li></ul><p><strong>Try not to use regular </strong><strong>for loops for the exercises.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eKQgwIipbItmwTchWS4vRQ.gif" /><figcaption>You deserve it! (via <a href="https://gph.is/2gjGfzK">Giphy</a>)</figcaption></figure><h3>Learn more</h3><ul><li><a href="https://bit.dev/">Bit. Composable software.</a></li><li><a href="https://blog.bitsrc.io/11-javascript-utility-libraries-you-should-know-in-2018-3646fb31ade">11 Javascript Utility Libraries you Should Know in 2019</a></li><li><a href="https://blog.bitsrc.io/understanding-design-patterns-in-javascript-13345223f2dd">Understanding Design Patterns in JavaScript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d6b9205cd66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/the-chronicles-of-javascript-objects-2d6b9205cd66">The Chronicles of JavaScript Objects</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to ES6 Arrow Functions]]></title>
            <link>https://medium.com/bitsrc/a-practical-guide-to-es6-arrow-functions-c16975100cf5?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16975100cf5</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 15:11:51 GMT</pubDate>
            <atom:updated>2019-03-22T21:26:09.763Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tale of two functions… with examples.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nP3F4PpwWwkqEnEGy3Lnwg.jpeg" /></figure><p>ECMAScript, in ES6, introduced a new way of making functions. They are popularly known as Arrow Functions (also known as Fat Arrow Functions) inspired by <a href="https://coffeescript.org/#fat-arrow">CoffeeScript’s Arrow</a> functions.</p><p>In this article, we are going to see the motivation for such a decision, and also compare and contrast some differences between normal, traditional functions and arrow functions.</p><p>The primary goal of Arrow Functions is to address and resolve several common pain points of traditional Function Expression.</p><ul><li>Shorter syntactical form (() =&gt; {} vs. function () {})</li><li><strong>Lexical</strong> this binding</li></ul><p>In JavaScript, functions are the workhorse of the language. They are used to do multiple things. <strong>Hence, the shorter syntax is definitely a welcome change.</strong></p><p>Tip: Don’t copy-paste functionalities between projects. Use open source tools like <a href="https://github.com/teambit/bit"><strong>Bit</strong></a> to easily share and sync components between projects and apps, and build faster with your team. It’s OSS, so feel free to give it a try…</p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhTW9KUUUUhxAccQ21_apw.png" /></a></figure><h3>Syntax</h3><p>In Arrow functions, the <strong>parameter list</strong> and the <strong>function body</strong> is separated by a =&gt; symbol. That is, the function keyword is effectively replaced by =&gt;. The parameters come first, and then the =&gt; symbol, which is then proceeded by the function body.</p><p>Here’s a brief overview of the syntax of arrow functions.</p><ul><li><strong>An Empty function (no body)</strong></li></ul><pre><strong>const</strong> func1 = () =&gt; { };</pre><p>When func1 is invoked, undefined returned.</p><ul><li><strong>Single Parameter</strong></li></ul><pre><strong>const</strong> add1 = <strong>x</strong> =&gt; x + 1;</pre><p>add1 adds one to a given number. The body of the function is x + 1. Note that the return statement is missing. In absence of a block, the expression following the =&gt; symbol is returned by default. Also, you can’t use statements like if-else or try-catch without a block.</p><ul><li><strong>Multiple parameters</strong></li></ul><pre><strong>const</strong> add1 = <strong>(x)</strong> =&gt; x + 1;</pre><pre><strong>const</strong> sum = <strong>(num1, num2)</strong> =&gt; num1 + num2;</pre><pre><strong>const</strong> sum = <strong>(num1, num2)</strong> =&gt; {<br>    <strong>return</strong> num1 + num2;<br>}</pre><p>These two definitions of sums are equivalent. Note that while passing more than one parameter, <strong>we need to wrap them in parentheses</strong>. Parentheses around a single parameter are optional, however.</p><ul><li><strong>Returning Objects</strong></li></ul><p>If you want to return objects from an arrow function, you need to wrap them in parentheses.</p><pre><strong>const</strong> details = name =&gt; <strong>({ firstName: name })</strong>;</pre><p>Calling details(&#39;Arfat&#39;) is going to produce an object { firstName: &#39;Arfat&#39; }.</p><p>If you forget the parentheses around the object, details(&#39;Arfat&#39;) is going to return undefined.</p><pre><strong>const</strong> details = name =&gt; <strong>{ firstName: name }</strong>;</pre><p>The reason for that is because JavaScript assumes { to be an opening of a block and not the beginning of an object. In the block, firstName becomes a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label">label</a>. Since there exists a block, we need a <strong>return</strong> statement to get the object back.</p><pre><strong>const</strong> details = (name) =&gt; { <br>  <strong>return { firstName: name };</strong><br>}</pre><ul><li><strong>As Callbacks</strong></li></ul><p>With arrow functions, things become much terser when passing a callback to methods such as map or reduce.</p><pre><strong>const</strong> powerOf2 = [1, 2, 3, 4].map(el =&gt; el ** 2) <br>// [ 1, 4, 9, 16 ]</pre><p>Here’s the ES5-style doing the same thing.</p><pre>// <strong>Here&#39;s the ES5 way</strong><br><strong>const</strong> powerOf2 = [1, 2, 3, 4].map(function(el) {<br>  return <strong>el ** 2;</strong><br>});</pre><p>We can already see that arrow functions simplify passing callback functions with much nicer syntax.</p><p>Before talking about the second point, let’s take a little detour and see various forms of functions in JavaScript.</p><h3>One Function to Rule Them All</h3><p>Functions can act in various ways in JavaScript. Let’s look at them —</p><h4><strong>Traditional Functions (that is, outside any object)</strong></h4><p>You can think of them as Java-style functions. They take certain arguments and do something with them. They act as “procedures” or <a href="https://en.wikipedia.org/wiki/Subroutine">subroutines</a>. For example,</p><pre>function add1(num1, num2) { // function declaration<br> return num1 + num2;<br>}<br>const add2 = function(num1, num2) { // function expression<br> return num1 + num2;<br>}</pre><h4>Object’s methods (inside an object)</h4><p>In this case, the <strong>functions are embedded in objects</strong>. In most cases, they are supposed to act on data stored in the object itself. For example, in the code below, getName() method returns the name property stored in details object.</p><p><strong>One important point to note is that the </strong><strong>this keyword inside a method refers to the object through which it was invoked, unless we manually override it.</strong></p><pre><strong>const</strong> details = {<br>  <strong>name</strong>: &#39;Arfat&#39;,<br>  getName: function () {<br>  return <strong>this.name</strong>;<br>  }<br>}<br>details.getName(); // &#39;Arfat&#39;</pre><h4>Constructor Functions</h4><p>Constructor functions “<strong>construct</strong>” objects. They are equivalent to classes in other languages. A class is considered as a factory for the production of “instances” or “objects”. Since JavaScript has no concept of a class (even though it has class keyword), functions rise up to the task. An example will demonstrate it —</p><pre>function Person(name) {<br>  <strong>this.name = name;</strong><br>}</pre><pre>const person1 = <strong>new</strong> Person(&#39;Arfat&#39;);</pre><pre>console.log(person1); <br>// Person { name: &#39;Arfat&#39; }</pre><p>A function, when used with the new operator, is called a constructor function. The new operator changes the behavior of the function. Among many changes that it does, in a function invoked with new operator, <strong>this refers to a newly-created empty object.</strong></p><h3>Lexical binding</h3><p>Before we understand the second point, let’s define <strong>lexical</strong> and <strong>binding</strong>.</p><p><strong>Binding</strong> is the association of code or data with an identifier(variable names) in a programming language.</p><p>The term <strong>lexical</strong> pertains to the “source code” of the program. Lexical binding means the portion of source code in which a binding of an identifier with a value exists. That is, the identifier is in “scope”.</p><p>In other words, in lexical binding, the resolution of an identifier depends on the location in the source code and the <strong>lexical context</strong>, which is defined by where the named variable or identifier is defined. Let’s understand by an example —</p><pre><strong>function</strong> outer() {<br>  <strong>const</strong> x = 5;<br>  return function () {<br>    <strong>const</strong> y = 7;<br>    <strong>return</strong> x + y;<br>  }<br>}</pre><p>The outer function has a variable x defined. outer function also returns another function that accesses the value of x and adds y to it. In this case, the “inner” function can access the variables of outer function.</p><p>The variable y is known as a <strong>bound</strong> variable and x is a “<strong>free</strong>” variable. In lexical binding, all <strong>free </strong>variables must belong to the parent scope. In this case, the parent scope is a function.</p><p><strong>So in short, a lexical binding can be thought of as taking (or retrieving) values from the parent scope.</strong></p><p><strong><em>Note</em></strong><em>: In contrast to Lexical Scope, Dynamic Scope also exist. Refer to </em><a href="https://en.wikipedia.org/wiki/Scope_(computer_science)"><em>this</em></a><em> for a good explanation.</em></p><p>So what exactly do we mean by “<strong>lexical </strong><strong>this binding</strong>”?</p><h3>What is ‘<em>this‘</em>?</h3><p>Consider the following code —</p><pre><strong>const</strong> details = {<br>  <strong>name</strong>: &#39;Arfat&#39;,<br>  <strong>getName</strong>: <strong>function</strong> () {<br>    return this.name;<br>  }<br>}<br>details.getName(); // &#39;Arfat&#39;</pre><p>Executing details.getName(); returns &#39;Arfat&#39;. In the getName function, we have return this.name. Here, the value of this is keyword is the details object. Hence, we can retrieve the name property.</p><p>However, a little change to the code can cause a different behavior. See this code for example —</p><pre><strong>const</strong> details = {<br>  name: &#39;Arfat&#39;,<br>  <strong>friends: [&#39;Bob&#39;, &#39;Alex&#39;],</strong><br>  <strong>getFriends</strong>: function () {<br>    this.friends.forEach(<strong>function</strong> (friend) {<br>      <strong>console.log(this.name + &quot; is friends with &quot; + friend);</strong><br>    });<br>  }<br>}</pre><pre>details.getFriends();</pre><pre>// undefined is friends with Bob<br>// undefined is friends with Alex</pre><p>We now have a friends key that is an array of string. We also now have a function called getFriends that prints who are the friends of Arfat. We can get that info by executing details.getFriends();. However, we don’t get the output that we expect.</p><p>Instead of printing Arfat is friends with Bob, we get undefined is friends with Bob. <em>What is happening?</em></p><p>If we trace the execution of getFriends() method, we see that we have a forEach method iterating on the friends array. forEach takes a function as a callback which is executed for each element for that array with the element being passed as an argument to the callback.</p><p><strong>However, in JavaScript, the callback function (and every traditional function) gets its own value of </strong><strong>this. </strong>This value is <em>different</em> from the details object. Hence, the getDetails methods has a value of this that is bound to details object, and the callback passed to the forEach method has a value of this that is <strong>not </strong>details object.</p><p>When the callback is searching for the this value, it invariably gets its own value <strong>first</strong> instead of the this value of getFriends method. In a sense, the this value of getFriends is <strong>shadowed</strong> by the callback’s own value.</p><p>One solution is to this problem is to use the that = this pattern. Let’s see the code —</p><pre>const details = {<br>  name: &#39;Arfat&#39;,<br>  friends: [&#39;Bob&#39;, &#39;Alex&#39;],<br>  getFriends: function () {<br>    <strong>const that = this;</strong><br>    this.friends.forEach(function (friend) {<br>      console.log(<strong>that.name</strong> + &quot; is friends with &quot; + friend);<br>    });<br>  }<br>}<br>details.getFriends();</pre><pre>// Arfat is friends with Bob<br>// Arfat is friends with Alex</pre><p>We create a new variable that and bind it to the value of this in the getFriends methods. In the callback to forEach, instead of using this, we use that. Since the callback does not have a variable called that, when it searches for it, it also looks in the parent scope. In this case, that variable is found in the parent scope which was correctly bound to the details object. Now, the code behaves as expected.</p><p>Arrow functions solve this <strong>manual</strong> <strong>rebinding</strong> of this. This is such a common problem that forEach method also takes an optional second parameter as a custom value of this. Here’s how that code looks like —</p><pre>const details = {<br>  name: &#39;Arfat&#39;,<br>  friends: [&#39;Bob&#39;, &#39;Alex&#39;],<br>  getFriends: function () {<br>    this.friends.forEach(function (friend) {<br>      console.log(<strong>this.name</strong> + &quot; is friends with &quot; + friend);<br>    }, <strong>this</strong>);<br>  }<br>}<br>details.getFriends();</pre><p>This code will also work as intended.<strong> A lot of methods in JavaScript take an optional </strong><strong>this argument because of above-mentioned problems.</strong></p><h3>Arrow functions to the Rescue</h3><p>Arrow functions bind this <strong>lexically</strong>. In other words, Arrow functions <strong>always </strong>have a value of this keyword taken from the parent scope. That is, they don’t have any intrinsic, own this value.</p><p>So in the above code, instead of using a traditional function, we can now use an arrow function. Since the this value will always be of the parent, we get the this value of getFriends method which was correctly set to details object. Here’s the code —</p><pre>const details = {<br>  name: &#39;Arfat&#39;,<br>  friends: [&#39;Bob&#39;, &#39;Alex&#39;],<br>  getFriends: function () {<br>    this.friends.forEach(<strong>friend =&gt; {<br>      console.log(this.name + &quot; is friends with &quot; + friend);<br>    }</strong>);<br>  }<br>}<br>details.getFriends();</pre><pre>// Arfat is friends with Bob<br>// Arfat is friends with Alex</pre><p>Also, this is not the <strong><em>only </em></strong>value taken from the parent scope. <strong><em>Let’s find out more.</em></strong></p><h3>Arrow Functions vs Traditional functions</h3><p>Arrow functions differ from traditional functions in some major ways.</p><p>Here’s what the <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions">ECMA specification</a> says about Arrow functions —</p><blockquote>An <strong>Arrow Function</strong> does not define local bindings for <strong>arguments</strong>, <strong>super</strong>, <strong>this</strong>, or <strong>new.target</strong>. Any reference to arguments, super, this, or new.target within an ArrowFunction <strong>must resolve to a binding in a lexically enclosing environment.</strong></blockquote><ul><li><strong>Can’t use </strong><strong>arguments special variable.</strong></li></ul><p>The purpose of arguments variable was to expose all the parameters in an array-like object. In ES6, we have <a href="https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831">rest parameters</a> which supercede this task.</p><ul><li><strong>Can’t be used as a constructor.</strong></li></ul><p>There is no internal method [[Construct]] which allows a normal function to be called by new and no prototype property. Also, Arrow functions do not have their own new.target property, and hence, cannot be used as constructor functions. Rewriting the Person function using arrow functions —</p><pre><strong>const Person = name =&gt;</strong>  {<br>  this.name = name;<br>}</pre><pre>const person1 = <strong>new</strong> Person(&#39;Arfat&#39;); // Will throw an error</pre><p>Running the above will cause an exception Person is not a constructor.</p><ul><li><strong>Can’t change the </strong><strong>this binding.</strong></li></ul><p>The this value is <strong>always</strong> bound. It cannot be changed. Even by functions which manually reassign the this value, for example, .bind() or .apply().</p><p>However, they still have access to Function.prototype and bind(), apply(), and call() still work. The only difference is that they cannot bind a different this parameter value, but they can pass arbitrary arguments, as shown below.</p><pre>const add = (a, b) =&gt; a + b;<br>const add5 = <strong>add.bind(null, 5);</strong><br>add5(7); // 12</pre><ul><li><strong>Can’t be used as generator functions</strong></li></ul><p>To use ES6 generators, you have to use function* syntax.<em> Learn more about generators </em><a href="https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5"><em>here</em></a><em>.</em></p><p>Despite all these differences, arrow functions and traditional functions both have same typeof value and prototype value.</p><pre>typeof (<strong>() =&gt; {}</strong>) === &quot;function&quot;; // true</pre><pre>Object.getPrototypeOf(<strong>() =&gt; {}</strong>) === Function.prototype; // true</pre><h3>Conclusion</h3><p><strong>Normal, traditional functions are here to stay.</strong> They have their use cases and arrow functions cannot completely replace them. However, for the most part, when writing code, functions not relying on dynamic this value, or callbacks relying on parent’s this value can take advantage of arrow functions.</p><p>And if you are programming in a functional style, arrow functions give you a quick way to create beautiful-looking(IMO) short pure functions.</p><p><strong>I write about JavaScript, Web Development, and Computer Science. Share this article if you like it.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff">Understanding Asynchronous JavaScript</a></li><li><a href="https://blog.bitsrc.io/understanding-design-patterns-in-javascript-13345223f2dd">Understanding Design Patterns in JavaScript</a></li><li><a href="https://blog.bitsrc.io/solid-principles-every-developer-should-know-b3bfa96bb688">SOLID Principles every Developer Should Know</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16975100cf5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/a-practical-guide-to-es6-arrow-functions-c16975100cf5">A Practical Guide to ES6 Arrow Functions</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Generators in ES6 JavaScript with Examples]]></title>
            <link>https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/6728834016d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 13:26:22 GMT</pubDate>
            <atom:updated>2019-06-25T22:47:24.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEHGVTF6h49u2-LR6cfCAw.jpeg" /></figure><p>ES6 introduced a new way of working with functions and iterators in the form of <strong>Generators (or generator functions)</strong>. A generator is a function that <strong>can stop midway</strong> and then continue <em>from where it stopped. </em><strong>In short, a generator <em>appears</em> to be a function but it <em>behaves</em> like an iterator.</strong></p><p><strong>Fun Fact</strong>: async/await <strong>can be</strong> based on generators. Read more <a href="https://tc39.github.io/ecmascript-asyncawait/">here</a>.</p><p>Generators are intricately linked with iterators. If you don’t know about iterators, <a href="https://codeburst.io/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e">here</a> is an article to better your understanding of them.</p><p><a href="https://codeburst.io/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e">A Simple Guide to ES6 Iterators in JavaScript with Examples</a></p><p>Here’s a simple analogy to have an intuition for generators before we proceed with the technical details.</p><p>Imagine you are reading a nail-biting techno-thriller. All engrossed in the pages of the book, you barely hear your doorbell ring. It’s the pizza delivery guy. You get up to open the door. <strong>However, before doing that, you set a bookmark at the last page you read.</strong> You mentally save the events of the plot. Then, you go and get your pizza. Once you return back to your room, you begin the book <strong><em>from the page that you set the bookmark on</em></strong><em>. </em>You don’t begin it from the first page again. In a sense, you acted as a generator function.</p><h3>Introduction</h3><p>Let’s see how we can utilise generators to solve some common problems while programming. But before that, let’s define what generators are.</p><h4>What are Generators?</h4><p>A normal function such as this one cannot be stopped <em>before</em> it finishes its task i.e its last line is executed. It follows something called <a href="https://en.wikipedia.org/wiki/Run_to_completion_scheduling">run-to-completion</a> model.</p><pre>function normalFunc() {<br>  console.log(&#39;I&#39;)<br>  console.log(&#39;cannot&#39;)<br>  console.log(&#39;be&#39;)<br>  console.log(&#39;stopped.&#39;)<br>}</pre><p>The only way to exit the normalFunc is by returning from it, or throwing an error. If you call the function again, it will begin the execution from the top <strong><em>again</em></strong>.</p><p>In contrast, a generator is a function that <strong>can stop midway</strong> and then continue <em>from where it stopped.</em></p><p>Here are some other common definitions of generators —</p><ul><li>Generators are a special class of functions that simplify the task of writing iterators.</li><li>A generator is a function that produces a sequence of results instead of a single value, i.e you <em>generate </em>​a series of values.</li></ul><p>In JavaScript, a generator is a function which returns an object on which you can call next(). Every invocation of next() will return an object of shape —</p><pre>{ <br>  value: Any,<br>  done: true|false<br>} </pre><p>The value property will contain the value. The done property is either true or false. When the done becomes true, the generator stops and won’t generate any more values.</p><p>Here’s an illustration of the same —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*7X8rtWOiz5RKENZ_vugmKg.png" /><figcaption>Normal Functions vs Generators</figcaption></figure><p>Note the dashed arrow that closes the <strong>yield-resume-yield</strong> loop just before <strong>Finish </strong>in <em>Generators </em>part of the image. <strong>There is a possibility that a generator may never finish.</strong> We’ll see an example later.</p><h4>Creating a Generator</h4><p>Let’s see how we can create a generator in JavaScript —</p><pre><strong>function *</strong> generatorFunction() { // Line 1<br>  console.log(&#39;This will be executed first.&#39;);<br>  <strong>yield</strong> &#39;Hello, &#39;;   // Line 2</pre><pre>  console.log(&#39;I will be printed after the pause&#39;);  <br>  <strong>yield</strong> &#39;World!&#39;;<br>}</pre><pre>const <strong>generatorObject</strong> = generatorFunction(); // Line 3</pre><pre>console.log(<strong>generatorObject.next()</strong>.value); // Line 4<br>console.log(<strong>generatorObject.next()</strong>.value); // Line 5<br>console.log(<strong>generatorObject.next()</strong>.value); // Line 6</pre><pre>// This will be executed first.<br>// Hello, <br>// I will be printed after the pause<br>// World!<br>// undefined</pre><p>Focus on the bold parts. For creating a generator function, we use function * syntax instead of just function. Any number of spaces can exist between the function keyword, the *, and the function name. Since it is just a function, you can use it anywhere that a function can be used i.e inside objects, and class methods.</p><p>Inside the function body, we don’t have a return. Instead, we have another keyword yield (Line 2). It’s an operator with which a generator can pause itself. Every time a generator encounters a yield, it “returns” the value specified after it. In this case, Hello, is returned. However, we don’t say “returned” in the context of generators. We say the “the generator has <strong><em>yielded</em></strong> Hello, ”.</p><p>We can also return from a generator. However, return sets the done property to true after which the generator cannot generate any more values.</p><pre>function *  generatorFunc() {<br>  yield &#39;a&#39;;<br>  <strong>return</strong> &#39;b&#39;; // Generator ends here.<br>  <strong>yield &#39;a&#39;;</strong> // Will never be executed. <br>}</pre><p>In Line 3, we create the generator object.<strong> It seems like we are invoking</strong> the function generatorFunction. Indeed we are! The difference is that instead of returning any value, a generator function <em>always </em>returns a generator object. The generator object is an iterator. So you can use it in for-of loops or other functions accepting an iterable.</p><p>In Line 4, we call the next() method on the generatorObject. With this call, the generator begins executing. First, it console.log the This will be executed first. Then, it encounters a yield ‘Hello, ‘. The generator yields the value as an object { value: &#39;Hello, &#39;, done: false } and suspends/pauses. Now, it is waiting for the next invocation.</p><p>In Line 5, we call next() again. This time the generator wakes up and begin executing from where it left. The next line it finds is a console.log. It logs the string I will be printed after the pause. Another yield is encountered. The value is yielded as the object { value: &#39;World!&#39;, done: false }. We extract the value property and log it. The generator sleeps again.</p><p>In Line 6, we again invoke next(). This time there are no more lines to execute. Remember that every function implicitly returns undefined if no return statement is provided. Hence, the generator returns (instead of yielding) an object { value: undefined, done: true}. The done is set to true. This signals the end of this generator. Now, it can’t generate more values or resume again since there are no more statements to be executed.</p><p>We’ll need to make new another generator object to run the generator again.</p><h3>Uses of Generators</h3><p>There are many awesome use cases of generators. Let’s see a few of them.</p><h4>Implementing Iterables</h4><p>When you implement an iterator, you have to manually make an iterator object with a next() method. Also, you have to manually save the state. Often times, it becomes really hard to do that. Since generators are also iterables, they can be used to implement iterables without the extra boilerplate code. Let’s see a simple example.</p><p><em>Problem: We want to make a custom iterable that returns </em><em>This, </em><em>is, and </em><em>iterable.. Here’s one implementation using iterators —</em></p><pre>const iterableObj = {<br>  [Symbol.iterator]() {<br>    <strong>let step = 0;</strong><br>    return {<br>      next() {<br>        <strong>step++;</strong><br>        if (step === 1) {<br>          <strong>return { value: &#39;This&#39;, done: false};</strong><br>        } else if (step === 2) {<br>          <strong>return { value: &#39;is&#39;, done: false};</strong><br>        } else if (step === 3) {<br>          <strong>return { value: &#39;iterable.&#39;, done: false};</strong><br>        }<br>        return { value: &#39;&#39;, done: true };<br>      }<br>    }<br>  },<br>}</pre><pre>for (const val of iterableObj) {<br>  console.log(val);<br>}</pre><pre>// This<br>// is <br>// iterable.</pre><p>Here’s the same thing using generators —</p><pre><strong>function *</strong> iterableObj() {<br>  yield &#39;This&#39;;<br>  yield &#39;is&#39;;<br>  yield &#39;iterable.&#39;<br>}</pre><pre>for (const val of iterableObj()) {<br>  console.log(val);<br>}</pre><pre>// This<br>// is <br>// iterable.</pre><p>You can compare both the versions. It’s true that this is some what of a contrived example. But it does illustrate the points —</p><ul><li>We don’t have to worry about Symbol.iterator</li><li>We don have to implement next().</li><li>We don’t have to manually make the return object of next() i.e { value: &#39;This&#39;, done: false }.</li><li>We don’t have to save the state. In the iterator’s example, the state was saved in the variable step. It’s value defined what was output from the iterable. We had to do nothing of this sort in the generator.</li></ul><h4>Better Async functionality</h4><p>Code using promises and callbacks such as —</p><pre>function <strong>fetchJson</strong>(url) {<br>    return fetch(url)<br>    .then(request =&gt; request.text())<br>    .then(text =&gt; {<br>        return JSON.parse(text);<br>    })<br>    .catch(error =&gt; {<br>        console.log(`ERROR: ${error.stack}`);<br>    });<br>}</pre><p>can be written as (with the help of libraries such as <a href="https://github.com/tj/co">co.js</a>)—</p><pre>const fetchJson = co.wrap(function * (url) {<br>    try {<br>        let request = <strong>yield</strong> fetch(url);<br>        let text = <strong>yield</strong> request.text();<br>        return JSON.parse(text);<br>    }<br>    catch (error) {<br>        console.log(`ERROR: ${error.stack}`);<br>    }<br>});</pre><p>Some readers may have noticed that it parallels the use of async/await. That’s not a co-incidence. async/await <strong>can</strong> follows a similar strategy and replaces the yield with await in cases where promises are involved. It can be based on generators. See this <a href="https://medium.com/@alezowszem/hey-great-article-few-remarks-here-ae93d827e47b">comment</a> for more info.</p><h4>Infinite Data Streams</h4><p>It’s possible to create generators that never end. Consider this example —</p><pre><strong>function *</strong> naturalNumbers() {<br>  let num = 1;<br>  while (true) {<br>    <strong>yield num;</strong><br>    num = num + 1<br>  }<br>}</pre><pre>const numbers = naturalNumbers();</pre><pre>console.log(numbers.next().value)<br>console.log(numbers.next().value)</pre><pre>// 1<br>// 2</pre><p>We make a generator naturalNumbers. Inside the function, we have an infinite while loop. In that loop, we yield the num. When the generator yields, it is suspended. When we call next() again, the generator wakes up, continues from where it was suspended (in this case yield num) and executes till another yield is encountered or the generator finishes. Since the next statement is num = num + 1, it updates num. Then, it goes to the top of while loop. The condition is still true. It encounter the next line yield num. It yields the updated num and suspends. This continues as long you want.</p><h4>Generators as observers</h4><p>Generators can also receive values using the next(val) function. Then the generator is called an observer since it wakes up when it receives new values. In a sense, it keeps <em>observing</em> for values and acts when it gets one. You can read more about this pattern <a href="http://exploringjs.com/es6/ch_generators.html#sec_generators-as-observers">here</a>.</p><h3>Advantages of Generators</h3><h4>Lazy Evaluation</h4><p>As seen with <strong>Infinite Data Streams</strong> example, it is possible only because of lazy evaluation. Lazy Evaluation is an evaluation model which delays the evaluation of an expression until its value is needed. That is, if we don’t need the value, it won’t exist. It is <strong>calculated </strong>as we demand it. Let’s see an example —</p><pre><strong>function *</strong> powerSeries(number, power) {<br>  let base = number;<br>  while(true) {<br>    yield Math.pow(base, power);<br>    base++;<br>  }<br>}</pre><p>The powerSeries gives the series of the number raised to a power. For example, power series of 3 raised to 2 would be <strong>9(3²) 16(4²) 25(5²) 36(6²) 49(7²). </strong>When we do const powersOf2 = powerSeries(3, 2); we just create the generator object. None of the values has been computed. Now, if we call next(), 9 would be computed and retuned.</p><h4>Memory Efficient</h4><p>A direct consequence of Lazy Evaluation is that generators are memory efficient. We generate only the values that are needed. With normal functions, we needed to pre-generate all the values and keep them around in case we use them later. However, with generators, we can defer the computation till we need it.</p><p>We can create combinator functions to act on generators. Combinators are functions that combine existing iterables to create new ones.One such combinator is take. It takes first n elements of an iterable. Here’s one implementation —</p><pre>function * take(n, iter) {<br>  let index = 0;<br>  for (const val of iter) {<br>    if (index &gt;= n) {<br>      return;<br>    }<br>    index = index + 1;<br>    yield val;<br>  }<br>}</pre><p>Here’s some interesting use cases of take —</p><pre>take(3, [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;])</pre><pre>// a b c</pre><pre>take(7, naturalNumbers());</pre><pre>// 1 2 3 4 5 6 7</pre><pre>take(5, powerSeries(3, 2));</pre><pre>// 9 16 25 36 49</pre><p>Here’s an implementation of <a href="https://github.com/sindresorhus/cycled">cycled</a> library (without the reversing functionality).</p><pre>function * cycled(iter) {<br>  const arrOfValues = [...iter]<br>  while (true) {<br>    for (const val of arrOfValues) {<br>      yield val<br>    }<br>  }<br>}</pre><pre>console.log(...take(10, cycled(take(3, naturalNumbers()))))</pre><pre>// 1 2 3 1 2 3 1 2 3 1</pre><h4>Caveats</h4><p>There are some points that you should remember while programming using generators.</p><ul><li><strong>Generator objects are one-time access only. </strong>Once you’ve exhausted all the values, you can’t iterate over it again. To generate the values again, you need to make a new generator object.</li></ul><pre>const numbers = naturalNumbers();</pre><pre>console.log(...take(10, numbers)) // 1 2 3 4 5 6 7 8 9 10<br><strong>console.log(...take(10, numbers))</strong> // This will not give any data</pre><ul><li>Generator objects do not allow random access as possible with arrays. Since the values are generated one by one, accessing a random value would lead to computation of values till that element. Hence, it’s not random access.</li></ul><h3>Conclusion</h3><p>A lot of things are yet to be covered in generators. Things such as yield *, return() and throw(). Generators also make <a href="https://en.wikipedia.org/wiki/Coroutine">coroutines</a> possible. I’ve listed some references that you can read to gain further understanding of generators.</p><p>You can head over to Python’s <a href="https://docs.python.org/2/library/itertools.html#itertools.chain">itertools</a> page, and see some of the utilities that allow working with iterators and generators. As an exercise, you can implement the utilities yourself.</p><h4>References —</h4><ul><li><a href="https://www.python.org/dev/peps/pep-0255/">PEP 255</a> — It’s the proposal for generators in Python. But the rationale is applicable to JavaScript as well.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Mozilla Docs</a></li><li>An in-depth four-part series by <a href="https://medium.com/u/5dccb9bb4625">Kyle</a> Simpson on generators and co-routines. Read <a href="https://davidwalsh.name/es6-generators">here</a>.</li><li>An in-depth review of generators by <a href="https://medium.com/u/7fab51e62203">Axel Rauschmayer</a>. Read it <a href="http://exploringjs.com/es6/ch_generators.html">here</a>.</li><li><a href="https://docs.python.org/2/library/itertools.html#itertools.chain">Python’s itertools</a> — It’s an builtin library in Python that has lots of utilities for working with generators and iterators.</li></ul><p><strong>I write about JavaScript, Web Development, and Computer Science. Follow me for weekly articles. Share this article if you like it.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6728834016d5" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5">Understanding Generators in ES6 JavaScript with Examples</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Proxies by Examining on-change Library]]></title>
            <link>https://codeburst.io/understanding-javascript-proxies-by-examining-on-change-library-f252eddf76c2?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/f252eddf76c2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 19:24:27 GMT</pubDate>
            <atom:updated>2018-04-12T16:19:11.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeZlbYvpCxYJ9prikN7UBQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Fi-GJaLRGKc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pankaj Patel</a> on <a href="https://unsplash.com/search/photos/javascript?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Javascript Proxies are a new addition in ES6. It’s a powerful feature that can be used for solving various problems elegantly. We are going to examine and re-create a small utility library by <a href="https://medium.com/u/37166cebf99b">Sindre Sorhus</a> called <a href="https://github.com/sindresorhus/on-change">on-change</a>. The aim is to conceptually understand JavaScript Proxies, and in the process, build something so that the concepts are reinforced.</p><p>I have tried to keep things as simple as possible.However, a little familiarity with JavaScript language is expected.</p><p>So what does on-change do? It’s a small utility that watches an object or array for changes. Let’s see a code sample to make things clear —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b6658ec3627c358c89b7e041a4b1e30/href">https://medium.com/media/5b6658ec3627c358c89b7e041a4b1e30/href</a></iframe><p>A few things to note —</p><ul><li>onChange is a function that takes two parameters: the object to watch, and the function to run when a change is encountered in the said object. It returns an object.</li><li>On line 17, when we set foo to true, the logger function is called.</li><li>On line 20, when we set an object that is deeply nested, even within arrays, logger is called. That is, it works recursively, so it will even detect if we modify a deep property like watchedObject.a.b[0].c = true.</li></ul><p>So let’s see how we can use JavaScript Proxies to re-create this utility! But before that, let’s study proxies.</p><h4>What is a Proxy?</h4><p>Consider this short code snippet —</p><pre>const someObject = { prop1: &#39;Awesome&#39; };</pre><pre>console.log(someObject.prop1);  // Awesome</pre><pre>console.log(someObject.prop2);  // undefined</pre><p>If we do someObject.prop1 we are going to get Awesome. But if we do someObject.prop2 we are going to get undefined because prop2 does not exist on someObject.</p><p>Let’s say we want to return a default value every time a non-existent property is accessed. That is, someObject.prop2 should give Oops! This property does not exist instead of undefined.<strong> How can we achieve this without modifying or adding new properties to </strong>someObject<strong>?</strong></p><p><strong>Welcome proxies!</strong> The Oxford English Dictionary defines a proxy as <strong><em>the authority to represent someone else</em>.</strong> That is exactly what a Proxy in JavaScript is. Proxies are part of ES6, and they enable us to <strong>intercept</strong> operations(such as setting a value or deleting a property) performed on objects. While accessing an object’s property, this is what happens —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*jtrYhKkdyQuMiD6vsA1XZA.jpeg" /><figcaption>Normal Execution of Program</figcaption></figure><p>When using a Proxy, things change a little bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*T0_FS6jQFk4N69casPuWnA.png" /><figcaption>With Proxy</figcaption></figure><p>As you can see from the above diagram, Proxy sits between the object and the program, mediating the exchange of values. The Proxy can check the object for a property key, and if it does not exist, <strong>it can send its own response too.</strong></p><p>Having shown how awesome proxies are, let’s see how we can create them in JavaScript. But before that, a few terms that you should be familiar with —</p><ul><li><strong>target — </strong>The object for which we will be making the proxy.</li><li><strong>traps — </strong>a fancy term for the operations that we will intercept. For example, accessing a property is called get trap. Setting a value to a property is called a set trap. Deleting a property from an object is called deleteProperty trap. There are many traps. You can see all of them <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">here</a>.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler"><strong>handler</strong></a><strong> — </strong>The object which contains all the traps, along with their descriptions.</li></ul><h4>Creating Proxies</h4><p>The first thing we need is an object for which we are creating the proxy. Let it be this —</p><pre>const originalObject = { firstName: &#39;Arfat&#39;, lastName: &#39;Salman&#39; };</pre><p>Now, we need to think of what traps we are going to intercept. Right now, we are going to intercept the get trap. The trap will live in the handler. So let’s create it.</p><pre>const <strong>handler</strong> = {<br>  <strong>get</strong>(<strong>target</strong>, <strong>property</strong>, <strong>receiver</strong>) {<br>    console.log(`GET ${property}`);<br>    return target[property];<br>  }<br>};</pre><p>A few things to note —</p><ul><li>The handler is a normal object.</li><li>The traps are functions (or methods) which are part of the handler. The names of the traps are fixed and predefined.</li><li>The get trap receives three parameters: <strong>target</strong>, <strong>property</strong>, <strong>receiver</strong>.</li><li>The target is the original object for which we created the proxy.</li><li>The property is the <em>name </em>of the property that is being accessed.</li><li>The receiver is either the proxy or an object that inherits from the proxy.</li></ul><p>Now, we need to combine the handler and the originalObject. We do this by using the Proxy constructor.</p><pre>const proxiedObject = <strong>new Proxy(originalObject, handler);</strong></pre><p>The entire code should look like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKtKssgvAfsBFTWExyIV0A.png" /><figcaption>Code Demo for proxy</figcaption></figure><p>You can run it in the browser’s console, or keep it in a file and run it using node (version ≥ 7 ). Here’s a sample run —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*S20qcC1yqFFNqD6efNnc4w.gif" /></figure><p>Now, if you log the firstName property of the proxiedObject —</p><pre>console.log(proxiedObject.firstName);<br>//=&gt; GET firstName<br>//=&gt; Arfat</pre><p>We are going to get two logs. If you get same outputs as above, that means everything was set up correctly.</p><p>Now, let’s modify the handler to handle non-existent properties.</p><pre>const newHandler = {<br>  get(target, property, receiver) {<br>    console.log(`GET ${property}`);</pre><pre><strong>  if (property in target) {<br>      return target[property];<br>    }</strong></pre><pre>return &#39;Oops! This property does not exist.&#39;;<br>  }<br>};</pre><p>Focus on the bold parts. <strong>We check whether the property exists on the target. If it exists, we return its value.</strong> Otherwise, we return Oops! This property does not exist..</p><p>Now, if you do —</p><pre>console.log(proxiedObject.<strong>thisPropertDoesNotExist</strong>);<br>// =&gt; GET thisPropertyDoesNotExist<br>// =&gt; Oops! This property does not exist.</pre><p><strong>you will not get</strong> undefined but the a custom response string.</p><p>It should be noted that <strong>for operations which do not have any traps defined, they are passed to the target normally as if the proxy did not exist.</strong></p><h4>Recreating on-change</h4><p>With the understanding of how proxies work, we are set to recreate the <em>on-change</em> library. As discussed above, onChange is a function that takes two parameters: the object to watch, and the function which will be executed on every change in the object. Let’s make a function, then —</p><pre>const onChange = (objToWatch, onChangeFunction) =&gt; { };</pre><p>It doesn’t do anything much right now.</p><p><strong>Let’s state the problem again:</strong> <em>We want to run </em><em>onChangeFunction whenever </em><em>objToWatch is changed, that is, either a property is accessed/retrieved, or a new property is added, or a property is deleted.</em></p><p>It seems clear that we are going to use proxies to intercept operations on the object. So let’s return a proxy in the onChange function with an empty handler. Since the handler does not specify any traps, all operations are transparently passed to the target object, that is, objToWatch.</p><pre>const onChange = (objToWatch, onChangeFunction) =&gt; { <br>  <strong>const handler = {};</strong></pre><pre><strong>  return new Proxy(objToWatch, handler);</strong><br>};</pre><p>Let’s focus on “<em>when a property is accessed/retrieved</em>” since we understood the get trap above. So, if in the get trap, we call the onChangeFunction, before returning the property’s value, we should be able to do achieve partly what <em>on-change</em> library does. Let’s code it and see —</p><pre>const onChange = (objToWatch, onChangeFunction) =&gt; { <br>  const handler = {<br><strong>    get(target, property, receiver) {<br>      onChangeFunction(); // </strong>Calling our function<br><strong>      return target[property];<br>    }</strong><br>  };</pre><pre>return new Proxy(objToWatch, handler);<br>};</pre><p>This seems about right. Let’s run it before proceeding further —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*T1AF_RUlFnrKG3r9WGz-2w.gif" /><figcaption>Yayy! It’s working! 🔥</figcaption></figure><p>So we have accomplished one part of the statement. Let’s now focus on when “<em>a new property is added, or a property is deleted”. </em>Since we’ve already laid the groundwork, we just need to add more traps to accomplish the remaining functionality. The trap for setting a property or modifying its value is set. Let’s add that in the handle —</p><pre>const onChange = (objToWatch, onChangeFunction) =&gt; { <br>  const handler = {<br>    get(target, property, receiver) {<br>      onChangeFunction();<br>      return <strong>Reflect.get(target, property, receiver);</strong><br>    },<br><strong>    set(target, property, value, receiver) {<br>      onChangeFunction();<br>      return Reflect.set(target, property, value);<br>    }</strong><br>  };</pre><pre>return new Proxy(objToWatch, handler);<br>};</pre><p>set receives 4 parameters: the extra one is the value that is being set. We are using Reflect because it gives us a programmatic way of manipulating an object. It’s not that different from obj.name = &#39;Arfat&#39; type of property setting. You can read <a href="https://github.com/tvcutsem/harmony-reflect/wiki">here</a> why it’s better to use Reflect API. You can read more about Reflect API <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect">here</a>.</p><p>Since we are using Reflect API, I’m going to replace target[property] with its equivalent Reflect function in the get trap as well.</p><p>In a similar way, if we want to intercept deletion of a property, we can do so by the deleteProperty trap. Let’s add that to the handler as well —</p><pre>const onChange = (objToWatch, onChangeFunction) =&gt; { <br>  const handler = {<br>    get(target, property, receiver) {<br>      onChangeFunction();<br>      return Reflect.get(target, property, receiver);<br>    },<br>    set(target, property, value) {<br>      onChangeFunction();<br>      return Reflect.set(target, property, value);<br>    },<br>   <strong> deleteProperty(target, property) {<br>      onChangeFunction();<br>      return Reflect.deleteProperty(target, property);<br>    }</strong><br>  };</pre><pre>return new Proxy(objToWatch, handler);<br>};</pre><p>Well done. If you now run this code —</p><pre>const logger = () =&gt; console.log(&#39;I was called&#39;);</pre><pre>const obj = { a: &#39;a&#39; };</pre><pre>const proxy = <strong>onChange(obj, logger);</strong></pre><pre>console.log(proxy.a); // logger called here in get trap<br>proxy.b = &#39;b&#39;; // logger called here as well in set trap<br>delete proxy.a; // logger called here in deleteProperty trap</pre><p>You are going to see I was called 3 times. That means, we’ve successfully re-created the <em>on-change</em> library.</p><p>There is one thing that we haven’t account for though. <strong>If you have nested objects in an array, they won’t trigger the logger function. </strong>For example, if the array is [1, 2, {a: false}] and you set array[2].a = true, the logger function will not be called.</p><p>It’s easy to rectify this bug. Instead of returning the value in the get trap, we will return another Proxy of the value <strong>if the value is an object </strong>so that the chain of proxies is never broken on objects.</p><p>Let’s add that logic to the get trap —</p><pre>get(target, property, receiver) {<br>  onChangeFunction();<br>  <strong>const value = Reflect.get(target, property, receiver);</strong><br><strong>  if (typeof value === &#39;object&#39;) {<br>    return new Proxy(value, handler);<br>  }<br>  return value;</strong><br>}</pre><p>Now, it will work even with nested objects inside arrays and objects.</p><h4>Final thoughts</h4><p>Some things that <em>on-change</em> does differently than our implementation are—</p><ul><li>It does not call onChangeFunction in the get trap.</li><li>Instead of set trap, <em>on-change </em>intercepts defineProperty trap.</li></ul><p>With the understanding of proxies, and knowledge of traps, these two would be a trivial addition/modifications. So, I’m leaving them for the reader to add themselves. You can read the source of <a href="https://github.com/sindresorhus/on-change">on-change</a> here, for reference.</p><p>One other issue that plagues <em>on-change</em> is this — if you have an array, and you do proxiedArray.sort() or any other function that heavily modifies the array, the logger function is going to be executed multiple times. For example, sorting the array [2,3,4,5,6,7,1] executes logger 12 times. This can be a desired functionality, or not. It depends on the developer.</p><p>There is another bug in the <em>on-change</em> library. If you read this <a href="https://github.com/sindresorhus/on-change/issues/9">issue</a>, you will notice that the get trap violates something called an “<strong>Invariant</strong>”. Invariants are constraint put on proxy objects by the Proxy API. These constraints dis-allow illegal operations on objects whose descriptors are set a certain way.</p><p>The issue lists a potential solution as well. You can read the references below to gain a deeper understanding of proxies and invariants. <strong>And if you have never contributed to open-source before, this could be a great beginning for you to make a pull request, correcting the behaviour. </strong>🙂</p><p>There are many other features and caveats of proxies. Read the references to understand them better.</p><h4>References —</h4><ul><li><a href="http://exploringjs.com/es6/ch_proxies.html">Exploring JS Proxies</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">MDN Proxy</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get#Invariants">get Invariants</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect">Reflect API</a></li></ul><p>You might also like some more articles that I wrote —</p><h4><a href="https://codeburst.io/top-javascript-vscode-extensions-for-faster-development-c687c39596f5">Top JavaScript VSCode Extensions for Faster Development</a></h4><p><a href="https://codeburst.io/top-javascript-vscode-extensions-for-faster-development-c687c39596f5">Top JavaScript VSCode Extensions for Faster Development 🔥</a></p><h4><a href="https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd">How to NOT React: Common Anti-Patterns and Gotchas in React</a></h4><p><a href="https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd">How to NOT React: Common Anti-Patterns and Gotchas in React</a></p><p><strong>I write about JavaScript, Web Development, and Computer Science. Follow me for weekly articles. Share this article if you like it.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f252eddf76c2" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/understanding-javascript-proxies-by-examining-on-change-library-f252eddf76c2">Understanding JavaScript Proxies by Examining on-change Library</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top JavaScript VSCode Extensions for Faster Development ]]></title>
            <link>https://codeburst.io/top-javascript-vscode-extensions-for-faster-development-c687c39596f5?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/c687c39596f5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Fri, 23 Mar 2018 17:19:30 GMT</pubDate>
            <atom:updated>2018-04-27T18:34:05.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaL3SxOBXbrwXrAciJyM3Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/l090uFWoPaI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Carlisle</a> on <a href="https://unsplash.com/search/photos/tools-?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://code.visualstudio.com/">VSCode</a> is an open-source, cross-platform editor that has become a favourite of programmers, particularly in the Web Development community. It’s fast, extensible, customisable, and has tons of features. You should check it out if you haven’t already done it.</p><p>Thousands of extensions have been made for VSCode. I am going to list a few extensions that I use on a day-to-day basis. <strong>Let’s begin</strong>!</p><h3>Quokka.js</h3><p><a href="https://quokkajs.com/">Quokka.js</a> is a rapid prototyping playground for JavaScript and TypeScript. What that <strong>means is that it runs your code immediately as you type</strong> and displays various execution results in your code editor. Try it yourself.</p><p>After installing this <a href="https://marketplace.visualstudio.com/items?itemName=WallabyJs.quokka-vscode">extension</a>, you can press <em>Ctrl/Cmd(⌘) + Shift + P</em> to display the editor’s command palette, and then type <em>Quokka</em> to see the list of the available commands. Select and run the <strong>New JavaScript File</strong> command. You can also press (⌘ + K + J) to open the file directly. Anything you type in this file is executed immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ukcsChGYEreBhhAksiYceA.gif" /><figcaption><a href="https://quokkajs.com/">Quokka.js</a></figcaption></figure><h4><strong>Similar Extensions </strong>—</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner">Code Runner</a> — Supports multiple languages such as <strong>C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6 and more.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=mattn.Runner">Runner</a></li></ul><h3>Bracket Pair Colorizer and Indent Rainbow 🔥🔥</h3><p>Brackets and parentheses are an inseparable part many programming languages. In a language such as JavaScript, <strong>a single page can have a barrage these characters with no easy mechanism to identify opening and closing pairs.</strong> Welcome <a href="https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer">Bracket Pair Colorizer</a> and <a href="https://marketplace.visualstudio.com/items?itemName=oderwat.indent-rainbow">Indent Rainbow</a>. These are two different extensions. However, they really make a good and beautiful couple. These extensions will fill your editor with a flurry of colours, and make the code blocks easily discernible and pleasing to the eyes. Once you get used to them, VSCode feels insipid, and bland without them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*tTp3nnHAfOJVRjc5mCa3fA.png" /><figcaption>Without Indent Rainbow and Bracket Pair Colouriser</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*fmd009UJSyiC3ZtsOgN3qA.png" /><figcaption>🔥🔥 With Indent Rainbow and Bracket Pair Colorizer 🔥🔥</figcaption></figure><h3>Snippets</h3><p>Snippets are shorthands in an editor. So instead of writing import React from &#39;react&#39;;, you can type imr and press Tab to expand this snippet. Similarly, clg becomes console.log.</p><p><strong>There exists a lot of snippets for all sorts of things:</strong> Javascript(or any other language), React, Redux, Angular, Vue, Jest. I personally find Javascript snippets really useful since I work mostly with JS.</p><h4>Some good snippet extensions are —</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets">JavaScript (ES6) code snippets</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=EQuimper.react-native-react-redux">React-Native/React/Redux snippets for es6/es7</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=TimonVS.ReactSnippetsStandard">React Standard Style code snippets</a></li></ul><h3>Todo Highlighter</h3><p>It often happens that you code a function, and think that there is a probably better way to do the same thing. You leave a comment // TODO: Needs Refactoring or something to that effect. But then you forget about the note and push your code to master/production. With <a href="https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight">Todo Highlighter</a>, that won’t happen. Hopefully.</p><p>It highlights your TODOs/FIXMEs or any other annotation in your code in bright colours so it is always clearly visible. One nifty feature is List Highlighted annotations. It lists all the TODOs in the output console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5s06_EuXWZIg281ajKN9g.png" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight">Todo Highlighter</a></figcaption></figure><h4>Similar Extensions —</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=fabiospampinato.vscode-todo-plus">Todo+</a> — More powerful that Todo Highlighter with a lot more features.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=minhthai.vscode-todo-parser">Todo Parser</a></li></ul><h3>Import Cost</h3><p>This <a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">extension</a> allows you to see the size of the imported module. It’s a huge help with bundlers such as Webpack. <strong>You can see whether you are importing the entire library or just a particular utility.</strong></p><p>One problem that exists is that it doesn’t show the cost of custom files or modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*LbfI4D9XXiZYS1Slwsys5g.gif" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">Import Cost</a></figcaption></figure><h3>REST Client</h3><p>As a web developer, we often need to work with REST APIs. For examining the URLs and checking the responses, tools like <a href="https://www.getpostman.com/apps">Postman</a> are used. But why have a different app when your editor can easily do the same task. Welcome <a href="https://marketplace.visualstudio.com/items?itemName=humao.rest-client">REST Client</a>. <strong>It allows you to send HTTP request and view the response in Visual Studio Code directly.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nsl7NFn1PPAcbJa4TApBhw.gif" /><figcaption>REST Client</figcaption></figure><h3>Auto Close Tag and Auto Rename Tag</h3><p>Since the advent of React and the traction it has gained in the last few years, HTML-like syntax in the form of JSX is all the rage now. We again have to code with <em>tags </em>JavaScript. Any web developer you would tell you that it is a pain to type the tags. In most cases, we need a tool that can quickly and easily generate tags and their children. <a href="https://emmet.io/">Emmet</a> is a really good example of this already built into VSCode. However, sometimes, you do just want something simple and concise. Such as an auto tag closer, which generates the closing pair of a tag as you type the opening pair. And when you change that same tag, the closing tag automatically gets changed. These two extensions do just that.</p><p><strong>It also works with JSX and many other languages such as XML, PHP, Vue, JavaScript, TypeScript, TSX.</strong></p><p>Get them here — <a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-close-tag">Auto Close Tag</a> and <a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag">Auto Rename Tag</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ME0oAmIJdO6zaaYwL1DPwA.gif" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag">Auto Rename Tag</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbGIozYQA3qS3nXpNtSDeg.gif" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-close-tag">Auto Close Tag</a></figcaption></figure><h4><strong>Similar Extensions</strong> —</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-complete-tag">Auto Complete Tag</a> — Combines the functionality of both Auto Rename and Auto Close Tag</li><li><a href="https://marketplace.visualstudio.com/items?itemName=Compulim.compulim-vscode-closetag">Close HTML/XML tag</a></li></ul><h3>GitLens</h3><p>As told by its author, GitLens supercharges the Git capabilities built into Visual Studio Code. <strong>It packs a surprising number of features such as code authorship shown via Code lens, commit search, history and GitLens explorer.</strong> You can read full explanations of these features <a href="https://github.com/eamodio/vscode-gitlens">here</a>. <strong>Suffice it to say that you should install this plugin if you do any work with git.</strong></p><p>There are other extensions that focus on a specific functionality. You can install those if GitLens feel bloated or you don’t use many of its features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*DS2aWPI70ydDx4WHkkiJVQ.gif" /></figure><h4>Similar Extensions —</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory">Git History</a> — Displays a beautiful graph of the commit history and much more. <strong>Recommend</strong>.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=waderyan.gitblame">Git Blame</a> — It lets you see Git Blame information in the status bar for the currently selected line. A similar feature is also provided by GitLens.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=lamartire.git-indicators">Git Indicators </a>— It lets you see the affected files and how many lines have been added or deleted in the status bar.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=ziyasal.vscode-open-in-github">Open in GitHub / Bitbucket / Gitlab / VisualStudio.com !</a> — It lets you open the repo in the browser with a single command.</li></ul><h3>Git Project Manager</h3><p>Git Project Manager (GPM) allows you to open a new window targeting a git repository directly from VSCode window. <strong>Basically, you can now open another repository without having to leave VSCode.</strong></p><p>After installing this <a href="https://marketplace.visualstudio.com/items?itemName=felipecaputo.git-project-manager">extension</a>, you will have to set gitProjectManager.baseProjectsFolders to the list of URLs which contain the repos.</p><h4>Example —</h4><pre>{<br>    &quot;gitProjectManager.baseProjectsFolders&quot;: [<br>        &quot;/home/user/nodeProjects&quot;,<br>        &quot;/home/user/personal/pocs&quot;<br>    ]<br>} </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*PvDRDxbdNKnnVhJ1HS4fjQ.gif" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=felipecaputo.git-project-manager">Git Project Manager</a></figcaption></figure><h4>Similar Extensions —</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager">Project Manager</a> — Haven’t personally used it, but it has a million+ installs. So definitely check it out.</li></ul><h3>Indenticator</h3><p>It visually highlights the current indent depth. So now you can easily distinguish between various blocks indented at different levels. Get it <a href="https://marketplace.visualstudio.com/items?itemName=SirTori.indenticator">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*ZY3eFPZ1-PmBhS5cQAZHAg.gif" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=SirTori.indenticator">Indenticator</a></figcaption></figure><h4>Similar Extensions</h4><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=spywhere.guides">Guides</a></li></ul><h3>VSCode Icons</h3><p>Icons to make your editor more appealing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*69vby7KoGBO5D6XDs2vdIg.gif" /><figcaption>VSCode Icons</figcaption></figure><p>Similar Extensions —</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=emmanuelbeziat.vscode-great-icons">VSCode Great Icons</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=jtlowe.vscode-icon-theme">Studio Icons</a></li></ul><h3>Dracula (Theme)</h3><p>One <a href="https://marketplace.visualstudio.com/items?itemName=dracula-theme.theme-dracula">theme</a> that I like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXgT4EFpAKtPfXTgi00BqA.png" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=dracula-theme.theme-dracula">Dracula</a> theme</figcaption></figure><h3>Other Recommendations —</h3><ul><li><a href="https://github.com/tonsky/FiraCode">Fira Code </a>— A monospaced font with programming ligatures. <strong>Thanks to </strong><a href="https://medium.com/u/b678fbba4494"><strong>Rea Deimos</strong></a><strong>.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server </a>— A development local Server with live reload feature for static &amp; dynamic pages. <strong>Thanks to </strong><a href="https://medium.com/u/cde4f198c1b5"><strong>Dani Vijay</strong></a><strong>.</strong></li><li><a href="https://github.com/prettier/prettier-vscode">Prettier for VSCode</a> — An opinionated Code Formatter. <strong>Thanks to </strong><a href="https://medium.com/u/fee38a283777"><strong>Daniyal</strong></a><strong>.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync">Settings Sync </a>— Allows you to save user settings, extensions and keybindings in a Gist so you can setup a new VSCode in minutes. <strong>Thanks to </strong><a href="https://medium.com/u/3e0b91076568"><strong>Albert ByVerdu</strong></a><strong>.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=slevesque.vscode-multiclip">Multiple clipboards for VSCode</a> — Override the regular Copy and Cut commands to keep selections in a clipboard ring. Also adds the ability to copy several blocks of text into a single copy buffer. <strong>Thanks to </strong><a href="https://medium.com/u/3de1049f5409"><strong>PRATEEK PATEL</strong></a><strong>.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense">Path Intellisense</a> — Visual Studio Code plugin that autocompletes filenames. <strong>Thanks to </strong><a href="https://medium.com/u/48c8a29c4b2"><strong>Jess Hines</strong></a><strong>.</strong></li><li><a href="https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens">Version Lens</a> — Shows package version information for npm, jspm, bower, dub and dotnet core in the Visual Studio Code editor. <strong>Thanks to </strong><a href="https://medium.com/u/9765933df3ee"><strong>Brian Kidd</strong></a><strong>.</strong></li></ul><p>These were some of the VSCode extensions that I use regularly. What other <strong>extensions and themes</strong> do you like? Respond to this article and mention them. 😀</p><p>If you are using in React, you should see these anti-patterns that are unintuitive and hard to understand.</p><p><a href="https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd">How to NOT React: Common Anti-Patterns and Gotchas in React</a></p><p><a href="https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd">How to NOT React: Common Anti-Patterns and Gotchas in React</a></p><p><strong>I write about JavaScript, Web Development, and Computer Science. Follow me for weekly articles. Share this article if you like it.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c687c39596f5" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/top-javascript-vscode-extensions-for-faster-development-c687c39596f5">Top JavaScript VSCode Extensions for Faster Development 🔥</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to NOT React: Common Anti-Patterns and Gotchas in React]]></title>
            <link>https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/40141fe0dcd</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 14:32:17 GMT</pubDate>
            <atom:updated>2018-03-26T07:50:57.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00F8QCjUhHAXqhnorGZSOg.jpeg" /><figcaption>We go so that we can tell others about it! Photo by <a href="https://unsplash.com/photos/-Cmz06-0btw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NeONBRAND</a> on <a href="https://unsplash.com/search/photos/caution?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>What is an anti-pattern? Anti-patterns are certain patterns in software development that are considered bad programming practices. The same pattern may have been considered correct at one point in the past, but now developers have realised that they cause more pain and hard-to-track bugs in long term.</p><p>React has matured as an UI library and with that a lot of best development practices have evolved over the years. We are going to learn from the collective wisdom of thousands of programmers and developers who learnt those things the hard way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*kD905dFJGIzg7DCjKIqwMw.gif" /><figcaption>Truly said!</figcaption></figure><p>Let’s begin!</p><h3>1. bind() and arrow functions in Components</h3><p>You must have bound your custom functions in the constructor function before using them as props for components. If you declare components using the extends keyword, then the custom functions (such as updateValue below) lose their this bindings. So, if you want to access this.state, or this.props or this.setState then you need to re-bind them.</p><h4>Demo</h4><pre>class app extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      name: &#39;&#39;<br>    };<br>   <strong> this.updateValue = this.updateValue.bind(this);</strong><br>  }</pre><pre>updateValue(evt) {<br>    this.setState({<br>      name: evt.target.value<br>    });<br>  }</pre><pre>render() {<br>    return (<br>      &lt;form&gt;<br>        &lt;input <strong>onChange={this.updateValue}</strong> value={this.state.name} /&gt;    <br>      &lt;/form&gt;<br>    )<br>  }<br>}</pre><h4>Problems</h4><p>There are two ways to bind the custom functions to the component’s this. One way is to bind them in the constructor as done above. The other way is to bind at the time of passing as prop value —</p><pre>&lt;input onChange={<strong>this.updateValue.bind(this)</strong>} value={this.state.name} /&gt;</pre><p>This method suffers from a problem. Since .bind() creates a <strong>new </strong>function each time it is run, <strong>this method would lead to a new function being created every time the </strong>render<strong> function executes.</strong> This has some performance implications. However, in a small app it may not be noticeable. As the app grows large, the difference will start to materialise. One case study is <a href="https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f">here</a>.</p><p>Arrow functions entails the same performance concerns that were there with bind.</p><pre>&lt;input onChange={ <strong>(evt) =&gt; this.setState({ name: evt.target.value })</strong> } value={this.state.name} /&gt;</pre><p>This way of writing is definitely clearer. You can see what’s going on in the onChange prop itself. But, this also creates new anonymous function every time input renders. So it has the same performance penalty as above.</p><p><strong>Edit</strong> — I came across this <a href="https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578">article</a> thanks to <a href="https://medium.com/u/5d41e3a654b7">Rob Wise</a>. Turns out, there hasn’t been any performance measurements as to how slow inline functions are. <strong>Also, most of the time, they are equally performant.</strong> Check out the <a href="https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578">article</a> for a more in-depth discussion on this.</p><h4>Solutions</h4><p>The best way to avoid the above performance penalty is to bind the functions in the constructor itself. This way only one extra function is created at the time of component creation, and that function is used even when render is executed again.</p><p>It often happens that you forget to bind your functions in the constructor, and then you get an error (<em>Cannot find X on undefined.</em>). Babel has a plugin that let’s you write auto-bound function using the fat-arrow syntax. The plugin is <a href="https://babeljs.io/docs/plugins/transform-class-properties/"><em>Class properties transform</em></a><em>. </em>Now you can write components like this —</p><pre>class App extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      name: &#39;&#39;<br>    };</pre><pre><strong>// Look ma! No functions to bind!</strong></pre><pre>}</pre><pre><strong>updateValue = (evt) =&gt; {<br>    this.setState({<br>      name: evt.target.value<br>    });<br>  }</strong></pre><pre>render() {<br>    return (<br>      &lt;form&gt;<br>        &lt;input onChange={this.updateValue} value={this.state.name} /&gt;<br>      &lt;/form&gt;<br>    )<br>  }<br>}</pre><h4>Read More —</h4><ul><li><a href="https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56">React Binding Patterns: 5 Approaches for Handling `this`</a></li><li><a href="https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f">React.js pure render performance anti-pattern</a></li><li><a href="https://medium.com/shoutem/react-to-bind-or-not-to-bind-7bf58327e22a">React — to Bind or Not to Bind</a></li><li><a href="http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/">Why and how to bind methods in your React component classes?</a></li></ul><h3>2. Using indexes in key Prop</h3><p>Key is an essential prop when you iterate over a collection of elements. Keys should be stable, predictable, and unique so that React can keep track of elements. Keys are used to help React easily reconcile(read: update) the differences between the virtual DOM and the real DOM. However, using certain set of values such as array <em>indexes </em><strong>may break your application or render wrong data</strong>.</p><h4>Demo</h4><pre>{elements.map((element, index) =&gt;<br>    &lt;Display<br>       {...element}<br>       key={index}<br>       /&gt;<br>   )<br>}</pre><h4>Problems</h4><p>When children have keys, React uses the key to match children in the original tree with children in the subsequent tree.<strong> The keys are used for identification.</strong> If two elements have same keys, React considers them same. When the keys collide, that is, more than 2 elements have the same keys, React shows a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3C-F1fs7E5fK9R8XlLk62g.png" /><figcaption>Warning for duplicate keys</figcaption></figure><p><a href="https://reactjs.org/redirect-to-codepen/reconciliation/index-used-as-key">Here</a> is an example of the issues that can be caused by using indexes as keys on CodePen.</p><h4>Solutions</h4><p>Any key that you are going to use should be —</p><ul><li><strong>Unique</strong> — The key of an element should be unique among its siblings. It is not necessary to have globally unique keys.</li><li><strong>Stable</strong> — The key for the same element should not change with time, or page refresh, or re-ordering of elements.</li><li><strong>Predictable</strong> — You can always get the same key again if you want. That is, the key should not be generated randomly.</li></ul><p>Array indexes are unique, and predictable. However, they are not stable. In the same vein, <strong>random numbers or timestamps should not be used as keys.</strong></p><p>Using random number is equivalent to not using keys at all since random numbers are not unique or stable. The components <strong>will</strong> be re-rendered every time even if the content inside the element has not changed.</p><p>Timestamps are unique but not stable or predictable. <strong>They are also always increasing.</strong> So on every page refresh, you are going to get new timestamps.</p><p>In general, you should rely on the ID generated by databases such as primary key in Relational databases, and Object IDs in Mongo. If a database ID is not available, you can generate a hash of the content and use that as a key. You can read about more about hashes <a href="https://en.wikipedia.org/wiki/Hash_function">here</a>.</p><h4>Read More —</h4><ul><li><a href="https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318">Index as a key is an anti-pattern</a></li><li><a href="https://paulgray.net/keys-in-react/">Why you need keys for collections in React.</a></li><li><a href="https://github.com/facebook/react/issues/1342#issuecomment-39230939">On why you shouldn’t use Random values as keys</a>.</li></ul><h3>3. setState() is async</h3><p>React components essentially comprises 3 things: state ,props and markup (or other components). Props are immutable. However, the state is mutable. Changing the state causes the component to re-render. If the state is managed internally by the component, this.setState function is employed to update the state. There are a few important things to note about this function. Let’s look —</p><h4>Demo</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d37a889b095e8bcc42261e42a83ecdc9/href">https://medium.com/media/d37a889b095e8bcc42261e42a83ecdc9/href</a></iframe><h4>Problems</h4><p>Focus on line 11. If you mutate the state <em>directly, </em>the component will <strong>not </strong>be re-rendered and the changes will not be reflected. This is because the state is compared <a href="https://stackoverflow.com/questions/36084515/how-does-shallow-compare-work-in-react">shallowly</a>. You should always use setState for changing the value of the state.</p><p>Now, in setState if you use the value of current state to update to the next state (as done in line 15), React <strong>may or may not</strong> <strong>re-render</strong>. This is because, state and props are updated asynchronously. That is, the DOM is not updated as soon as setState is invoked. Rather, React batches multiple updates into one update and then renders the DOM. You may receive outdated values while querying the state object. The <a href="https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous">docs</a> also mention this —</p><blockquote>Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.</blockquote><p>Another problem is when you have multiple setState calls in a single function, as shown above on line 16 and 20. Initial value of the counter is 350. Assume the value of this.props.increment is 10. You might think that after the first setState invocation on line 16, the counter’s value will change to 350+10 = <strong>360. </strong>And, when the next setState is called on line 20, the counter’s value will change to 360+10 = <strong>370</strong>. However, this does not happen. The second call still sees the value of counter as 350. <strong>This is because setState is async</strong>. The counter’s value does not change until the next update cycle. The execution of setState is waiting in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">event loop</a> and until updateCounter finishes execution, setState won’t run and hence won’t update the state.</p><h4>Solution</h4><p>You should use the other form of setState as done on line 27 and 31. In this form, you can pass a function to setState which receives <em>currentState</em> and <em>currentProps</em> as arguments. The return value of this function is merged in with the existing state to form the new state.</p><h4>Read More —</h4><ul><li>A wonderful <a href="https://github.com/facebook/react/issues/11527">explanation</a> of why setState is async by <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a>.</li><li><a href="https://medium.com/@wisecobbler/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1">Using a function in `setState` instead of an object</a></li><li><a href="https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3">Beware: React setState is asynchronous!</a></li></ul><h3>4. Props in Initial State</h3><p>The React docs mention this anti-pattern as —</p><blockquote><em>Using props to generate state in </em>getInitialState<em> often leads to duplication of “source of truth”, i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.</em></blockquote><h4>Demo</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487b9b3016ae70f01fa306504e82621c/href">https://medium.com/media/487b9b3016ae70f01fa306504e82621c/href</a></iframe><h4>Problems</h4><p>The constructor or (getInitialState) is called <strong>only at the time of component creation</strong>. That is, constructor is invoked only once. Hence, when you change the props next time, the state won’t be updated and will retain its previous value.</p><p>Young developers often assume that the props values will be in sync with the state, and as props change, the state will reflect those values. However, that is not true.</p><h4>Solutions</h4><p>You can use this pattern if you want a specific behaviour. That is,<strong> you want the state to be <em>seeded </em>by the values of props only once</strong>. The state will be managed internally by the component.</p><p>In other cases, you can use componentWillReceiveProps lifecycle method to keep the state and props in sync, as shown here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca3353c37761e69a5cc9b5738b9d6695/href">https://medium.com/media/ca3353c37761e69a5cc9b5738b9d6695/href</a></iframe><p>Beware that using componentWillReceiveProps has it own caveats. You can read about it the <a href="https://reactjs.org/docs/react-component.html#componentwillreceiveprops">Docs</a>.</p><p>The best approach would be to use a state management library such as Redux to <a href="https://github.com/reactjs/react-redux"><em>connect</em></a> the state and the component.</p><h4>Read More —</h4><ul><li><a href="https://github.com/vasanthk/react-bits/blob/master/anti-patterns/01.props-in-initial-state.md">Props in Initial State</a></li></ul><h3>5. Components Name</h3><p>In React, if you are rendering your component using JSX, the name of that component has to begin with a capital letter.</p><h4>Demo</h4><pre>&lt;MyComponent&gt;<br>    &lt;app /&gt; // Will not work :(<br>&lt;/MyComponent&gt;</pre><pre>&lt;MyComponent&gt;<br>    &lt;App /&gt; // Will work!<br>&lt;/MyComponent&gt;</pre><h4>Problems</h4><p>If you create a component app and render it using JSX as &lt;app label=&quot;Save&quot; /&gt;, React will throw an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCB4cI255tVV41NvIozL7g.png" /><figcaption>Warning when using non-capitalised custom components.</figcaption></figure><p>The error says that &lt;app&gt; is not recognised. Only HTML elements and SVG tags can begin with a lowercase. Hence, &lt;div /&gt; is okay but &lt;app&gt; is not.</p><h4>Solution</h4><p>You need to make sure that while using custom component in JSX, it should begin with a capital letter.</p><p>But, also understand that declaring components does not adhere to this rule. Hence, you can do this —</p><pre>// Here lowercase is fine.<br>class <strong>primaryButton</strong> extends Component {<br>  render() {<br>    return &lt;div /&gt;;<br>  }<br>}</pre><pre>export default <strong>primaryButton</strong>;</pre><pre>// In a different file, import the button. However, make sure to give a name starting with capital letter.</pre><pre>import <strong>PrimaryButton</strong> from &#39;primaryButton&#39;;</pre><pre>&lt;<strong>PrimaryButton</strong> /&gt;</pre><h4>Read More —</h4><ul><li><a href="https://daveceddia.com/react-gotchas/">React Gotchas</a></li></ul><p>These were some unintuitive hard-to-understand bug-makers in React. If you know about any other anti-pattern, respond to this article. 😀</p><p>I have also written <a href="https://codeburst.io/top-react-and-redux-packages-for-faster-development-5fa0ace42fe7">Top React and Redux Packages for Faster Development</a></p><p><a href="https://codeburst.io/top-react-and-redux-packages-for-faster-development-5fa0ace42fe7">Top React and Redux Packages for Faster Development</a></p><p>If you are still learning how to setup a React Project, this <a href="https://codeburst.io/yet-another-beginners-guide-to-setting-up-a-react-project-part-1-bdc8a29aea22">two-part series</a> might be helpful in understanding various aspects of React build system.</p><ul><li><a href="https://codeburst.io/yet-another-beginners-guide-to-setting-up-a-react-project-part-1-bdc8a29aea22">Yet another Beginner’s Guide to setting up a React Project — Part 1</a></li><li><a href="https://codeburst.io/yet-another-beginners-guide-to-setting-up-a-react-project-part-2-5d3151814333">Yet another Beginner’s Guide to setting up a React Project — Part 2</a></li></ul><p><strong>I write about JavaScript, web development, and Computer Science. Follow me for weekly articles. Share this article if you like it.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40141fe0dcd" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd">How to NOT React: Common Anti-Patterns and Gotchas in React</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top React and Redux Packages for Faster Development]]></title>
            <link>https://codeburst.io/top-react-and-redux-packages-for-faster-development-5fa0ace42fe7?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fa0ace42fe7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 28 Feb 2018 06:01:58 GMT</pubDate>
            <atom:updated>2018-02-28T06:18:22.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOfFxGkE0FP-eQ30xoYxlQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/dQf7RZhMOJU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fleur Treurniet</a> on <a href="https://unsplash.com/search/photos/tools?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>React has grown in popularity over the last few years. With that, a lot of tools have emerged that make developer’s life easy and development fun. They are going to help us in achieving the extra productivity that we want. After all, we always want our development tools to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lUkZYUKtkykpHNIOz3c0gg.gif" /><figcaption>Via <a href="https://gph.is/1VO6H7f">Giphy</a></figcaption></figure><p>If you are a beginner in React, you may find some of the packages helpful in debugging or visualising various abstract parts of your app.</p><p>Let’s begin!</p><h3>React Storybook</h3><p>While creating applications in React, you must have had this thought at least once: <em>What if I could see a rendition of the component that I am using(or making) and see how it behaves under different combinations of props, states, and actions.</em> Well, there is a package for this. It’s called Storybook.</p><p>React storybook is a visual development environment for React. <strong>It allows you to browse a component library, view the different states of each component, and interactively develop and test components.</strong> It allows you to quickly prototype components and see changes on every state and prop changes. Here’s a link to their GitHub’s <a href="https://github.com/storybooks/storybook">repo</a>.</p><p>You should definitely check out their <a href="https://storybook.js.org/examples/">examples</a> page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxuoKupMwNqsEKyrCdB9cQ.gif" /><figcaption>Demo from <a href="https://github.com/storybooks/storybook">storybook’s</a> repo</figcaption></figure><p><strong>Some highlights are —</strong></p><ul><li>Storybook runs outside of your app.</li><li>This allows the components to be developed in isolation from the app development.</li><li>It also means that you do not have to worry about various dependencies while creating the components.</li></ul><p>Other similar packages are: <a href="https://github.com/react-cosmos/react-cosmos">React Cosmos</a>, <a href="https://github.com/styleguidist/react-styleguidist">React Styleguidist</a></p><h3>React Dev Tools</h3><p>This is the most famous React development package. <strong>It lets you inspect the React component elements and their hierarchy like HTML elements, including component props and state.</strong> Also, you can search for a particular components using regular expressions, and see how it affects the rendering of other components using a nifty feature called ‘<strong>Highlight Updates</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*9XrmfPqh_naIBlTi7dv3Hw.gif" /><figcaption>React DevTools demo</figcaption></figure><p>It is available as an <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">extension</a> of Google Chrome, and as an <a href="https://addons.mozilla.org/firefox/addon/react-devtools/">add-on</a> for Firefox. It is available as an standalone <a href="https://github.com/facebook/react-devtools/tree/master/packages/react-devtools">app</a> too. Installing it is as simple as downloading the extension(or addon). Once installed, there should be a new tab called ‘React’ in Developers Tools(in Chrome).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*3qBkNUef0uvzZvI_U8ZhLA.gif" /><figcaption>Highlight Updates of React Dev Tools</figcaption></figure><p><strong>Tips —</strong></p><ul><li><strong>Highlight Updates:</strong> Focus on the colourful lines that are appearing at the bottom of <strong>Submit</strong> button in the above-mentioned gif. When I type in the input box, <strong>the whole component is being re-rendered!</strong></li><li>If causing an action in one place highlight many others, isolated components, it is a cause for concern.</li><li>In most cases, the component is too large and should be refactored into smaller, modular components.</li><li>You can also see the current props and state (email and password) of the component at the right bottom corner. It is a really cool way to see the effect of state changes across the app.</li></ul><h3>Why did you update?</h3><p>We spoke about unnecessary rendering in the last segment. It’s not always easy to visually gauge which components are re-rendering needlessly. Thankfully, there is a package for that. It <strong>notifies you in the console when potentially unnecessary re-renders occur.</strong> It keeps track of the props and states, and when a component is re-rendered without any change in the props or the state, the package logs the details in the console. Make sure to not use this in production. Check it out <a href="https://github.com/maicki/why-did-you-update">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CL5jum98a0QxOWeIb9QRBg.png" /><figcaption>Image from <a href="https://github.com/maicki/why-did-you-update">Why did you update</a>’s repo</figcaption></figure><h3>Create React App(CRA)</h3><p>Not exactly a development tool, but over the years I have found that this package is really helpful in creating rapid prototypes. Setting up a working React project is really hard. Understand various parts of its structure like Babel and webpack is even harder for a beginner. I wrote a two-part series just to explain that. It’s <strong>Yet another Beginner’s Guide to setting up a React Project </strong>— <a href="https://codeburst.io/yet-another-beginners-guide-to-setting-up-a-react-project-part-1-bdc8a29aea22">Part 1</a> and <a href="https://codeburst.io/yet-another-beginners-guide-to-setting-up-a-react-project-part-2-5d3151814333">Part 2</a>. I explained the need of JSX, Babel and webpack.</p><p>Once you understand the basics, you’ll need to repeat the same set of steps every time you create a new project. And, you <strong><em>will</em></strong> need to create multiple project. Hence, to save developer’s time, Facebook created a package that encapsulates the complexity. Try it <a href="https://github.com/facebook/create-react-app">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*O1N_DRWt0EKJ-uzBTNE-tg.png" /><figcaption>A successful execution of create-react-app</figcaption></figure><p>There’s a high chance that you are using <a href="https://redux.js.org/">Redux</a> for state management in your React app. Here are some Redux specific tools —</p><h3>Redux Dev Tools</h3><p>Like React Dev Tools, but for redux. It is also available as a Chrome <a href="https://github.com/zalmoxisus/redux-devtools-extension">Extension</a>, and Firefox <a href="https://github.com/zalmoxisus/redux-devtools-extension">addon</a>. Its features are —</p><ul><li>It lets you inspect every state and action payload</li><li>It lets you go back in time by “cancelling” actions. It is also called <strong>Time Travel Debugging. </strong>There is a great video on this by the creator Redux Dev Tools himself, <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a>. Watch it <a href="http://youtube.com/watch?v=xsSnOQynTHs">here</a>.</li><li>If you change the reducer code, each “staged” action will be re-evaluated</li><li>If the reducers throw, you will see during which action this happened, and what the error was.</li><li>The dev tools logging UI (called LogMonitor) can be customised according to your needs. It’s a just another React Component. So it is not that difficult to customise it. Here’s a challenge by <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a> urging you to <a href="https://github.com/gaearon/redux-devtools/issues/3">create</a> your own LogMonitor.</li></ul><p>Some other monitors are: <a href="https://github.com/whetstone/redux-devtools-diff-monitor">Diff Monitor</a>, <a href="https://github.com/alexkuz/redux-devtools-inspector">Inspector</a>, <a href="https://github.com/bvaughn/redux-devtools-filterable-log-monitor/">Filterable Log Monitor</a>, <a href="https://github.com/romseguy/redux-devtools-chart-monitor">Chart Monitor</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*lAp8ZAk5uNFTuxjhx4GTdw.gif" /></figure><h3>redux-immutable-state-invariant</h3><p>Due to constraints put by functional programming style and the way redux behaves, <a href="https://redux.js.org/troubleshooting#never-mutate-reducer-arguments">we are never supposed to mutate state</a>. <strong>However, it is not readily clear when we are mutating the state and when we are <em>replacing</em> the existing state by a new one.</strong></p><p>This redux middleware will ensure that you inadvertently never do that. When the state is mutated, it will throw an error. Check it <a href="https://github.com/leoasis/redux-immutable-state-invariant">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOB0xSGDesQrkgAmMawR-Q.png" /><figcaption>Error when the state is mutated</figcaption></figure><p><strong>Tips—</strong></p><ul><li>Make sure that the state does not contain non-serialisable values such as functions. Otherwise, it will throw RangeError: Maximum call stack size exceeded.</li><li>Make sure to <strong>not</strong> use this package in production as the package involves lot of object copying and is really inefficient.</li></ul><h3>redux-diff-logger</h3><p>Chances are that you console.log the state whenever you need to examine it. Or better yet, you use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger">debugger</a> statement and use dev tools to debug the state. In both cases, you need to see the <strong><em>changed values</em></strong> between the previous state and the current state. Redux diff logger does exactly that. <strong>It logs the values that have changed between the states.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*dwqA2l5S7nKPjY8cOoL1rA.png" /><figcaption>Image from <a href="https://github.com/evgenyrodionov/redux-diff-logger">redux-diff-logger</a>’s repo</figcaption></figure><p>What if you need to see the entire state and not just the changed values? Well, you are in luck: <strong>Here’s another logger tool by the same author</strong>: <a href="https://github.com/evgenyrodionov/redux-logger">redux-logger</a>.</p><p>I have also written about <a href="https://codeburst.io/top-webpack-plugins-for-faster-development-a2f6accb7a3e">Top Webpack Plugins for faster development</a>. It lists webpack plugins that simplify our life.</p><p><a href="https://codeburst.io/top-webpack-plugins-for-faster-development-a2f6accb7a3e">Top Webpack plugins for faster development</a></p><p><em>We are always looking for talented, curious people to </em><a href="https://goo.gl/gePhPg"><em>join the team</em></a><em>.</em></p><p><strong>I write about JavaScript, web development, and Computer Science. Follow me for weekly articles.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fa0ace42fe7" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/top-react-and-redux-packages-for-faster-development-5fa0ace42fe7">Top React and Redux Packages for Faster Development</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why should you care about Progressive Web Apps (PWAs)?]]></title>
            <link>https://codeburst.io/why-should-you-care-about-progressive-web-apps-pwas-3c3f73cb8c92?source=rss-74153188d515------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c3f73cb8c92</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[application-development]]></category>
            <dc:creator><![CDATA[Arfat Salman]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 14:05:25 GMT</pubDate>
            <atom:updated>2018-02-21T14:05:25.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8OiLAXoENK7Yi1-2yeQig.png" /><figcaption>The unofficially official logo by <a href="https://medium.com/samsung-internet-dev/we-now-have-a-community-approved-progressive-web-apps-logo-823f212f57c9">the community.</a></figcaption></figure><p>This article summarises the things that I have learnt in Udacity’s <strong>Mobile Web Specialist</strong> Course. It is offered by Udacity in collaboration with Google. It’s an awesome course. You should definitely check out Udacity (<a href="https://goo.gl/nvzoPG">here</a>).</p><p>The world has become a global village. The average internet speed has gone up significantly. The average number of internet users in the world have steadily risen, and the number of cat videos have increased in proportion. The world is becoming increasingly reliant on the internet. The web has grown to a point where it has 5 billion devices connected to it. <strong>Yet</strong>, the thing that is most feared in this age of interconnectedness is the <strong>downasaur!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*cADHu-B7U67wS7wY9lx0oA.jpeg" /><figcaption>The dreaded Downasaur</figcaption></figure><p>Developers strive to never show the downasaur, even in uncertain network conditions. This <em>reliability</em> is a cornerstone of <strong>offline-first approach</strong>. But you may ask: why do we even need to worry about the network or connectivity when on average the world is getting more connected, with speedier network connectivity?</p><p><strong>Here’s why</strong>: When a user clicks on a link on a web page, the browser creates a request packet. This packet passes through multiple layers of TCP/IP on the client’s machine before it is sent to the Wi-Fi router. The router appends its own headers in the packet. The packet is then put on transmission cable that may be thousands of miles long, going to the other side of the globe. Along the way, the packet passes though multitude of routers, gateways, ISPs, and computers before reaching the server. The server makes an appropriate response based on the request, and <strong>the full journey repeats again in reverse</strong>.</p><p>That was a (very) short description of a really long journey!</p><p>Between the request and the response, a lot can fail. If a component is slow in this chain, it slows down the whole network. The response from the server may fail to come, or worse, do not come in time due to poor connectivity. <a href="https://developers.google.com/web/progressive-web-apps/"><strong>53% of users will abandon a site if it takes longer than 3 seconds to load! </strong></a>Google calls this type of connections <a href="https://developers.google.com/web/fundamentals/performance/poor-connectivity/"><strong>Lie-Fi</strong></a>. The reasons for Lie-fi are(but not limited to):</p><ul><li>Poor Signal</li><li>Misconfigured Proxy</li><li>Faults in the mobile network</li><li>Busy network</li><li>Server being DDoSed</li><li>Bugs in the server</li><li>Moon’s Gravitational Pull</li></ul><p><em>Well, the last point is debatable.</em></p><p>This means that we want to adopt a development paradigm that is offline-first as opposed to online-first.</p><h4>What are online and offline-first?</h4><p>Simply put, if a web app is making a network request <strong>and</strong> <strong><em>when</em> the request fails</strong>, the app shows:</p><ul><li>Cached data</li><li>Fancy error page</li><li>A sad cat video</li></ul><p>then it is online-first. Keep in mind that the web app is waiting for the network to succeed <strong><em>or</em></strong> fail first before showing any content.</p><p>In direct contrast, an offline-first approach shows <strong><em>something</em></strong> on the screen before waiting for the network to succeed or fail. A few examples to illustrate the point are —</p><ul><li>Deliver the page’s <strong>header and content</strong> from a cache on the device and then attempt to fetch <strong>updated content</strong> from the network.</li><li>Deliver the page’s <strong>header</strong> from the cache, and then attempt to fetch <strong>content</strong> from the network.</li></ul><p>It is evident from the preceding examples that the device’s or browser’s cache is going to play a big role in offline-first techniques.</p><h4>What are Progressive Web Apps(PWAs)?</h4><p>The web is one of the biggest platforms on the internet. It is bigger than any other operating system or form-factor. The web has higher (as much as 3X) reach than mobile apps. This is due to the fact that it is much easier to navigate to a new website than an application since a new application requires downloading and installation first. However, the engagement is much more on mobile applications because it becomes tedious to type URLs again and again when you can just touch an icon on your home screen and start to engage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XOOERNA79-16Vc7RvQSdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kQcjo835opCTCwRRNFbZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSNurJ0kP9sQ9FDD8f8NIg.png" /><figcaption>Data from Google’s <a href="https://www.youtube.com/watch?v=m-sCdS0sQO8">Progressive Web Apps: Great Experiences Everywhere</a></figcaption></figure><p>What if you could give users deep, engaging experiences of a mobile application while having the reach of a website? In the process, you also remove tedious steps such as installations via an app store? What if users lands on your website and they get a native-app like experience along with all the perks of a real app such as Push Notifications, Splash Screens, and <strong>the capability to work offline</strong>.</p><p>This new breed of web applications is known as <strong>Progressive Web Applications(PWAs)</strong>. Here’s the <a href="https://infrequently.org/2015/06/progressive-apps-escaping-tabs-without-losing-our-soul/">definition from Alex Russell</a>, who came up with the concept along with Frances Berriman. PWAs are:</p><blockquote>Responsive, connectivity-independent, app-like, fresh, safe, discoverable, re-engageable, installable, linkable web experiences.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*3hkWdjbFIpxl55C5JET_dA.png" /><figcaption>There is a XKCD for every situation.</figcaption></figure><p><strong>You might think</strong>: Why not just let the user use a browser and let them see the website like they always did? Well, this is where the offline-first approach kicks in. If the users’ network connection is lost, they are going to see the dreaded downasaur. If the user is on Lie-Fi, they are going to see a white screen of nothingness for a long time before the actual content appears. This is going to frustrate and agonise most users and is not the best user experience.</p><p>The key concepts of PWAs are —</p><ul><li><strong>Reliable</strong> — Reliability ensures that the user never sees the downasaur irrespective of their network connection’s strength. This is usually achieved by using Service Workers in JavaScript. Service Workers are a relatively new browser feature that makes PWAs possible. They are scripts that the browser runs in the background, separate from the rest of the website.</li><li><strong>Fast</strong> — Respond quickly to user interactions with silky smooth animations and no jittery scrolling.</li><li><strong>Engaging</strong> — Feel like a natural app on the device, with an immersive user experience. This means that the PWAs should utilise the full set of features such as Full Screen launches and Push Notifications.</li></ul><h4>Should your new app be a PWA?</h4><p>The PWAs are an evolving technology. Currently not all browsers support it, but that is changing rapidly. Chrome, Opera and Firefox are already on it. Support in Microsoft Edge is in development, and Safari has yet to catch the drift. Support for PWAs are also available in Webpack in <a href="https://github.com/NekR/offline-plugin">forms</a> of <a href="https://github.com/arthurbergmz/webpack-pwa-manifest">plugins</a>. Parcel (after 1.6.0) <a href="https://medium.com/@devongovett/parcel-v1-6-0-46f4a2514668">supports</a> PWAs too.</p><p>If you want to get your hands dirty now, you can do so <a href="https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/">here</a>.</p><p>All in all, it is definitely one of the most exciting technologies to emerge in recent times in Web Development. The future of PWAs looks bright. Do you feel the same?</p><p>Sources —</p><ul><li><a href="https://developers.google.com/web/progressive-web-apps/">Progressive Web Apps</a></li><li><a href="https://medium.com/samsung-internet-dev/6-myths-of-progressive-web-apps-81e28ca9d2b1">6 myths of Progressive Web Apps</a></li><li><a href="https://in.udacity.com/course/mobile-web-specialist-nanodegree--nd024">Mobile Web Specialist Course</a> @ Udacity.</li></ul><p><strong>I write about JavaScript, web development, and Computer Science. Follow me for weekly articles.</strong></p><p><strong>Reach out to me on @ </strong><a href="https://www.facebook.com/arfat.salman"><strong>Facebook</strong></a><strong> @ </strong><a href="https://www.linkedin.com/in/arfatsalman/"><strong>Linkedin</strong></a><strong> @ </strong><a href="https://twitter.com/salman_arfat"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c3f73cb8c92" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/why-should-you-care-about-progressive-web-apps-pwas-3c3f73cb8c92">Why should you care about Progressive Web Apps (PWAs)?</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>