<?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 Pinakin Mistry on Medium]]></title>
        <description><![CDATA[Stories by Pinakin Mistry on Medium]]></description>
        <link>https://medium.com/@PinakinMistry?source=rss-95d85303f39d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ejjySZvKWzf5gk7J.png</url>
            <title>Stories by Pinakin Mistry on Medium</title>
            <link>https://medium.com/@PinakinMistry?source=rss-95d85303f39d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 19 May 2026 19:29:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@PinakinMistry/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[Angular Component Cutter Using ES2015, Gulp & Webpack]]></title>
            <link>https://medium.com/@PinakinMistry/angular-component-cutter-using-es2015-gulp-webpack-127957aa0d70?source=rss-95d85303f39d------2</link>
            <guid isPermaLink="false">https://medium.com/p/127957aa0d70</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Pinakin Mistry]]></dc:creator>
            <pubDate>Thu, 08 Oct 2015 11:31:31 GMT</pubDate>
            <atom:updated>2016-06-07T17:00:02.996Z</atom:updated>
            <content:encoded><![CDATA[<h2>Angular</h2><h2>Component Cutter</h2><h2>Using</h2><h2>ES2015, Gulp &amp; Webpack</h2><p>We have components everywhere. Our software is no exception. We have them in cutting edge stuffs like React, Bower, NPM, Web Components, Ember, and now in Angular 2. <strong><em>Components are like building blocks in Lego game which does one thing and does it very well</em></strong>. And they’re so generic/reusable that we can fit them together to build stuffs that we want.</p><p>Now think about them other way around. We can split our huge application into smaller, independent, reusable and testable components based on their functionality which can then be packaged together to build the entire application. These components can be business objects like product, user, shopping cart, etc. or even technical things like header, footer, menu, etc. These can then be reused in other applications of similar nature requiring similar business and technical components.</p><p>With <a href="https://babeljs.io/docs/learn-es2015/#introduction"><strong>ES2015</strong></a> and <a href="http://www.jvandemo.com/a-10-minute-primer-to-the-new-angular-router/"><strong>component router in Angular 1.5</strong></a> coming soon which is going to ease the transition to Angular 2, it’s worth exploring the newest way of writing Angular apps using this super awesome combo and component mindset. And then we can take it to next level by <strong><em>automating component making process and make it as simple as a cookie cutter.</em></strong></p><blockquote>Here are the 2 tools that we need:</blockquote><h4><strong>1. Webpack:</strong></h4><ul><li>Transpiles ES2015 (ES6) to ES5 (JavaScript that current browsers know).</li><li>Loads HTML files and dependent files as modules.</li><li>Transpiles stylesheets and appends them to HTML.</li><li>Bundles the entire app.</li><li>Loads the modules on demand to keep initial load time low.</li></ul><h4><strong>2. Gulp:</strong></h4><p>Gulp is used as orchestrator for</p><ul><li>Starting and calling Webpack.</li><li>Starting a development server.</li><li>Refreshing the browser and rebuilding on file changes.</li></ul><h3>File Organization of Angular App:</h3><p>With components in mind, let’s have file organization as show below:</p><pre>client<br>⋅⋅app/<br>⋅⋅⋅⋅app.js * app entry file<br>⋅⋅⋅⋅app.html * app template<br>⋅⋅⋅⋅common/ * functionality pertinent to several components<br>⋅⋅⋅⋅components/ * where components live<br>⋅⋅⋅⋅⋅⋅components.js * components entry file<br>⋅⋅⋅⋅⋅⋅home/ * home component<br>⋅⋅⋅⋅⋅⋅⋅⋅home.js * entry file (routes, configurations, declarations)<br>⋅⋅⋅⋅⋅⋅⋅⋅home.component.js * home &quot;directive&quot;<br>⋅⋅⋅⋅⋅⋅⋅⋅home.controller.js * home controller<br>⋅⋅⋅⋅⋅⋅⋅⋅home.styl * home styles<br>⋅⋅⋅⋅⋅⋅⋅⋅home.html * home template<br>⋅⋅⋅⋅⋅⋅⋅⋅home.spec.js * home specs</pre><p>Let’s look at how <strong>home</strong> component can be implemented in these individual files using new features like import, export, class, object shortcut notation, arrow function from ES2015:</p><blockquote><strong>home.js:</strong></blockquote><p>This is the first file we should look at as it holds the definition of the component, what url it is reachable at and what’s its template which acts as skin cover for the component. The template (line 15) should use a custom directive, home in this case (line 19), which is imported as homeComponent from <strong><em>home.component.js</em></strong> file (line 3).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b0e7dec062a6a864a6d6045c359afd/href">https://medium.com/media/72b0e7dec062a6a864a6d6045c359afd/href</a></iframe><p><strong><em>Note:</em></strong><em> Above is the only component file that has angular in it. The following files have plain JavaScript making Angular’s footprint smaller in our code base. Thanks to ES2015&#39;s import/export feature to make this possible.</em></p><blockquote><strong>home.component.js:</strong></blockquote><p>This is the center piece that imports and knits the component’s HTML, controller and stylesheet together. Since this custom directive is used in the template of home component, home.html gets rendered on the screen with home.styl applied to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2484cdaba4476348356954ee1d0883ac/href">https://medium.com/media/2484cdaba4476348356954ee1d0883ac/href</a></iframe><blockquote><strong>home.controller.js:</strong></blockquote><p>Next comes the controller that makes all the JavaScript properties and methods defined on HomeController class accessible in the home.html template via controller’s alias name vm declared in above file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8df89a6e898b05484ce4d23a413a469/href">https://medium.com/media/e8df89a6e898b05484ce4d23a413a469/href</a></iframe><blockquote><strong>home.styl:</strong></blockquote><p>Stylesheet written using Stylus gets converted to CSS using Webpack’s stylus loader.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/976733484b15e24d5ff837639091bd84/href">https://medium.com/media/976733484b15e24d5ff837639091bd84/href</a></iframe><blockquote><strong>home.html:</strong></blockquote><p>This holds the UI of the component, binding the data and methods defined in the controller class via vm object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/843335d82e09b0b0fae7ca1634044b09/href">https://medium.com/media/843335d82e09b0b0fae7ca1634044b09/href</a></iframe><blockquote><strong>home.spec.js:</strong></blockquote><p>With spec file for individual components, we can write well focused and isolated test cases for all the features we add in our component. Also packing spec file in here ensures that it will always move along with the component if it is reused in other applications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20ebc0e59f0eb55efbec09301bc105a1/href">https://medium.com/media/20ebc0e59f0eb55efbec09301bc105a1/href</a></iframe><h3>Webpack Config:</h3><p>It’s worth mentioning about Webpack module loaders configuration that makes importing .html, .styl, .css, .js and even .png, .jpg, .jpeg possible at component level. Here is how loaders are configured:</p><blockquote><strong>webpack.config.js:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9dd736609912c9749724518253e24f9/href">https://medium.com/media/a9dd736609912c9749724518253e24f9/href</a></iframe><h3>Automation of Component Creation:</h3><p>Writing these individual files for creating components is tedious. How about automating it? Let’s take copy of all the home component files and name them as temp and parameterize name of the component in these files for automating component creation.</p><blockquote><strong>temp.js:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eac2c61a0f92da0bba3d402587c3bf47/href">https://medium.com/media/eac2c61a0f92da0bba3d402587c3bf47/href</a></iframe><blockquote><strong>temp.component.js:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f60c85e9b64ca6a5b0d5320c647cccbf/href">https://medium.com/media/f60c85e9b64ca6a5b0d5320c647cccbf/href</a></iframe><blockquote><strong>temp.controller.js:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db200216ff0c46063d64d41fb3bda897/href">https://medium.com/media/db200216ff0c46063d64d41fb3bda897/href</a></iframe><blockquote><strong>temp.styl:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce5ee288a2ebc6c03376aa1d5c29f257/href">https://medium.com/media/ce5ee288a2ebc6c03376aa1d5c29f257/href</a></iframe><blockquote><strong>temp.html:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb3108dde2865b2530efad790e74ff8/href">https://medium.com/media/3bb3108dde2865b2530efad790e74ff8/href</a></iframe><blockquote><strong>temp.spec.js:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/085a57f322d234b8a881ec334e7eca5a/href">https://medium.com/media/085a57f322d234b8a881ec334e7eca5a/href</a></iframe><h3><strong>Command To Cut A Component:</strong></h3><pre>gulp component --name componentName</pre><p>And you get a brand new component cut out with the given name. Isn’t this as simple as a cookie cutter? This is all it takes to setup this command as a gulp task in gulpfile.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc662b86bcd8562da7182055c907981/href">https://medium.com/media/bcc662b86bcd8562da7182055c907981/href</a></iframe><p>We need to have all the temp files listed above inside a directory and point paths.blankTemplates variable to it to seed all these files in this task. It will take name parameter that we will enter in the command after — name and use it to replace name and upCaseName in all these files that we have parameterized between &lt;%= and %&gt;</p><p>That’s is it! If you want to try this out yourself, fork and play around with this tiny seed called <a href="https://github.com/angular-class/NG6-starter"><strong>NG6-starter</strong></a><strong>.</strong></p><h4>Bake some cookies the way you like. Enjoy.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127957aa0d70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Path to JumpStart with JavaScript]]></title>
            <link>https://medium.com/@PinakinMistry/path-to-jumpstart-with-javascript-249eae2d8deb?source=rss-95d85303f39d------2</link>
            <guid isPermaLink="false">https://medium.com/p/249eae2d8deb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Pinakin Mistry]]></dc:creator>
            <pubDate>Fri, 25 Sep 2015 17:20:15 GMT</pubDate>
            <atom:updated>2015-09-25T17:20:15.105Z</atom:updated>
            <content:encoded><![CDATA[<h2>Path</h2><h2>to</h2><h2>JumpStart</h2><h2>with</h2><h2>JavaScript</h2><p>Do you feel like making a start with something new? Are you lost as there is so many things to learn? Your battery has drained out and not giving you a start anymore? <strong>You need a Jumpstart.</strong></p><h2>Inspiration</h2><p><em>I was working on mainframe for 7 years. It was like fixing bulbs and doors in an old mansion to keep it going. There was no major engineering as the mansion was built already. I wanted to do more but couldn’t afford a mainframe of my own. It was time to start something new by stepping out of the safe mansion. I started with JavaScript and now I don’t have word ‘mainframe’ in my </em><a href="http://pinakinmistry.github.io/"><em>profile</em></a><em>. </em><strong><em>I rewrote it. And so can you.</em></strong><em> </em><strong><em>And trust me, there is no looking back thereafter.</em></strong></p><p>JavaScript has grown so much (web, desktop, mobile, TV, hardware, server) that it is now called <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9"><strong>Universal JavaScript</strong></a>. The language once known as toy language is now not just a language but also known as an <a href="https://dzone.com/articles/secrets-javascript-ninja"><strong>Ecosystem</strong></a><strong>.</strong></p><p>Here is must watch video on <strong><em>JavaScript is Everywhere</em></strong> by Douglas Crockford, father of JSON (JavaScript Object Notation).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyI8rYQtkwC4%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyI8rYQtkwC4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyI8rYQtkwC4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c80196fe0158e8d998d4a84303ae0bbe/href">https://medium.com/media/c80196fe0158e8d998d4a84303ae0bbe/href</a></iframe><p>You can do so many things with one single language. You can even step out of your usual <strong><em>app dev mode to programming anything mode</em></strong>, if you like to. <a href="http://www.infoworld.com/article/2953719/javascript/samsung-banks-on-javascript-node-js-for-iot.html?utm_source=javascriptweekly&amp;utm_medium=email"><strong>Samsung is banking on JavaScript as language for IoT (Internet of Things)</strong></a><strong>.</strong></p><h3>Path to JumpStart with JavaScript:</h3><p>The first month or two can be very daunting. And if you have put all your money into it (like me dumping my 7 years of mainframe experience), you might ask yourself what am I doing with my career (like I did that time). Just hang onto it and you will pass this phase. <strong><em>Change is Good.</em></strong></p><blockquote><strong>Here is my attempt to JumpStart you with JavaScript using my battery.</strong></blockquote><h3><strong>1. Learn JavaScript:</strong></h3><p><strong><em>JavaScript is a tiny language. Learn it instead of just using it.</em></strong> Because of its syntax similar to other languages, developers just start using it without feeling the need to learn it. In last 4 years of my interviews with JavaScript developers, I have heard only a few saying that they are learning the language besides using it. Please don’t take it for granted. JumpStart learning JavaScript with this <a href="https://github.com/ericelliott/essential-javascript-links#essential-javascript-links"><strong>list</strong></a><strong> </strong>by Eric Elliot.</p><h3>2. Don’t Take Shortcuts:</h3><p>Don’t jump onto frameworks/libraries to make your life easier. You will miss a lot of skills that the language is offering in its vanilla form. Frameworks and libraries hide away complex problems and their solutions in them and leave little for us to learn from the language. <strong><em>Frameworks/libraries come and go. What stays around is the language.</em></strong></p><h3>3. Grok Frameworks And Libraries Source Code:</h3><p>Don’t ignore frameworks/libraries altogether. They solve complex problems in best possible ways. <strong><em>They are written by experts and so reading their source code is one of the best ways to learn the language.</em></strong></p><h3>4. Contribute To Frameworks/Libraries:</h3><p>While you are at it, grokking the language more and more, you should start contributing to the frameworks and libraries. Some day you might write frameworks or libraries of your own.</p><h3>5. Learn ES.Next:</h3><p>ECMAScript 2015 (also called ES2015 or ES6) is the next and the most awaited version of JavaScript coming this year. With year in its name, we will get more such updates every year from now on. Guess what, ES2016/ES7 is already work in progress. <strong><em>Upcoming versions that are lining up are called ES.Next. These are coming one after the other with bigger and wider impacts. Most of the projects/frameworks/libraries will be written in ES.Next. So catch it before it catches you some day.</em></strong></p><h3>6. Pair With Other JavaScript Enthusiasts:</h3><p><strong><em>Though at #6, this has the most impact.</em></strong> This will keep you motivated all the time and will never let you drain away your battery. Strive to make a <strong>high velocity team explained </strong><a href="https://medium.com/javascript-scene/how-to-build-a-high-velocity-development-team-4b2360d34021"><strong>here</strong></a><strong>.</strong> Ultimately, it’s all about teamwork.</p><h3>7. Run Pet Projects:</h3><p><strong><em>Convert your ideas into reality. Pet projects will help you learn what you want to learn very quickly. So don’t wait until your regular project is over. </em></strong>Make them open source on Github for others to contribute. It’s time for your repos to get forked and receive pull requests.</p><h3>8. Follow Tech And People On Twitter:</h3><p>Follow technology and the people who are shaping the technology on Twitter. Get into network of people who are into what you are. This will keep you up to date on what’s latest and what’s happening around the world in things that you are interested in so that you can become part of it. This will keep you inspired and on track all the time.</p><h3>9. Write Blogs:</h3><p>Four years back, I was asked to write blog on JavaScript and I believed there was nothing to write about it. After following the language for some time, I realized there is so much to write. <strong><em>Get into habit of jotting down what you learn everyday and then converting them into blogs for others to learn from.</em></strong></p><h3><strong>10. Prepare Monthly Study Calendar:</strong></h3><p>Mark your calendar with what you want to study in each week for next 4 weeks and stick to it. Repeat this every month. You need to set some time out for doing this. Start with an hour a day on weekdays and few more hours on weekends and see how it goes.</p><h3>11. Run Meetups:</h3><p>Now you are reaching there with packets of knowledge to deliver. Meetup is a really good platform to share you knowledge and learn from others. Monthly meetups will help you set your monthly study calendar well and stick to it. Here is a <a href="http://www.meetup.com/JSChannel-Mumbai"><strong>meetup</strong></a> that I started recently.</p><h3>12. Speak At Conferences:</h3><p>Once you are on track, this will happen naturally. Aim to speak at conferences. And then, <strong><em>you will find yourself starting from step 1 and repeating all these over and over again.</em></strong></p><blockquote><strong><em>Don’t feel left behind. All you need is a JumpStart. Hang onto it and you will ride on it.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=249eae2d8deb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Closures — Long Live Locals]]></title>
            <link>https://medium.com/@PinakinMistry/javascript-closures-long-live-locals-93e1f6220dbe?source=rss-95d85303f39d------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e1f6220dbe</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Pinakin Mistry]]></dc:creator>
            <pubDate>Sat, 05 Sep 2015 16:05:59 GMT</pubDate>
            <atom:updated>2015-09-05T16:05:59.102Z</atom:updated>
            <content:encoded><![CDATA[<h2>JavaScript Closures</h2><h3>- Long Live Locals</h3><h4>Googling ‘closure’ gives you this TLDR version:</h4><p><em>In programming languages, a </em><strong><em>closure</em></strong><em> (also </em><strong><em>lexical closure </em></strong><em>or</em><strong><em> function closure</em></strong><em>) is a function or reference to a function together with a referencing environment — a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.</em></p><p>More often, it is also DFDC version (Didn’t Follow, Don’t Care) for folks new or not sure about Closures.</p><h3>Closure Simplified:</h3><p><em>Closure is formed when </em><strong><em>a function can remember and access its lexical scope even when it’s invoked outside of its lexical scope.</em></strong></p><p>Didn’t follow? Don’t worry. Many developers (include me in this list) don’t get it first time. Check this example:</p><pre>function <strong>outerFunction</strong>() {<br>    var <strong>outerVariable</strong> = ‘I am local to outerFunction’;<br> <br>     function <strong>innerFunction</strong>() { <strong>//This is a closure. Simple.</strong><br>         console.log(<strong>outerVariable</strong>); <strong>//It can access outer scope.</strong><br>     }<br> <br>     innerFunction();<br>}</pre><pre>outerFunction();</pre><p>JavaScript function gives rise to new scope. Nested function, innerFunction in above example, can access variables defined in its outer scope, like hot air balloon can access outside air. This can be nested to multiple levels forming spheres of scopes. The innermost scope has access to all its outer scopes.</p><p>Note that innerFunction is called from within its lexical scope which is outerFunction in this case. We will soon see how to call it outside of its lexical scope by returning reference to innerFunction from outerFunction.</p><h4><strong>What is this lexical scope now?</strong></h4><p>It’s called lexical because of the way the scope of a variable is defined by its location within the source code. The variable’s scope is apparent <em>lexically. </em>Thus when we nest function within function (to form a parachute, or a transformer, or a dream within dream), each having scope of its own, the local variables are lexically scoped in these spheres of scopes.</p><h4><strong>Globals are Immortal.</strong></h4><p>Global variables live the entire life span of the application and are not garbage collected (GC’ed). But due to shared namespace in JavaScript (window object in browser environment), we know the quirks of using globals and often resort to locals.</p><h4><strong>Locals are better but they die.</strong></h4><p>What a world it would be with all locals when they die as soon as the function holding them completes? Hot air is gone when balloon deflates. Locals are GC’ed once the function holding them completes. Check below example:</p><pre>function <strong>outerFunction</strong>() {<br>    var <strong>outerVariable</strong> = &#39;I am outside&#39;;<br>    <br>    function <strong>innerFunction</strong>() {     <br>       console.log(<strong>outerVariable</strong>);<br>    }<br>    <br>    innerFunction();<br>}</pre><pre>outerFunction();             //<strong>Logs &#39;I am local to outerFunction&#39;</strong><br>console.log(outerVariable); //<strong>Logs outerVariable is not defined</strong></pre><h4>How Locals can Live Longer?</h4><p>If we return reference of innerFunction from outerFunction, outerVariable won’t get GC’ed and can live longer.</p><pre>function <strong>outerFunction</strong>() {<br>    var <strong>outerVariable</strong> = &#39;I am local to outerFunction&#39;;<br>    <br>    return function <strong>innerFunction</strong>() {     <br>       console.log(<strong>outerVariable</strong>);<br>    };<br>}</pre><pre>var innerFunctionReference = outerFunction();</pre><pre><strong>//Calling innerFunction outside of its lexical scope:</strong><br>innerFunctionReference(); //<strong>Logs &#39;I am local to outerFunction&#39;</strong></pre><p>Inner function can hold onto variables defined in its outer scope as a reference to it is still alive. Mr. Garbage Collector lets them live longer.</p><p>Inner function can remember not just the variables defined in outer scope but also the arguments passed to its outer function. Run this and see it for yourself:</p><pre>var messages = [&#39;I&#39;, &#39;will&#39;, &#39;be&#39;, &#39;back&#39;];</pre><pre><strong>//Without closure:</strong><br>for(<strong>var</strong> i = 0; i &lt; messages.length; i++) {<br>    setTimeout(<strong>function</strong> () {<br>        console.log(messages[<strong>i</strong>]); <strong>//Logs ???</strong><br>    }, 1000);<br>}</pre><pre><strong>//With closure:</strong><br>for(<strong>var</strong> i = 0; i &lt; messages.length; i++) {<br>    (function (<strong>i</strong>) {                   <strong>//Closure holding onto i</strong><br>        setTimeout(<strong>function</strong> () {<br>            console.log(messages[<strong>i</strong>]); <strong>//Logs the popular message</strong><br>        }, 1000);<br>    })(<strong>i</strong>);<br>}</pre><p>Without closure, it logs undefined 4 times as the anonymous function passed to setTimeout doesn’t remember what was ‘i’ at the time it was set to timeout. It runs when i has reached 4 which is undefined in messages array.</p><p>With closure it works as expected because now it can hold onto value of variable ‘i’ in each iteration. Value of ‘i’ is locked into inner function (inner balloon) in the closure of outer function (outer balloon) we wrapped it into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*XDxzQHmFF7gkAC945hXbIA.jpeg" /><figcaption>Outer balloon forming closure to hold onto its inner balloon while looping</figcaption></figure><h4><strong>Why do we need Closure?</strong></h4><p>Why use closure when we can live without it? But what a world it would be to remind (pass arguments to) a function when it can remember things around it? Think about it. It can open doors to do lot more than what we have been doing right now.</p><h4>Benefits/Practical uses of Closure:</h4><ul><li>Create self sustained and persistent modules with public/private properties and methods.</li><li>Make semi-computations or currying to hold onto intermediate results to arrive at final/other results later. See My First Closure below.</li><li>Remembering/caching what happened last time that can be used in AI, Machine Learning, Parsers, etc.</li><li>Hold onto index while looping some asynchronous code.</li></ul><h4><strong>My First Closure:</strong></h4><p>Say you want to create a heatmap wherein days are columns and rows are stocks and each cell holds the stock price with color to indicate price fluctuation between high and low of that stock in that period. And say you want to do this for last nDays (nDays is user input) for 30 stocks.</p><p>That will be nDays X 30 computations to decide the color of the cell. What about min and max computation in this period as that needs to be calculated based on prices in that period? Would you do this minMax calculation nDays X 30 times. Nah! I used closure to make cellColor remember what min and max is for the given stock:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867a3039ab82545e414bcf3d4aefaac7/href">https://medium.com/media/867a3039ab82545e414bcf3d4aefaac7/href</a></iframe><h3>Care for Closure. Get closer to Closure :-)</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e1f6220dbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let there be ‘let’ in JavaScript]]></title>
            <link>https://medium.com/@PinakinMistry/let-there-be-let-in-javascript-6fd184f46f80?source=rss-95d85303f39d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fd184f46f80</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[scopes]]></category>
            <dc:creator><![CDATA[Pinakin Mistry]]></dc:creator>
            <pubDate>Mon, 24 Aug 2015 12:33:47 GMT</pubDate>
            <atom:updated>2015-08-25T06:50:28.474Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1995:</strong> Let there be <strong>‘var’</strong> in JavaScript. This problem, which is source of many other problems, is dated two decades old. It all started when JavaScript was created back then in matter of 10 days by Brendan Eich. And it exists even today which is why it’s super important to know more about it.</p><h4><strong><em>-1995-</em></strong></h4><ul><li><em>Let there be keyword </em><strong><em>‘var’</em></strong><em> to declare variables/references in JavaScript.</em></li><li><em>Let </em><strong><em>‘var’ be optional</em></strong><em> for JavaScript to be forgiving language for the beginners.</em></li><li><em>Let variables declared </em><strong><em>outside of a function be global</em></strong><em> i.e. accessible from anywhere and those declared </em><strong><em>inside of a function be local</em></strong><em> i.e. accessible only inside of function holding them. This is called </em><strong><em>scope</em></strong><em>.</em></li><li><em>Let variables be declared anywhere but get </em><strong><em>hoisted from top of enclosing scope</em></strong><em>.</em></li><li><em>Moreover, let there be </em><strong><em>‘no’ block scope</em></strong><em>. Only</em><strong><em> function can give rise to new scope which can even be nested to form closures</em></strong><em>.</em></li><li><em>And one more thing, let there be </em><strong><em>lexical scoping</em></strong><em> to </em><strong><em>access variables of outer scopes from inner scopes</em></strong><em> for closures to work.</em></li></ul><p>Back then, some of these design decisions were hasty while creating a brand new programming language that too in mere 10 days. Brendan Eich is a genius. But even genius can make mistakes when asked to rush.</p><p>Let’s see the problems related to ‘var’ one at a time in action:</p><pre><strong>//Problem #0: Let there be &#39;var&#39;:<br></strong>//-------------------------------</pre><pre><strong>var</strong> myVariable = <strong>&#39;I am global&#39;</strong>;<br>console.log(myVariable); <strong>//Logs &#39;I am global&#39;</strong></pre><pre>function myFunction() {<br>    <strong>var</strong> myVariable = <strong>&#39;I am local&#39;</strong>;<br>    console.log(myVariable); <strong>//Logs &#39;I am local&#39;</strong><br>}</pre><pre>myFunction();</pre><pre>console.log(myVariable); <strong>//Logs &#39;I am global&#39;</strong></pre><p>This is self explanatory with <strong>no visible problem</strong> at all so far.</p><h3><em>But, </em><strong><em>hidden problems </em></strong><em>related to ‘var’ creeped in right from the beginning.</em></h3><p>You can run below snippets in browser’s console to check these problems:</p><pre><strong>//Problem #1: &#39;var&#39; is optional:</strong><br>//------------------------------</pre><pre>myVariable = <strong>&#39;I am global&#39;</strong>;<br>console.log(myVariable); //Logs &#39;I am global&#39;</pre><pre>function myFunction() {<br>    myVariable = <strong>&#39;I am local&#39;</strong>;<br>    console.log(myVariable); //Logs &#39;I am local&#39;<br>}</pre><pre>myFunction();</pre><pre>console.log(myVariable); <strong>//Logs</strong> <strong>&#39;I am local&#39; instead.</strong></pre><p>Because ‘var’ is optional, myVariable inside myFunction appears to be declared/assigned as a local variable inside myFunction. But it is not the case. It is global and the change in its value is visible even outside of myFunction.</p><p><em>For folks coming from other languages, </em><strong><em>not using ‘var’ doesn’t lead to any error</em></strong><em> unless you use ‘use strict’ mode.</em></p><pre><strong>//Problem #2: Let variables be hoisted at top of enclosing scope:<br></strong>//---------------------------------------------------------------</pre><pre><strong>var</strong> myVariable = <strong>&#39;I am global&#39;</strong>;<br>console.log(myVariable); //Logs &#39;I am global&#39;</pre><pre>function myFunction() {<br>    //TDZone starts<br>    console.log(myVariable); <strong>//Logs ???</strong><br>    //TDZone ends<br>    <strong>var</strong> myVariable = <strong>&#39;I am local&#39;</strong>;<br>    console.log(myVariable); //Logs &#39;I am local&#39;<br>}</pre><pre>myFunction();</pre><pre>console.log(myVariable); //Logs &#39;I am global&#39;</pre><p>What will first log statement inside myFunction give? If you think the global myVariable is lurking around for you to use before the local version is declared, you are wrong. It gives ‘undefined’ as the local myVariable gets hoisted at the top of defining scope which is myFunction in this case. And as the local myVariable is yet to be assigned with a value, any attempt to use it in that TDZone in between will give rise to undefined value. That’s why this zone is called <strong>Temporal Dead Zone.</strong></p><pre><strong>//Problem #3: Let there be &#39;no&#39; block scope:<br></strong>//------------------------------------------</pre><pre><strong>var</strong> i = <strong>&#39;I am global&#39;</strong>;<br>console.log(i); //Logs &#39;I am global&#39;</pre><pre>for(<strong>var</strong> i = 0; i &lt; 5; i++) {<br>    //do whatever you want...<br>}</pre><pre>console.log(i); <strong>//Logs 5 instead.</strong></pre><p>Yes, it logs 5 instead of ‘I am global’ because there is no block scope. Variable ‘i’ declared inside for loop is visible even outside of it. Same will be the case if we had declared it inside while, do while, for and else blocks. <strong>Let’s</strong> call this as <strong>Accidentally Unblocked Problem</strong>.</p><p>Now, let’s see the most hidden and notorious problem that provides one of the most powerful feature of creating closures in JavaScript when applied knowingly and correctly:</p><pre><strong>//Problem #4: Let closure access variables from outer scope:<br></strong>//----------------------------------------------------------</pre><pre>var messages = [&#39;I&#39;, &#39;will&#39;, &#39;be&#39;, &#39;back&#39;];</pre><pre>for(<strong>var</strong> i = 0; i &lt; messages.length; i++) {<br>    setTimeout(<strong>function</strong> () {<br>        console.log(messages[<strong>i</strong>]); <strong>//Logs ???</strong><br>    }, 1000);<br>}</pre><p>This won’t log back the popular message we know of. It will log ‘undefined’ 4 times. Yes, undefined again. Why? Think about it.</p><p>Variable ‘i’ keeps running from 0, 1, 2, 3 and 4 whereas the calls to anonymous function (marked bold) given to setTimeout function in each iteration are left aside <strong>at least</strong> for 1 second. (This anonymous function is a closure and has access to variable ‘i’ (declared outside of it) with help of lexical scoping). And by the time their turn come, variable ‘i’ has reached 4 which is ‘undefined’ in messages array. Let’s call this as <strong>Runaway Problem </strong>as ‘i’ is running away and <strong><em>not holding its binding to each iteration</em></strong>. Clear enough but hidden enough to understand it first time.</p><p>If you give one more look to these problems, all of them are hidden due to those design decisions related to <strong>‘var’</strong>. We can’t change these rules now as they will break the web due to the existing JavaScript code written based on these rules. There is no turning back in time to rectify this.</p><p>So, <strong>‘let’’s</strong> look forward.</p><p><strong>Solution:</strong> Let there be <strong>‘let’</strong> in JavaScript.</p><h4><strong><em>-2015-</em></strong></h4><ul><li><em>Let there be </em><strong><em>‘let’</em></strong><em> in JavaScript to declare variables/references in a new way.</em></li><li><em>Using ‘let’ variables before their declaration will lead to </em><strong><em>ReferenceError</em></strong><em>. This will </em><strong><em>kill the Temporal Dead Zone itself </em></strong><em>(described in problem #2 above).</em></li><li><em>Let </em><strong><em>‘let’ variables have block scope</em></strong><em>. The scope of variables declared using ‘let’ is its enclosing block and not the whole enclosing function. This avoids </em><strong><em>Accidentally Unblocked Problem</em></strong><em> (described in problem #3 above).</em></li><li><em>Let ‘let’ variable declared inside loops </em><strong><em>have fresh binding in each iteration so that each iteration remembers its value</em></strong><em>. This will avoid the </em><strong><em>Runaway Problem</em></strong><em> (described in problem #4 above).</em></li></ul><h2>ES2015 is coming.</h2><h2>Let’s use let.</h2><p>You can run below snippets in <a href="https://babeljs.io/repl/#?experimental=false&amp;evaluate=true&amp;loose=false&amp;spec=true&amp;code=">babel</a> and see ‘let’ solving these problems:</p><pre><strong>//Problem #2 of Temporary Dead Zone solved with let:</strong><br>//--------------------------------------------------</pre><pre><strong>let</strong> myVariable = <strong>&#39;I am global&#39;</strong>;<br>console.log(myVariable); //Logs &#39;I am global&#39;</pre><pre>function myFunction() {<br>    //TDZone starts<br>    console.log(myVariable); <strong>//Gives not defined/ReferenceError</strong><br>    //TDZone ends<br>    <strong>let</strong> myVariable = <strong>&#39;I am local&#39;</strong>;<br>    console.log(myVariable); //Logs &#39;I am local&#39;<br>}</pre><pre>myFunction();</pre><pre>console.log(myVariable); //Logs &#39;I am global&#39;</pre><pre><strong>//Problem #3 of no block scope solved with let:<br></strong>//---------------------------------------------</pre><pre><strong>let</strong> i = <strong>&#39;I am global&#39;</strong>;<br>console.log(i); //Logs &#39;I am global&#39;</pre><pre>for(<strong>let</strong> i = 0; i &lt; 5; i++) {<br>    //do whatever you want...<br>}</pre><pre>console.log(i); <strong>//Logs &#39;I am global&#39;</strong></pre><pre><strong>//Problem #4 (Runaway Problem) solved using let:<br></strong>//----------------------------------------------</pre><pre>let messages = [&#39;I&#39;, &#39;will&#39;, &#39;be&#39;, &#39;back&#39;];</pre><pre>for(<strong>let</strong> i = 0; i &lt; messages.length; i++) {<br>    setTimeout(<strong>function</strong> () {<br>        console.log(messages[<strong>i</strong>]); <strong>//Logs the popular message</strong><br>    }, 1000);<br>}</pre><p><strong>‘let’</strong> was introduced in 2005 by Brendan Eich as panacea to these problems. Though it took ten years to reach ES2015 specs, it is finally coming.</p><p>ES2015 (also called ES6), specs for next version of JavaScript were released in June 2015, some time close to 20th birthday of JavaScript. It’s the best birthday gift JavaScript ever had. Be assured, more are coming soon that too every year from now on. That’s why they smartly put year in its new name.</p><h4><strong>-Conclusion-</strong></h4><h3>Let <strong>‘let’</strong> be the new <strong>‘var’</strong> here on!</h3><p>This doesn’t mean you can just find and replace all ‘var’ by ‘let’ as it may break something based on how the design flaws were accidentally put in use in the code. Best bet is to use ‘let’ whenever possible in the new ES2015 code you write.</p><h3>So, Keep Calm</h3><h3>&amp;</h3><h3>Let ‘let’ Help</h3><h3>You Stay Calm.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fd184f46f80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>