<?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 Bunlong on Medium]]></title>
        <description><![CDATA[Stories by Bunlong on Medium]]></description>
        <link>https://medium.com/@bunlong?source=rss-66a7e388cf4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1U2j_Z9AodMTK3t5W8t6ag.png</url>
            <title>Stories by Bunlong on Medium</title>
            <link>https://medium.com/@bunlong?source=rss-66a7e388cf4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:09:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bunlong/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[How to find a point a given distance from another point along a line?]]></title>
            <link>https://medium.com/@bunlong/how-to-find-a-point-a-given-distance-from-another-point-along-a-line-e0cd41b26610?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0cd41b26610</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[mathematics-education]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[maths-tuition]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Sat, 02 May 2020 04:45:25 GMT</pubDate>
            <atom:updated>2020-05-02T04:47:51.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*u6ayegfhg90p21aqdpjeBw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0cd41b26610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Data Structures and Algorithms?]]></title>
            <link>https://medium.com/@bunlong/why-data-structures-and-algorithms-880e87f72231?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/880e87f72231</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 15:00:10 GMT</pubDate>
            <atom:updated>2020-02-10T15:00:10.667Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Structures and Algorithms are some of the most essential topics for programmers, both to get a job and to do well on a job.</p><p>Good knowledge of data structures and algorithms is the foundation of developing the high quality project.</p><h3>What is Algorithms?</h3><p>If you want computer system to do something you need to give it an algorithm. Basically an algorithms is a process or set of rules which is used to solve a computer problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*c-75ePZfP9qra_fRzbLUNg.png" /></figure><h3>What is Algorithms used for?</h3><p>Sometime programmers generate their own algorithms to solve a problem and sometime they uses another algorithm as its part to handle the situation.</p><p>There are different approaches to solve a problem. Some approaches take more time and effort and some don’t according to programmers knowledge and experience on how they implements algorithm best suited for that particular problem.</p><p>Let consider the task of searching an element in an array:</p><ul><li>Algorithm 1: Using Linear search.</li><li>Algorithm 2: Using Binary search.</li></ul><p>Linear search and Binary search, which one is faster?</p><p>In computer programming, firstly you need to pick up one of computer programming language to implement the algorithm and then apply the usage of variables, loops, make the use of jump statements as it makes algorithms run smoothly using little space of memory, or use the break to terminate the process, and so on.</p><p>An algorithm analysis is a technique that is used to measure the performance of the algorithms. Speed is one of the key parameters in determining the potential of an algorithm.</p><p>There are some other factors like user-friendliness, security, maintainability, and usage space that determine the quality of an algorithm.</p><p>Time and space complexity are metrics used to measure parameters:</p><ol><li>Time Complexity — Time Complexity is a way to represent the amount of time required by the program to run till its completion. It’s generally a good practice to try to keep the time required minimum, so that our algorithm completes it’s execution in the minimum time possible.</li><li>Space Complexity — Its the amount of memory space required by the algorithm, during the course of its execution. Space complexity must be taken seriously for multi-user systems and in situations where limited memory is available.</li></ol><h3>What is Data Structures?</h3><p>Data Structures is a particular way of organizing data in a computer so that it can be used efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQQgERSZ5l0BmX99aCCWXA.png" /></figure><h3>What is Data Structures used for?</h3><p>A data structure is selected or designed to store data for the purpose of working on it with various algorithms. Different kinds of data structures are suited to different kinds of applications.</p><p>Data Structures is used to organize the storage and retrieval of information stored in both main memory [RAM] and secondary memory[Hard Disks].</p><p>Data Structures is the key organizing factor in software design as well.</p><p>Thanks for reading ❤ Say Hello! <a href="https://github.com/bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://twitter.com/bunlongvan">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880e87f72231" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component Lifecycle Hooks Cheatsheet]]></title>
            <link>https://medium.com/@bunlong/react-component-lifecycle-hooks-cheatsheet-60424e2985be?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60424e2985be</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 17:29:20 GMT</pubDate>
            <atom:updated>2020-02-02T13:32:32.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*J1OWWbEDit18yTrM0sthgA.png" /></figure><p>useState, useEffect, useRef and React.memo are the hooks and the higher order component that allow you to replace React class component lifecycle methods.</p><h3>useState</h3><ul><li><strong>Use:</strong> to manage a component’s local state.</li><li><strong>Purpose:</strong> to replace the need for this.state and constructor.</li></ul><h3>useEffect</h3><ul><li><strong>Use:</strong> to manage side effects (Ex. an API request, tracking analytics, interacting with DOM not contained inside your React app, etc).</li><li><strong>Purpose:</strong> to replace the need for lifecycle methods (<a href="https://dev.to/bunlong/react-component-lifecycle-methods-cheatsheet-1eaf">React Component Lifecycle Methods Cheatsheet</a>).</li></ul><h3>useRef</h3><ul><li><strong>Use:</strong> to provide the way to access DOM nodes or HTML elements created in the render method.</li><li><strong>Purpose:</strong> to helps the useEffect to replaces the need for componentDidUpdate.</li></ul><h3>memo</h3><ul><li><strong>Use:</strong> to manage a component’s re-rendering.</li><li><strong>Purpose:</strong> to replace the need for shouldComponentUpdate.</li></ul><h3>Explanation with Words and Code</h3><pre>const {useEffect, useState, useRef, memo} = React;<br><br>const ReactLifecycleHooks = (props) =&gt; {<br><br>  // Commonly Used Hooks<br>  // Purpose: Initialize state, read and update state variable.<br><br>  // The useState hook allows you to read and update a state variable.<br>  // The usetState function returns an array containing the current value and the function to <br>  // update the value.        <br>  const [desc, setDesc] = useState(&#39;user&#39;);<br>  const [prevCount, setPrevCount] = useState(null);<br><br>  // The mounted variable of useRef here is used to check the component is rendered.<br>  const mounted = useRef();<br><br>  console.log(&#39;render&#39;);<br><br>  // The useEffect hook takes 2 arguments, a function containing a side effect action and an array.<br>  // The array contains the variable(s) that you want to track.<br>  // When a value in the array changes, the side effect function is executed.<br><br>  // The empty array is passed to useEffect as its second argument<br>  // in the purpose of replacing the useEffect with componentDidMount &amp; componentWillUnmount.<br>  useEffect(() =&gt; {<br>    console.log(&#39;componentDidMount&#39;);<br>    // Lifecycle: Mount immediately after render.<br>    // Purpose: Initialize state that requires DOM nodes, Network requests and side effects.<br>    return () =&gt; {<br>      console.log(&#39;componentWillUnmount&#39;);<br>      // Lifecycle: Unmount.<br>      // Purpost: Clean up things such as event handlers, cancel network request, etc.<br>    }<br>  }, []);<br><br>  // The array containing props.count is passed to useEffect as its second argument<br>  // in the purpose of replacing the useEffect with componentDidUpdate.<br>  // The useEffect is tracking the value of props.count, and when it sees a change, the side effect<br>  // function is executed.<br>  // When the side effect function executes, the logic of checking componentDidUpdate is executed.<br>  useEffect(() =&gt; {<br>    if (!mounted.current) {<br>      mounted.current = true;<br>    } else {<br>      console.log(&#39;componentDidUpdate&#39;);<br>      // Lifecycle: Update immediately after render.<br>      // Purpose: Operate on updated DOM or handle network requests.<br>    }<br>  }, [props.count]);<br><br>  // The logic of calling function getDerivedStateFromProps.<br>  if (prevCount !== props.count) {<br>    setDesc(ReactLifecycleHooksOptimization.getDerivedStateFromProps(props, desc));<br>    setPrevCount(props.count);<br>  }<br><br>  // Required<br>  // Code to display the component.<br>  return (<br>    &lt;&gt;<br>      {props.count} {desc}<br>    &lt;/&gt;<br>  )<br>}<br><br>// Return true if you don&#39;t want it to rerender, return false if you want it to render.<br>const shouldComponentUpdate = (prevProps, nextProps) =&gt; {<br>  console.log(&#39;shouldComponentUpdate&#39;);<br>  // Lifecycle: Update immediately before render.<br>  // Purpose: Allows developer to prevent rendering.<br>  return nextProps.count === prevProps.count;<br>};<br><br>// The memo higher order component allows you to replace the need for shouldComponentUpdate.<br>// The memo higher order component takes 2 arguments, a component and a comparison function of <br>// prevProps and nextProps.<br>const ReactLifecycleHooksOptimization = memo(ReactLifecycleHooks, shouldComponentUpdate);<br><br>// Rarely Used Lifecycle<br><br>// The getDerivedStateFromProps function here is created for the purpose of <br>// using getDerivedStateFromProps in hooks.<br>ReactLifecycleHooksOptimization.getDerivedStateFromProps = (nextProps, prevState) =&gt; {<br>  console.log(`getDerivedStateFromProps<br>  nextProps.count=${nextProps.count}<br>  prevState=${prevState}`);<br>  // Lifecycle: Mount and update immediately before render.<br>  // Purpose: When your state depends on props (should be avoided).<br>  if (nextProps.count === 0 || nextProps.count &gt; 1) {<br>    return &#39;users&#39;;<br>  }<br>  return &#39;user&#39;;<br>}<br><br>const Nothing = () =&gt; &#39;Nothing&#39;;<br>const App = () =&gt; {<br>  const [component, setComponent] = useState(1);<br>  const [count, setCount] = useState(1);<br>  const Component = component &gt; 0 ? ReactLifecycleHooksOptimization : Nothing;  <br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; (console.clear(), setComponent(component &gt; 0 ? 0 : 1))}&gt;Mount/Unmount&lt;/button&gt;<br>      &lt;button onClick={() =&gt; (console.clear(), setCount(count + 1))}&gt;Update value&lt;/button&gt;<br>      &lt;Component count={count} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;app&#39;));</pre><p>Live demo is available on <a href="https://codepen.io/Bunlong/pen/zYYXpZK">CodePen</a>.</p><h3>Note</h3><p>According to the React docs, getSnapshotBeforeUpdate, componentDidCatch and getDerivedStateFromError, there are no Hook equivalents for these methods yet.</p><h3>References</h3><ul><li><a href="https://reactjs.org/docs/hooks-intro.html">Hooks at a Glance — React</a></li></ul><p>Thanks for reading ❤<br>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://www.instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60424e2985be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component Lifecycle Methods Cheatsheet]]></title>
            <link>https://medium.com/@bunlong/react-component-lifecycle-methods-cheatsheet-1fb865884346?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb865884346</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 13:15:02 GMT</pubDate>
            <atom:updated>2020-02-02T12:53:20.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2ANppcgcNvccNSsS8fHbnQ.png" /></figure><p>Each component in React has a lifecycle which you can monitor and manipulate.</p><p>Lifecycle Explanation:</p><ul><li><strong>Mounting:</strong> Called before your component is displayed on the UI.</li><li><strong>Updating:</strong> Caused by a change to props or state and rerendered the UI.</li><li><strong>Unmounting:</strong> Called when your UI will no longer display the component.</li></ul><h3>Mounting</h3><h4>constructor</h4><ul><li><strong>Lifecycle:</strong> Mount immediately before render.</li><li><strong>Purpose:</strong> Initialize state.</li></ul><pre>// Commonly Used Lifecycle Methods<br>constructor() {<br><br>}</pre><h4>componentDidMount</h4><ul><li><strong>Lifecycle:</strong> Mount immediately after render.</li><li><strong>Purpose:</strong> Initialize state that requires DOM nodes, Network requests and side effects.</li></ul><pre>componentDidMount() {<br><br>}</pre><h3>Updating</h3><h4>shouldComponentUpdate</h4><ul><li><strong>Lifecycle:</strong> Update immediately before render.</li><li><strong>Purpose:</strong> Allows developer to prevent rendering.</li></ul><pre>shouldComponentUpdate(nextProps, nextState) { // Optional Parameters<br><br>}</pre><h4>render</h4><p>Code to display the component.</p><pre>// Required<br>render() {<br><br>}</pre><h4>getSnapshotBeforeUpdate</h4><ul><li><strong>Lifecycle:</strong> Update immediately before render output is committed to DOM.</li><li><strong>Purpose:</strong> Capture DOM information such as scroll position which could change.</li></ul><pre>getSnapshotBeforeUpdate(prevProps, prevState) { // Optional Parameters<br><br>}</pre><h4>componentDidUpdate</h4><ul><li><strong>Lifecycle:</strong> Update immediately after render.</li><li><strong>Purpose:</strong> Operate on updated DOM or handle network requests.</li></ul><pre>componentDidUpdate(prevProps, prevState, snapshot) { // Optional Parameters<br><br>}</pre><h3>Mounting &amp; Updating</h3><h4>getDerivedStateFromProps</h4><ul><li><strong>Lifecycle:</strong> Mount and update immediately before render.</li><li><strong>Purpose:</strong> When your state depends on props (should be avoided).</li></ul><pre>// Rarely Used Lifecycle Methods<br>static getDerivedStateFromProps(props, state) { // Optional Parameters<br><br>}</pre><h3>Unmounting</h3><h4>componentWillUnmount</h4><ul><li><strong>Lifecycle:</strong> Unmount.</li><li><strong>Purpose:</strong> Clean up things such as event handlers, cancel network request, etc.</li></ul><pre>componentWillUnmount() {<br><br>}</pre><h3>Other Methods</h3><h4>componentDidCatch</h4><p>Creates an error boundary to captures errors from child components.</p><pre>// Special Use Cases<br>componentDidCatch(error, info) { // Optional Parameters<br><br>}</pre><h3>References</h3><ul><li><a href="https://reactjs.org/">React.Component — React</a></li></ul><p>Thanks for reading ❤<br>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://www.instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb865884346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‘Single-Quotes’ Vs “Double-Quotes” in JavaScript]]></title>
            <link>https://medium.com/@bunlong/single-quotes-vs-double-quotes-in-javascript-f224894d554f?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f224894d554f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 16:06:34 GMT</pubDate>
            <atom:updated>2019-11-18T08:40:53.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Single-Quotes Vs Double-Quotes in JavaScript" src="https://cdn-images-1.medium.com/max/950/1*0tm2VgzszE9wTTVZxQcKtw.png" /><figcaption>Code tidbit by Bunlong</figcaption></figure><p>JavaScript, allows you to use either single quotes (&#39;&#39;) or double quotes (&quot;&quot;) to create a string literals.</p><h3>Both Have the Same Qualities</h3><p>They are essentially the same.</p><pre>console.log(&#39;abc&#39; === &quot;abc&quot;); // true</pre><p>A single quoted string can have double quotes within it without having to escape them.</p><pre>console.log(&#39;Single quotes with a double ( &quot; ) quote in the middle.&#39;);</pre><p>A double quoted string can have single quotes without escaping them.</p><pre>console.log(&quot;Double quotes with a single ( &#39; ) quote in the middle.&quot;);</pre><p>Each type must escape their own type.</p><pre>console.log(&#39;single quotes ( \&#39; ) must escape a single quote&#39;);</pre><pre>console.log(&quot;double quotes ( \&quot; ) must escape a double quote&quot;);</pre><h3>Pros of Using Single Quotes</h3><p>One popular argument for single quotes is when you have to write html within JavaScript.</p><p>If you use single quotes you can write as following.</p><pre>const html = &#39;&lt;div id=&quot;some_div&quot;&gt;&lt;/div&gt;&#39;;</pre><p>If you use double quotes you must escape each nested &quot;</p><pre>const html = &quot;&lt;div id=\&quot;some_div\&quot;&gt;&lt;/div&gt;&quot;;</pre><p>which can get annoying or you could use single quotes within the html string.</p><h3>Pros of Using Double Quotes</h3><p>Remember that JSON only allows double quotes.</p><pre>{<br>  &quot;in_json&quot;: &quot;You use only double quotes.&quot;<br>}</pre><h3>Single Quotes are More Common</h3><p>A few repositories of popular JavaScript projects reveals that single quotes are favored over double quotes.</p><pre>+------------+----------------------------------+<br>| Projects   | Dominant of Single Quotes        |<br>+------------+----------------------------------+<br>| async      | Single-Quotes (&#39;&#39;) 76% of quotes |<br>| express    | Single-Quotes (&#39;&#39;) 92% of quotes |<br>| lodash     | Single-Quotes (&#39;&#39;) 73% of quotes |<br>| request    | Single-Quotes (&#39;&#39;) 97% of quotes |<br>| underscore | Single-Quotes (&#39;&#39;) 78% of quotes |<br>| angular    | Single-Quotes (&#39;&#39;) 58% of quotes |<br>| react      | Single-Quotes (&#39;&#39;) 52% of quotes |<br>+------------+----------------------------------+</pre><p>You can see that front-end libraries (React, Angualar) have more double quotes than the other libraries as might have to do with the presence of HTML fragments.</p><p>Let’s take a look at a few style guides you can see that about half recommend single quotes and other half double quotes.</p><ul><li><a href="https://developers.google.com/closure/utilities">gjslint</a> (Google Closure Linter) favors single quotes (&#39;&#39;).</li><li><a href="https://www.npmjs.com/package/standard">standard</a> (an NPM package) favors single quotes (&#39;&#39;).</li><li><a href="http://www.jslint.com/">jslint</a> favors double quotes (&quot;&quot;).</li><li><a href="https://eslint.org/">eslint</a> favors double quotes (&quot;&quot;).</li><li><a href="https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines">TypeScript Contributors Coding Guidelines</a> favors double quotes (&quot;&quot;).</li></ul><h3>Summary</h3><p>You should define one standard style and stick with it. I recommend single quotes (&#39;&#39;) as a solid standard and more common.</p><p>In ES6, there is another option to create a string literals using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a>.</p><h3>References</h3><ul><li><a href="https://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript">Stack Overflow: When to Use Double or Single Quotes in JavaScript?</a></li><li><a href="https://stackoverflow.com/questions/9959928/double-quotes-vs-single-quotes-in-javascript">Stack Overflow: Double Quotes Vs Single Quotes in JavaScript</a></li><li><a href="https://stackoverflow.com/questions/3149192/difference-between-single-quotes-and-double-quotes-in-javascript">Stack Overflow: Difference Between Single Quotes and Double Quotes in Javascript</a></li></ul><p>Thanks for reading ❤</p><p>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/Bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f224894d554f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Real-World Case Study of Improving React App Runtime Performance]]></title>
            <link>https://medium.com/@bunlong/a-real-world-case-study-of-improving-react-app-runtime-performance-7edf61657e7a?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7edf61657e7a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Fri, 15 Nov 2019 16:54:25 GMT</pubDate>
            <atom:updated>2019-11-17T07:48:15.644Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A real-world case study of React SPA performance optimization.</blockquote><p>A web application performance is not just only about loading time. It is critical to provide a fast performance app to users, especially for productivity web application which people use everyday.</p><h3>The Issue</h3><p>A web application built with React which helps store owners (restaurants and cafes shop) to manage the shift work of their staffs. The single page application provides rich client features including various grid tables of shift schedules organized by day, week, month and more.</p><p>After development team added new features to the app, they started seeing more feedback around slow performance.</p><p>After going through the investigate, the development team realized that many of their users were trying to load massive shift tables on low spec computers.</p><p>And the app was blocking the main thread with heavy scripts, but the development team didn’t realize how heavy the scripts were because they were developing and testing on rich spec computers with fast wifi connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RI9RPFMZDfQ80veNIGq4lg.png" /></figure><p>When loading the shift table, around 80% of the load time was consumed by running scripts.</p><p>After profiling the performance in <a href="https://developers.google.com/web/tools/chrome-devtools">Chrome DevTools</a> with CPU and network throttling enabled, it became clear that performance optimization was needed.</p><p>The following are 4 things they focused on to make app more responsive to user input.</p><h3>1. Virtualize Large Tables</h3><h3>The Issue</h3><p>Displaying the shift table is required many heavy steps, constructing the virtual DOM and rendering it on screen.</p><p>For instance, if a restaurant had 50 staffs who want to check their monthly shift schedule, it would be a table of 50 (staffs) multiplied by 30 (days) which would lead to 1, 500 components to render.</p><p>This is a very heavy operation, especially for low spec devices. In reality, things were worse. From the investigate they learned that there were shops managing 200 staffs, requiring around 6, 000 components in a single monthly table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Y62bw0uaE9Gy-JTbNFxCUw.png" /></figure><h3>The Solution</h3><p>To reduce the cost of this operation, the development team virtualized the shift table. The app now only mounts the components within the viewport and unmounts the off-screen components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fCTlfcv4JlTYUMLRERJzuQ.png" /></figure><p>In this case, The development team used <a href="https://github.com/bvaughn/react-virtualized">react-virtualized</a> as there were requirements around enabling complex two dimensional grid tables.</p><h3>The Result</h3><p>Virtualizing the table alone reduced scripting time by 6 seconds (on a 4x CPU slowdown + Fast 3G throttled Macbook Pro environment). This was the most impactful performance improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rWvU4Nke6uMsWb_sxUXnOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Vu2537iYAV0HcSigsSWLng.png" /></figure><h3>2. Audit with User Timing API</h3><h3>The Solution</h3><p>Next, the development team refactored the scripts that run on user input. The <a href="https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference#main">flame chart</a> of <a href="https://developers.google.com/web/tools/chrome-devtools/">Chrome DevTools</a> makes it possible to analyze what’s actually happening in the main thread, but the development team found it easier to analyze application activity based on React’s lifecycle.</p><p>React 16 provides its performance trace via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API">User Timing API</a>, which you can visualize from the <a href="https://developers.google.com/web/updates/2018/04/devtools#tabs">Timings section</a> of Chrome DevTools. The development team used the Timings section to find unnecessary logic running in React lifecycle events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7Jq0dFgnHpSap5bQ0mz1_g.png" /></figure><h4>The Result</h4><p>The development team discovered that an unnecessary <a href="https://reactjs.org/docs/reconciliation.html">React Tree Reconciliation</a> was happening right before every route navigation. This mean that React was updating the shift table unnecessarily before navigations. An unnecessary Redux state update was causing this issue. Fixing it saved around 750 ms of scripting time. The development team made other micro optimizations as well which eventually led to a 1 second total reduction in scripting time.</p><h3>3. Lazy Load Components and Move Heavy Logic to Web Workers</h3><h4>The Issue</h4><p>The development team has a built-in chat application. Many store owners communicate with their staffs via the chat while looking at the shift table, which means that a user might be typing a message while the table is loading. If the main thread is occupied with scripts that are rendering the table, user input could be janky.</p><h4>The Solution</h4><p>To improve this, the development team used <a href="https://reactjs.org/docs/code-splitting.html">React.lazy and Suspense</a> to show placeholders for table contents while lazily loading the actual components.</p><p>The development team also migrated some of the heavy business logic within the lazily loaded components to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">web workers</a>. This solved the user input jank problem by freeing up the main thread so that it could focus on responding to user input.</p><p>Typically developers face complexity in using workers but this time <a href="https://github.com/GoogleChromeLabs/comlink">Comlink</a> did the heavy lifting for them. Below is the code of how the development team workerized one of the most heavy operations they had is calculating total labor costs.</p><p>In App.js, use React.lazy and Suspense to show fallback content while loading.</p><pre>// App.js</pre><pre>import React, { lazy, Suspense } from &#39;react&#39;<br> <br>// Lazily loading the Cost component with React.lazy<br>const Hello = lazy(() =&gt; import(&#39;./Cost&#39;))<br> <br>const Loading = () =&gt; (<br>  &lt;div&gt;Some fallback content to show while loading&lt;/div&gt;<br>)<br> <br>// Showing the fallback content while loading the Cost component by Suspense<br>export default function App({ userInfo }) {<br>   return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>        &lt;Cost /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In the Cost component, use <a href="https://github.com/GoogleChromeLabs/comlink">Comlink</a> to execute the calc logic.</p><pre>// Cost.js</pre><pre>import React from &#39;react&#39;<br>import { proxy } from &#39;comlink&#39;<br> <br>// Import the workerlized calc function with comlink<br>const WorkerlizedCostCalc = proxy(new Worker(&#39;./WorkerlizedCostCalc.js&#39;))</pre><pre>export default function Cost({ userInfo }) {<br>  // Execute the calculation in the worker<br>  const instance = await new WorkerlizedCostCalc()<br>  const cost = await instance.calc(userInfo)<br>  return &lt;p&gt;{cost}&lt;/p&gt;<br>}</pre><p>Implement the calculation logic that runs in the worker and expose it with <a href="https://github.com/GoogleChromeLabs/comlink">Comlink</a>.</p><pre>// WorkerlizedCostCalc.js</pre><pre>import { expose } from &#39;comlink&#39;<br>import { someExpensiveCalculation } from &#39;./CostCalc.js&#39;<br> <br>// Expose the new workerlized calc function with comlink<br>expose({<br>  calc(userInfo) {<br>    // run existing (expensive) function in the worker<br>    return someExpensiveCalculation(userInfo);<br>  }<br>}, self)</pre><h4>The Result</h4><p>Despite the limited amount of logic they workerized as a trial, the development team shifted around 100 ms of their JavaScript from the main thread to the worker thread (simulated with 4x CPU throttling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o0Ksbf_zBB8yABSUzUQ64A.png" /></figure><p>The development team is currently exploring whether they can lazy load other components and offload more logic to web workers to further reduce jank.</p><h3>4. Setting a Performance Budget</h3><p>Having implemented all of these optimizations, it was critical to make sure that the app remains performant over time. The development team now uses <a href="https://github.com/siddharthkp/bundlesize">bundlesize</a> to not exceed the current JavaScript and CSS file size. Aside from setting these basic budgets, they built a dashboard to show various percentiles of the shift table loading time to check whether the application is performant even in non-ideal conditions.</p><ul><li>The script completion time for every Redux event is now measured.</li><li>Performance data is collected in <a href="https://www.elastic.co/jp/">Elasticsearch</a>.</li><li>10th, 25th, 50th, and 75th percentile performance of each event is visualized with <a href="https://www.elastic.co/jp/products/kibana">Kibana</a>.</li></ul><p>The development team is now monitoring the shift table loading event to make sure it completes in 3 seconds for the 75th percentile users. This is an unenforced budget for now but they are considering auto-notifications via Elasticsearch when they exceed their budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FxVD6Z4Ap-j5YUFEymPEug.png" /></figure><h4>The Result</h4><p>From the graph above, you can tell that the development team is now mostly hitting the 3 seconds budget for 75th percentile users and also loading the shift table within a second for 25th percentile users. By capturing RUM performance data from various conditions and devices, the development team can now check whether a new feature release is actually affecting the application’s performance or not.</p><h3>Summary</h3><p>It was definitely not the easiest journey for the development team to work on these optimizations but it certainly paid off. Now the application is loading the shift table within 1.5 sec which is a 6x improvement from their performance before the project.</p><p>After Improvement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*WoYoNQKVt9VzA5eYi4V6jQ.gif" /></figure><p>Before Improvement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*3YeKRMpZEkWQXfGVxPAc3A.gif" /></figure><p>Thanks for reading ❤</p><p>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/Bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7edf61657e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Style Console Output in JavaScript]]></title>
            <link>https://medium.com/@bunlong/style-console-output-in-javascript-160485944839?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/160485944839</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 16:03:47 GMT</pubDate>
            <atom:updated>2019-11-12T16:27:41.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Style Console Output in JavaScript" src="https://cdn-images-1.medium.com/max/1024/1*rDg1dk55lyHjNBwy0ByZ4A.png" /><figcaption>Code tidbit by Bunlong</figcaption></figure><p>When writing a complex web application one of the important debugging tools is using the logging facility the environment provides. This can help the developer see what’s going in the application without interfering with the real UI.</p><p>The standard way to print out a message to the JavaScript console of the web browser (or Node application) is using the log method of the console object. It accepts a list of strings and objects and prints them to the console.</p><p>Actually, the console object has several additional methods that can be used to fine-tune the logging. There are debug, info, log, warn, error.</p><p>You can use the %c directive to apply a CSS style to console output, it help you easily identify debug information in the console.</p><h3>Browser’s Debugging Console</h3><h4>1. Basic Text Styles</h4><pre>// Single Text Styles<br>console.log(&#39;This is %cmy stylish message.&#39;, &#39;color: yellow; background-color: blue;&#39;);<br><br>// Multiple Text Styles<br>console.log(&#39;This is %cmy stylish message. %cAwesome!&#39;, &#39;color: yellow; background-color: blue;&#39;, &#39;color: blue; background-color: yellow;&#39;);</pre><p>The text before the %c directive will not be affected, but the text after the %cdirective will be styled using the CSS declarations in the parameter.</p><h4>2. Refactor Text Styles</h4><p>You can clean up the text using %s string substitutions.</p><pre>const styles = &#39;color: yellow; background-color: blue;&#39;;<br>const text = &#39;This is my stylish message.&#39;;<br>console.log(&#39;%c%s&#39;, styles, text);</pre><p>You can clean up the styles by passing the styles as an array and then use the join() method to turn the array elements into a string.</p><pre>const styles = [<br>  &#39;color: yellow&#39;,<br>  &#39;background-color: blue&#39;,<br>].join(&#39;;&#39;);<br><br>const text = &#39;This is my stylish message.&#39;;<br>console.log(&#39;%c%s&#39;, styles, text);</pre><h3>Node Debugging Console</h3><p>You can print the colorful text in Node application as well.</p><pre>console.log(&#39;\x1b[33m%s\x1b[0m&#39;, &#39;This is my stylish message.&#39;);</pre><p><a href="https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color">Color Reference on Stack Overflow.</a></p><h3>References</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/console">MDN Web Docs — Console</a></li><li><a href="https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color">Stack Overflow: Color Reference</a></li></ul><p>Thanks for reading ❤<br>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://www.instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=160485944839" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrow Functions Return Rules in JavaScript]]></title>
            <link>https://medium.com/@bunlong/arrow-functions-return-rules-in-javascript-b63ed5f25994?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b63ed5f25994</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 16:56:39 GMT</pubDate>
            <atom:updated>2020-02-04T13:50:59.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*GG9YZmW3GEEW6FZPqS8RRQ.png" /></figure><p>There are 2 ways for returning values in arrow functions:</p><ol><li>Explicit Return</li><li>Implicit Return</li></ol><h3>1. Explicit Return</h3><p><strong>What is Explicit Return?</strong></p><p>A function is returned values using the return keyword, it’s called an explicit return.</p><p><strong>The Rules of Explicit Return</strong></p><p>You must use an explicit return statement in a block body.</p><p><strong>Example</strong></p><pre>// Single-line<br>const explicit = (value) =&gt; { return value; }<br><br>// Multi-line<br>const explicit = (value) =&gt; {<br>  return value;<br>}</pre><h3>2. Implicit Return</h3><p><strong>What is Implicit Return?</strong></p><p>A function is returned values without using the return keyword, it’s called an implicit return.</p><p><strong>The Rules of Implicit Return</strong></p><p>You must use an implicit return in a concise body.</p><p><strong>Example</strong></p><pre>// Single-line<br>const implicit = (value) =&gt; value;<br><br>// Multi-line<br>const implicit = (value) =&gt; (<br>  value<br>);</pre><p><strong>Issue Returning Objects</strong></p><p>When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function’s body.</p><pre>const implicit = () =&gt; { value: 1 };<br>implicit(); // undefined<br><br>const implicit = () =&gt; ({ value: 1 });<br>implicit(); // { value: 1 }</pre><h3>Parens Rules</h3><p>Arrow functions can omit parentheses when they have exactly one parameter.</p><pre>// Arrow Functions, with parentheses<br>const myFunction = (p) =&gt; {}<br><br>// Arrow Functions, without parentheses<br>const myFunction = p =&gt; {}</pre><p>In all other cases (multiple parameters), the parameter(s) must be wrapped in parentheses.</p><pre>// Arrow Function, with parentheses<br>const myFunction = (p1, p2) =&gt; {}</pre><h3>References</h3><ul><li><a href="https://jaketrent.com/post/javascript-arrow-function-return-rules">JavaScript Arrow Function Return Rules</a></li><li><a href="https://eslint.org/docs/rules/arrow-parens">Eslint — arrow-parens rules</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">MDN Web Docs — Arrow functions</a></li></ul><p>Thanks for reading ❤<br>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://www.instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b63ed5f25994" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dot Notation Vs Bracket Notation to Access Object Properties in JavaScript]]></title>
            <link>https://medium.com/@bunlong/dot-notation-vs-bracket-notation-to-access-object-properties-in-javascript-b9a916205e61?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a916205e61</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 08:55:21 GMT</pubDate>
            <atom:updated>2019-11-03T15:33:38.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Dot Notation Vs Bracket Notation to Access Object Properties in JavaScript" src="https://cdn-images-1.medium.com/max/797/1*4ArCZQYVIH3SKAY0JzYpng.png" /><figcaption>Code Tidbit by Bunlong</figcaption></figure><h3>Accessing Object Properties</h3><p>There are 2 ways to access object properties are Dot and Bracket in JavaScript.</p><pre>const obj = {<br>  name: &#39;value&#39;<br>};</pre><pre>// Dot Notation<br>obj.name; // &#39;value&#39;</pre><pre>// Bracket Notation<br>obj[&#39;name&#39;]; // &#39;value&#39;</pre><p>But the question is always which one should I use 🤔. Let’s get to understand Dot Notation’s issues which is the root to answer the question.</p><h3>Dot Notation’s Issues</h3><ol><li>Issue working with invalid Identifiers</li><li>Issue working with Variables</li></ol><h4>1. Issue working with invalid Identifiers</h4><p>Dot notations is only work with valid identifiers. But what is identifiers?</p><blockquote>Identifiers are names. In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).</blockquote><p>In JavaScript, the identifier has the following rules:</p><ul><li>case sensitive</li><li>can contain Unicode letters</li><li>$, _, and digits (0–9) are allowed but may not start with a digit</li></ul><p>Let’s take a look the examples below and see what happens when we use the Dot notation and Bracket notation.</p><pre>const obj = {<br>  123: &#39;digit&#39;,<br>  123name: &#39;start with digit&#39;,<br>  name123: &#39;does not start with digit&#39;,<br>  $name: &#39;$ sign&#39;,<br>  name-123: &#39;hyphen&#39;,<br>  NAME: &#39;upper case&#39;,<br>  name: &#39;lower case&#39;<br>};</pre><p>Using with Dot Notation</p><pre>obj.123;      // ❌ SyntaxError<br>obj.123name;  // ❌ SyntaxError<br>obj.name123;  // ✅ &#39;does not start with digit&#39;<br>obj.$name;    // ✅  &#39;$ sign&#39;</pre><pre>obj.name-123;  // ❌ SyntaxError<br>obj.&#39;name-123&#39;;// ❌ SyntaxError</pre><pre>obj.NAME; // ✅ &#39;upper case&#39;<br>obj.name; // ✅ &#39;lower case&#39;</pre><p>Using with Bracket Notation</p><pre>obj[&#39;123&#39;];     // ✅ &#39;digit&#39;<br>obj[&#39;123name&#39;]; // ✅ &#39;start with digit&#39;<br>obj[&#39;name123&#39;]; // ✅ &#39;does not start with digit&#39;<br>obj[&#39;$name&#39;];   // ✅ &#39;$ sign&#39;</pre><pre>obj[&#39;name-123&#39;]; // ✅ &#39;does not start with digit&#39;</pre><pre>obj[&#39;NAME&#39;]; // ✅ &#39;upper case&#39;<br>obj[&#39;name&#39;]; // ✅ &#39;lower case&#39;</pre><blockquote>If you think you have an invalid JavaScript identifier as your property key, use the Bracket Notation.</blockquote><h4>2. Issue working with Variables</h4><p>Another issue of the Dot notation is working with variables.</p><p>Let’s take a look the examples below and see what happens when we use the Dot notation and Bracket notation.</p><pre>const variable = &#39;name&#39;;</pre><pre>const obj = {<br>  name: &#39;value&#39;<br>};</pre><pre>// Dot Notation<br>obj.variable; // undefined</pre><pre>// Bracket Notation<br>obj[variable]; // ✅ &#39;value&#39;</pre><blockquote>Never use the Dot Notation when using a Variable.</blockquote><h3>Undefined Property (Bonus)</h3><p>When you try to access a property that doesn’t exist, it will return undefined.</p><pre>const emptyObj = {};</pre><pre>emptyObj.name; // undefined</pre><pre>emptyObj[&#39;name&#39;]; // undefined</pre><h3>Summary</h3><blockquote>Use the Dot Notation. Anyway if you’re dealing with invalid identifier or variables, use the Bracket Notation instead.</blockquote><p>Thanks for reading ❤</p><p>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/Bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a916205e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Not to use Arrow Functions]]></title>
            <link>https://medium.com/@bunlong/when-not-to-use-arrow-functions-ddb8a9b4972a?source=rss-66a7e388cf4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb8a9b4972a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bunlong]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 14:21:29 GMT</pubDate>
            <atom:updated>2019-11-03T09:12:40.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jxmR1moVHuFLde72oSD_-g.png" /><figcaption>Code Tidbit by Bunlong</figcaption></figure><p>Here are some instances where you probably should avoid using arrow functions:</p><h3>1. Object Methods</h3><pre>const person = {<br>  points: 23,<br>  score: () =&gt; {<br>    console.log(this); // &#39;this&#39; here is window<br>    this.points++; // &#39;this&#39; here is window, not person<br>  }<br>}</pre><pre>person.score();</pre><pre>console.log(person.points); // 23</pre><p>When you do console.log(person.points) the result should be 24 but it’s still 23.</p><p>Why? because this is always scoped to the parent which is the window in this case (it’s not bound to anything else).</p><p>You must use regular function instead.</p><pre>const person = {<br>  points: 23,<br>  score: function()  {<br>    this.points++; // &#39;this&#39; here is person<br>  }<br>}</pre><pre>person.score();</pre><pre>console.log(person.points); // 24</pre><h3>2. Callback Functions with Dynamic Context</h3><pre>const button = document.getElementById(&#39;myButton&#39;);<br>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(this); // &#39;this&#39; here is window<br>  this.innerHTML = &#39;Clicked Button&#39;; // &#39;this&#39; here is window, not button<br>});</pre><p>When you click on myButton it won’t actually work.</p><p>Why? because this is not bound to the button, but instead bound to its parent scope which is the window in this case.</p><p>You must use regular function instead:</p><pre>const button = document.getElementById(&#39;myButton&#39;);<br>button.addEventListener(&#39;click&#39;, function() {<br>  console.log(this); // button<br>  this.innerHTML = &#39;Clicked Button&#39;; // &#39;this&#39; here is button<br>});</pre><h3>3. Prototype Methods</h3><pre>class Person {<br>  constructor(points) {<br>    this.points = points;<br>  }<br>}</pre><pre>Person.prototype.info = () =&gt; {<br>  console.log(this); // &#39;this&#39; here is window<br>  return `Points: ${this.points}`; // // &#39;this&#39; here is window, not Person<br>};</pre><pre>const me = new Person(24);</pre><pre>console.log(me.info());</pre><p>When you do console.log(me.info()) it won’t actually work.</p><p>Why? Why? because this is not bound to the Person, but instead bound to its parent scope which is the window in this case.</p><p>You must use regular function instead:</p><pre>class Person {<br>  constructor(points) {<br>    this.points = points;<br>  }<br>}</pre><pre>Person.prototype.info = function() {<br>  console.log(this); // Person<br>  return `Points: ${this.points}`; // // &#39;this&#39; here is Person<br>};</pre><pre>const me = new Person(24);</pre><pre>console.log(me.info());</pre><h3>4. arguments Object</h3><pre>const logArgument = () =&gt; {<br>  console.log(arguments[0]);<br>};</pre><pre>logArgument(&#39;Hi!&#39;); // ReferenceError: arguments is not defined</pre><p>It won’t actually work.</p><p>Why? because arrow functions do not automatically bind their own arguments value, and that there was no reference to arguments in logArgument’s outer scope, so the compiler throws a reference error.</p><p>You must use regular function instead:</p><pre>const logArgument = function () {<br>  console.log(arguments[0]);<br>};</pre><pre>logArgument(&#39;Hi!&#39;); // Hi!</pre><h3>Summary</h3><p>Arrow functions are terrific, but not suitable for all situations. Places where they will not only help, but cause you trouble.</p><blockquote>Arrow functions doesn’t replace regular functions.</blockquote><p>Thanks for reading ❤</p><p>Say Hello! <a href="https://twitter.com/bunlongvan">Twitter</a> | <a href="https://github.com/Bunlong">Github</a> | <a href="https://www.linkedin.com/in/bunlongvan">LinkedIn</a> | <a href="https://www.facebook.com/codervlog">Facebook</a> | <a href="https://instagram.com/codervlog">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb8a9b4972a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>