<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[codesips]]></title><description><![CDATA[Code snippets to quench your thirst 🍸]]></description><link>https://codesips.io/</link><image><url>https://codesips.io/favicon.png</url><title>codesips</title><link>https://codesips.io/</link></image><generator>Ghost 3.14</generator><lastBuildDate>Mon, 14 Oct 2024 09:04:10 GMT</lastBuildDate><atom:link href="https://codesips.io/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[JavaScript: Advance async patterns]]></title><description><![CDATA[JavaScript advance concurrent async patterns. ]]></description><link>https://codesips.io/javascript-async-patterns/</link><guid isPermaLink="false">5ed55b559b194f1722ef4fc1</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Mon, 01 Jun 2020 20:05:24 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1512103865222-dcf9531c9961?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1512103865222-dcf9531c9961?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Advance async patterns"><p>One of the best video tutorials about JavaScript async patterns is from Kyle Simpson. I watched this video about three years ago and it's still relevant today. </p><p>I am writing this post for myself to refer through the async concepts which are vital in writing JS applications.</p><p>Without further ado,</p><figure class="kg-card kg-embed-card"><iframe width="480" height="270" src="https://www.youtube.com/embed/Qg1SvpIau6U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p>In summary he talks about,</p><ol><li>Callbacks</li><li>Promises</li><li>async await</li><li>Observables (RxJS)</li><li>Communicating sequential processes (CSP)</li></ol><p>All of which can achieve the same results (concurrent async calls) but he shows how you can improve your code by adapting advance async patterns. </p><p>I thought it's good one to remember even if it out-dates in the future.</p>]]></content:encoded></item><item><title><![CDATA[S&P 500, FTSE 100 Indexes' Constituents Google Sheet]]></title><description><![CDATA[Excel download of S&P 500 and FTSE100 constituents and their real time performances.]]></description><link>https://codesips.io/s-p-500-ftse-100-indexes-constituents-google-sheet/</link><guid isPermaLink="false">5ed556dc9b194f1722ef4f81</guid><category><![CDATA[Investing]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Mon, 01 Jun 2020 19:44:08 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1544145945-8aef7094f151?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1544145945-8aef7094f151?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="S&P 500, FTSE 100 Indexes' Constituents Google Sheet"><p>For anyone looking for quick excel download of indexes like S&amp;P 500, FTSE 100 with real time price, change %, PE ratio and market cap information, I am posting a google sheet link that you can utilize for your work.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://docs.google.com/spreadsheets/d/1DPrL6uvg50Sx7RNQhKTcG_syhTWyTETKbgYvhWYGd1w/edit?usp=sharing&amp;usp=embed_facebook"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Indexes</div><div class="kg-bookmark-description">S&amp;P 500 Symbol,Name,Sector,Exchange,Price,Change,Percentage,PE,EPS,Market Cap
FLS,Flowserve Corporation,Industrials,NYSE
IVZ,Invesco Ltd.,Financials,NYSE
LB,L Brands Inc.,Consumer Discretionary,NYSE
AIV,Apartment Investment &amp; Management,Real Estate,NYSE
RHI,Robert Half International,Industrials,...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://ssl.gstatic.com/docs/spreadsheets/favicon3.ico" alt="S&P 500, FTSE 100 Indexes' Constituents Google Sheet"><span class="kg-bookmark-publisher">Google Docs</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://lh6.googleusercontent.com/j4XAI6WtfItsfS8jSovrfk01_eSIU0QcPN3uHO6qgt4oQbCPPIT_10anVm_Z0CCvHzOQsymksQ=w1200-h630-p" alt="S&P 500, FTSE 100 Indexes' Constituents Google Sheet"></div></a></figure><p>I use it for my own personal investing. I though it will be useful for the wider community. Let me know your thoughts and if you like anything to be added to the sheet please contact me. </p><p>I will be updating the sheet with latest information and adding more indexes as time goes. </p>]]></content:encoded></item><item><title><![CDATA[I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰]]></title><description><![CDATA[Pipeline decorator for your codebase 😇]]></description><link>https://codesips.io/pipeline-decorator-for-one-who-wants-to-use-pipeline-operator/</link><guid isPermaLink="false">5ec177b99b194f1722ef4a5a</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Sun, 17 May 2020 19:13:37 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1496318447583-f524534e9ce1?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1496318447583-f524534e9ce1?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰"><p>Few days back, I wrote an article about how helpful the Pipeline Operator could be for some use cases. </p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/two-javascript-experimental-features-that-im-already-dreaming-of-implementing-on-my-codebase/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Two JavaScript experimental features that I’m already dreaming of implementing on my codebase.</div><div class="kg-bookmark-description">Ever heard of AggregateError and Pipeline Operator (|&gt;)</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.png" alt="I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰"><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1542849187-5ec6ea5e6a27?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰"></div></a></figure><p>I shared this article on multiple forums and a lot of users from Reddit gave interesting thought, but one of them gave a rough sketch of writing pipeline decorator using curry. So I went ahead and gave it a try, and here I have it. I just thought it will be useful for anyone looking ways for writing cleaner code. </p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/var-kar/pipe-decorator"><div class="kg-bookmark-content"><div class="kg-bookmark-title">var-kar/pipe-decorator</div><div class="kg-bookmark-description">A pipe decorator(Pipeline Operator) with promise callbacks for JavaScript - var-kar/pipe-decorator</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.githubassets.com/favicons/favicon.svg" alt="I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰"><span class="kg-bookmark-author">var-kar</span><span class="kg-bookmark-publisher">GitHub</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://avatars3.githubusercontent.com/u/26141562?s=400&amp;v=4" alt="I made Pipeline Decorator for one who wants to use Pipeline Operator in JavaScript 🚰"></div></a></figure><p>It is a very tiny library with only 45 lines of code. It has room for loads of improvements. I welcome you to contribute to the codebase or you can use this decorator with your favourite libraries like lodash, underscore etc.</p><h3 id="syntax">Syntax</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">pipe(arity)(Function)...();</code></pre><figcaption>Pipeline Decorator&nbsp;</figcaption></figure><p>Notice how it ends with an empty invocation, this will make sure it returns the result. </p><p>I knew similar functionality exists with libraries like RamdaJS. But, I just thought it will be good to learn and create a smaller library than Ramda. </p><h3 id="promise">Promise</h3><p>The library also handles promise, for example, you can do pre and post-processing of data along with <code>Promise</code> to make it more useful.</p><!--kg-card-begin: html--><script src="https://gist.github.com/var-kar/f671ec0cc7b30a46a51c5c034dd65c4b.js"></script><!--kg-card-end: html--><p>Notice how step 2 passes two arguments to <code>_.difference</code> function and notice step 4, get results from <code>Promise</code> and pass it on to <code>_.filter</code> function along with the email to be found as a second argument.   </p><h3 id="use-cases">Use cases</h3><ol><li>Makes your code clean and easy to read</li><li>Better than chaining or at least in my opinion</li><li>Makes multiple Promise handling much cleaner and readable. </li><li>Pre and post-processing of data for a promise gets easier and cleaner.</li></ol><h3 id="summary">Summary</h3><p>It's always good to share with a wider JavaScript community to get a different perspective. I'm for sure going to give it a try on my next project to reduces the number of lines of code I write. </p><p>I welcome you to contribute and make it even more useful covering more use cases. </p><p>Finally, please share your thought. Thank you. </p>]]></content:encoded></item><item><title><![CDATA[JavaScript: How to construct a Perpetual Curry function.]]></title><description><![CDATA[Let's make some JavaScript curry. Yummy 🤤]]></description><link>https://codesips.io/javascript-currying-perpetual-currying/</link><guid isPermaLink="false">5ebc264c9b194f1722ef4873</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Wed, 13 May 2020 20:29:36 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1585937421612-70a008356fbe?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1585937421612-70a008356fbe?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: How to construct a Perpetual Curry function."><p>In JavaScript Currying is a technique to translate a function which takes multiple arguments into a sequence of functions which takes single argument yet producing the same result.</p><h3 id="why-do-we-need-it">Why do we need it?</h3><ol><li>In functional programming, it provides a way of managing arguments to a function. Helps you deal with only one argument at a time.</li><li>It decorates your code by reducing the number of arguments supplied to a function directly.</li></ol><h3 id="how-does-it-look">How does it look?</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">// Simple function with multiple arguments
function sum(a, b) {
    return a + b;
}
console.log(sum(1, 2)); //Output: 3

// Function with returning sequencial function that takes one argument - Curry
function sum(a) {
    return function(b) {
    	return a + b;
    };
}
console.log(sum(1)(2)); //Output: 3</code></pre><figcaption>Currying in JavaScript</figcaption></figure><p>Notice that instead of returning the sum of <code>a</code> and <code>b</code> we return an anonymous function which takes <code>b</code> as an argument. This gets immediately invoked upon return when we do <code>sum(1)(2)</code>.</p><p>One has to ask a big question here. How does the scope of variable <code>a</code> available to the inner anonymous function that gets invoked later 🤯?</p><p>The answer is very simple, its JavaScript Closures. If you haven't read my previous post about closures, please do.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/javascript-closures/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">JavaScript: Closures</div><div class="kg-bookmark-description">Hide your secrets 😉</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.png" alt="JavaScript: How to construct a Perpetual Curry function."><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1559443922-3f698a0ff27a?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: How to construct a Perpetual Curry function."></div></a></figure><h3 id="perpetual-curry">Perpetual Curry</h3><p>You can make the above curry technique by infinitely returning a function which takes one argument and accumulate the result till you say its enough. Something like,</p><pre><code class="language-JavaScript">sum(1)...(n)() //Output: Sum of n numbers</code></pre><p>Let's get to the crux,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">function perpetualCurry() {

    return (() =&gt; {
    
        return perpetualCurry(); // Recursive
  
    });
}

console.log(perpetualCurry()()()()()()()) // Output: [Function] </code></pre><figcaption>Simplified perpetual curry function</figcaption></figure><p>Writing a perpetual curry function is kind of writing a recursive function. The only difference is that for every recursion, our function will return another function. The above function <code>perpetualCurry</code> will always return an anonymous function that can be invoked  immediately. This is how a basic infinite curry is constructed.</p><p>Let's make the above <code>perpetualCurry</code> function a bit more useful that does our <code>sum()</code>. Something like,</p><pre><code class="language-JavaScript">sum = (x, y) =&gt; x + y;
perpetualCurry(sum)(1)(2)(3)(4)(5)(); //Output: 15</code></pre><p>Notice how we end the infinite curry, and notice how the first invocation takes a function as an argument. </p><p>But before our function gets too complex to understand let do one more stage of problem break down. Let's accumulate all our arguments and return it as an array. Also, try and end the infinite loop and return accumulated arguments.</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">function perpetualCurry() {

    const curryWrapper = ((...args) =&gt; {
    	
        return (() =&gt; {
            if (!x) { // If no argument supplied, It ends the infinite curry
                return args;
            }
            return curryWrapper(...args, x); //Recursive, Accumulate args
        })
  
    });
    
    return curryWrapper();
}

perpetualCurry()(1)(2)(3)(4)(5)(); // Output: [1,2,3,4,5]</code></pre><figcaption>Accumulating arguments</figcaption></figure><p>See how we added another layer of function called <code>curryWrapper()</code>. Notice on our recursion code how we use spread operator and accumulate our arguments. The first invocation is reserved for passing the <code>sum()</code> function that can be used with <code>call</code> or <code>apply</code> to return our desired result.</p><p>Let's do our final <code>perpetualCurry()</code> function that will return our desired result.</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">sum = (x, y) =&gt; x + y;


function perpetualCurry(fn) {

    const curryWrapper = ((...args) =&gt; {
        return ((i) =&gt; {
            if (!i) {
                //Only new thing
                return args.reduce((accmulate, arg) =&gt; {
            	    return fn.call(null, accmulate, arg);
                }); 
            }
            return curryWrapper(...args, i);
        })
    });
    
    return curryWrapper(0);
}

perpetualCurry(sum)(1)(2)(3)(4)(5)(); //Output: 15</code></pre><figcaption>Final perpetual curry function</figcaption></figure><p>The only new addition to the function is the <code>reduce</code> code block with <code>fn.call</code>. The <code>reduce()</code> just accumulates your result by executing our <code>sum.call()</code> by passing two arguments at a time to that function. Finally the <code>reduce()</code> returns the result of all addition when it reaches the end of <code>args</code> array.</p><p>If you would like to read more about <code>reduce</code> and <code>call</code> I have added their MDN links at the bottom.</p><p>One of the most popular libraries written with this technique is, <a href="https://ramdajs.com/">https://ramdajs.com/</a></p><p>Voila! we reached to the end of this post.</p><h3 id="ideas-to-further-improve">Ideas to further improve</h3><ol><li>Accommodate more varied data types like inputting other functions, arrays, objects instead of just numbers.</li><li>Curry async/await or Promise methods.</li><li>Or a combination of all of the above.</li></ol><h3 id="summary">Summary</h3><ol><li>Curry technique can make your code clean and reduce complexity for functional programming as it deals with one argument at a time.</li><li>You can extend currying by infinitely returning a curried function.</li><li>You can reduce the number of line of code on your project by making the perpetual curry function take any datatype as argument. </li></ol><h3 id="references">References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Currying">https://en.wikipedia.org/wiki/Currying</a> </li><li><a href="https://codeburst.io/perpetual-currying-in-javascript-5ae1c749adc5">https://codeburst.io/perpetual-currying-in-javascript-5ae1c749adc5</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call</a></li></ol>]]></content:encoded></item><item><title><![CDATA[The only terminal emulator you need for your development on Windows.]]></title><description><![CDATA[Please don't waste time by searching around for a terminal emulator for Windows. ]]></description><link>https://codesips.io/the-only-terminal-emulator-you-need-for-your-development-on-windows/</link><guid isPermaLink="false">5ebaf60b9b194f1722ef4830</guid><category><![CDATA[Opinion]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Tue, 12 May 2020 19:32:07 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1497990902153-c6d041aad676?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1497990902153-c6d041aad676?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="The only terminal emulator you need for your development on Windows."><p>There are so many terminal emulators available for windows, but I have been using this lesser known terminal that no one would probably given it a try.</p><h3 id="git-bash">Git Bash</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://gitforwindows.org/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Git for Windows</div><div class="kg-bookmark-description">We bring the awesome Git VCS to Windows</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://gitforwindows.org/favicon.ico" alt="The only terminal emulator you need for your development on Windows."></div></div><div class="kg-bookmark-thumbnail"><img src="https://gitforwindows.org/img/gw1web_thumb.png" alt="The only terminal emulator you need for your development on Windows."></div></a></figure><p>You can do all linux based commands, colour coded, tab complete and all the good things that you can get from a linux or mac terminal or at least close to.</p><p>Drawbacks,</p><ol><li>No regular ctrl+c and ctrl+v for copy and paste.</li><li>No multiple tabs</li><li>No multiple screen option. </li></ol><p>But you can get around these by other means. </p><p>So, Get Bash is the only terminal emulator you need for Windows or at least in my opinion ;)</p><p>Thats all I have for today.</p>]]></content:encoded></item><item><title><![CDATA[Two JavaScript experimental features that I'm already dreaming of implementing on my codebase.]]></title><description><![CDATA[Ever heard of AggregateError and Pipeline Operator (|>)]]></description><link>https://codesips.io/two-javascript-experimental-features-that-im-already-dreaming-of-implementing-on-my-codebase/</link><guid isPermaLink="false">5eb8233c9b194f1722ef46ac</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Opinion]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Sun, 10 May 2020 17:24:14 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1542849187-5ec6ea5e6a27?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<h2 id="aggregateerror-">AggregateError()</h2><img src="https://images.unsplash.com/photo-1542849187-5ec6ea5e6a27?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Two JavaScript experimental features that I'm already dreaming of implementing on my codebase."><p>AggregateError object takes multiple iterable <code>Error</code> instances and wraps them in a single error.</p><h3 id="syntax">Syntax?</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">AggregateError(Array&lt;Error&gt;, "message");</code></pre><figcaption>AggregateError Syntax</figcaption></figure><h3 id="how-to-throw-an-aggregateerror">How to throw an AggregateError?</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">throw new AggregateError([
    new Error("Required field missing");
    new TypeError("Looking for string by array found");
], "All errors in your operation");</code></pre><figcaption>Throw an AggregateError</figcaption></figure><h3 id="how-to-catch-an-aggregateerror">How to catch an AggregateError?</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">try {
    throw new AggregateError([
        new Error("Required field missing");
        new TypeError("Looking for string by array found");
    ], "All errors in your operation");
} catch(e) {
    console.log(e instanceof AggregateError); //true
    console.log(e.message) //All errors in your operation
    console.log(e.name) //AggregateError
    console.log(e.errors); // [Error: "Required field missing", Error: "Looking for string by array found"]
}</code></pre><figcaption>Catching an AggregateError</figcaption></figure><h3 id="use-cases">Use cases</h3><ol><li>During <code>Promise.all</code> or <code>Promise.any</code> all errors from all async operations can be caught with a single error object. Helps you provide detailed error messages.</li><li>If you are an API developer, you can collect all validation errors in an array for a call and report it once, instead of going for a round trip. Most of you may already do it with different ways, AggregateError makes it easy by instantiating one object for each request and lets you collect many errors from ACLs, Authentication, Validation etc.</li><li>You don't have to interrupt an execution in the middle by throwing an Error object. You can let it pass and collect all errors in an array and finally deal with the errors if at all required.</li></ol><h3 id="mdn-docs">MDN Docs</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError"><div class="kg-bookmark-content"><div class="kg-bookmark-title">AggregateError</div><div class="kg-bookmark-description">The AggregateError object represents an error when several errors need to be wrapped in a single error.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://developer.mozilla.org/static/img/favicon144.e7e21ca263ca.png" alt="Two JavaScript experimental features that I'm already dreaming of implementing on my codebase."><span class="kg-bookmark-publisher">MDN Web Docs</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://developer.mozilla.org/static/img/opengraph-logo.72382e605ce3.png" alt="Two JavaScript experimental features that I'm already dreaming of implementing on my codebase."></div></a></figure><h2 id="pipeline-operator">Pipeline Operator</h2><p>Functions with a single parameter, the value of a parameter can be piped into a function. </p><h3 id="syntax-1">Syntax</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">expression |&gt; function</code></pre><figcaption>Syntax for Pipeline Operator</figcaption></figure><h3 id="example">Example</h3><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">-5 |&gt; Math.abs; // Output: 5</code></pre><figcaption>Pipeline Operator Example</figcaption></figure><h3 id="chaining">Chaining</h3><p>Let's take an underscore.js library's example,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];

stooges |&gt; reverse |&gt; last; //Output: {name: 'curly', age: 25}</code></pre><figcaption>Chaining with Pipeline Operator</figcaption></figure><p>With this new way of chaining methods in JavaScript, it gets rid of the whole debate about weather method chaining is a good practice or not.</p><h3 id="unknowns">Unknowns</h3><ol><li>As it takes only one parameter, do they allow more complex syntax? Like,</li></ol><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var names = ["John", "Sam", "Dave", "Bob"];
var age = [30, 16, 27, 35];
var getAgeFor = "Sam";

var ageOfSam = age[getAgeFor |&gt; names.indexOf];


</code></pre><figcaption>Pipeline operator inside array index syntax</figcaption></figure><p>2. Can they play a role in async/await functions? Imagine how clean the code will look.</p><p>3. Can they also play a role for generator functions?</p><h3 id="mdn-docs-1">MDN Docs</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Pipeline_operator"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Pipeline operator</div><div class="kg-bookmark-description">The experimental pipeline operator | (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://developer.mozilla.org/static/img/favicon144.e7e21ca263ca.png" alt="Two JavaScript experimental features that I'm already dreaming of implementing on my codebase."><span class="kg-bookmark-publisher">MDN Web Docs</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://developer.mozilla.org/static/img/opengraph-logo.72382e605ce3.png" alt="Two JavaScript experimental features that I'm already dreaming of implementing on my codebase."></div></a></figure><h3 id="summary">Summary</h3><ol><li>AggregateError helps you collect all Error objects as one object.</li><li>Pipeline Operator makes calling functions with single parameter clean and helps you chain methods.</li></ol>]]></content:encoded></item><item><title><![CDATA[JavaScript: Function Hoisting]]></title><description><![CDATA[Hoist a function now. ;)]]></description><link>https://codesips.io/javascript-function-hoisting/</link><guid isPermaLink="false">5eb7de4f9b194f1722ef45cc</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Sun, 10 May 2020 15:37:55 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1536599424071-0b215a388ba7?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1536599424071-0b215a388ba7?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Function Hoisting"><p>On our previous post, we looked at variable hoisting. In this post, we will take a look at function hoisting, which is part two of JavaScript Hoisting concept and part of our JavaScript basic concept series. </p><p>Let's start with a code example,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">foo(); //Output: Hello world

function foo() {
	console.log("Hello world")';
}</code></pre><figcaption>Function declaration hoisted</figcaption></figure><p>The above way of writing a method with a <code>function</code> keyword is called a function declaration. </p><p>Function declarations are always hoisted by JavaScript in its existing scope. And you can see that the function <code>foo()</code> is available before its declaration.</p><p>You can write a function in another way and its called function expression. With function expression, you declare an anonymous function and assign it to a variable. Let's see that with a code example.</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">foo(); // Reference Error": 'foo' is not a function

var foo = function() {
	console.log("Hello world");
}

or in ES6

let foo = () =&gt; {
	console.log("Hello world");
}</code></pre><figcaption>Function expression do not get hoisted</figcaption></figure><p>Function expression on both ES5 and ES6 will not get hoisted. The variable declaration will get hoisted but without a function assignment. The interpretation of the above code by JavaScript will be,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var foo;
foo(); //Referance Error: 'foo' is not a function
console.log(foo); //Output: undefined

var foo = function() {
	console.log("Hello world");
}</code></pre><figcaption>JavaScript interpretation of function expression</figcaption></figure><h3 id="es6-classes">ES6 Classes </h3><p>The data type of an ES6 class is a Function. So, classes behave the same as function when it comes to hoisting. Class declarations are hoisted and Class expressions are not.</p><p>There is one extra rule with class declarations, you have to declare a class before you can use it. Let's take a look,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var rectangle = new Rectangle(10, 5, 5); // Reference Error: Cannot access 'Rectangle' before initialisation 
class Rectangle {
	constructor(length, width, height) { 
    	this.length = length;
        this.width = width;
        this.height = height;
    }
    volume() {
    	return this.length * this.width * this.height;
    }
    area() {
    	return this.length * this.width;
    }
}</code></pre><figcaption>Class declaration hoisting</figcaption></figure><p>The fact that the error is "initialisation" error and that it is not a 'is not defined' error, proves that JavaScript can see its definition hence it is hoisted. </p><p>Same as function expression, class expressions are not hoisted. </p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var rect = new Rectangle(10, 5, 5); // Type Error: Rectangle is not a constructor
var Rectangle = class Rectangle {
	constructor(length, width, height) { 
    	this.length = length;
        this.width = width;
        this.height = height;
    }
    volume() {
    	return this.length * this.width * this.height;
    }
    area() {
    	return this.length * this.width;
    }
}</code></pre><figcaption>Class expression do not hoist</figcaption></figure><h3 id="summary">Summary</h3><ol><li>Function and ES6 Class declarations are hoisted.</li><li>Function and ES6 Class expressions are not hoisted.</li><li>ES6 <code>let</code> and <code>const</code> hoist the same way as <code>var</code> does.</li></ol>]]></content:encoded></item><item><title><![CDATA[Deep Render: New ways of looking at tech amazes me!]]></title><description><![CDATA[Deep Render: A startup optimising image & video compression in a unique way.]]></description><link>https://codesips.io/new-ways-of-looking-at-tech/</link><guid isPermaLink="false">5eb70bab9b194f1722ef44e9</guid><category><![CDATA[Opinion]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Sat, 09 May 2020 20:54:16 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1558645836-e44122a743ee?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1558645836-e44122a743ee?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Deep Render: New ways of looking at tech amazes me!"><p>Despite a lot of advancements and optimizations on all technological fronts, image compression techniques have not changed a lot for more than 30 years (in the case of JPEG). Or at least their progress is very slow. </p><p><a href="https://techcrunch.com/2020/05/07/deep-render/">https://techcrunch.com/2020/05/07/deep-render/</a></p><blockquote>Deep Render's founders claim that they are completely reinventing compression for images and videos and optimise more than 50% in size with better quality! </blockquote><p>They claim that they achieve this by optimising the colour, hue and saturation details of an image to what human eye can see and grasp and getting rid of all other details. And they do this optimisation using AI &amp; ML.</p><p>This is insanely blows my mind. Just imagine more than 50% of worlds storage capacity will be freed up overnight or it will take half the time to send good images of space from light-years away!</p><p>There are still a lot of unanswered questions that puzzles me. Some of them are, after optimisation do they then compress into JPEG or a completely new file format? If they are completely new format how quickly do current rendering devices and browsers adapt to this new file format? How do transparencies look? Is this lossy technique good enough for medical sciences or space?</p><p>Till I get those answers, I will be keenly watching Deep Render's progress.</p><p>I wish Deep Render's founders a very good luck for this important cause.</p>]]></content:encoded></item><item><title><![CDATA[JavaScript: Variable Hoisting]]></title><description><![CDATA[Hoist your JavaScript Flag!]]></description><link>https://codesips.io/javascript-variable-hoisting/</link><guid isPermaLink="false">5eb56c379b194f1722ef40d7</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Sat, 09 May 2020 19:17:07 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1562708294-4df93280352d?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1562708294-4df93280352d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Variable Hoisting"><p>On our basic concepts of JavaScript series of posts, let's take a look at Variable Hoisting.</p><p>JavaScript moves variables and functions declaration to the top of its scope during execution. This behaviour in JavaScript is called Hoisting. Let's see that with a code example,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">console.log(foo); // Output: undefined
var foo = "hello world";</code></pre><figcaption>Variable Hoisting Example</figcaption></figure><p>In any other programming languages, the expected output for the above code would be some sort of "foo not declared error". But in JavaScript, it is already declared with the type of <code>undefined</code>. This is because JavaScript interprets the above code like,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var foo;
console.log(foo); // Output: undefined
foo = "hello world";</code></pre><figcaption>Interpretation of Variable Hoisting by JavaScript</figcaption></figure><p>It takes all <code>var</code> declaration to the top of its scope and this is called variable hoisting. </p><h3 id="why-we-should-learn-hoisting">Why we should learn Hoisting?</h3><p>Because it will create a lot of unexpected behaviour during execution. On my previous posts, we looked into Closures and how they create a local scope whenever you declare a function. Let's take a look at this example to see how Hoisting breaks that rule when you don't declare the variable with <code>var</code> keyword,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">function foo() {
    bar = "Hello world";
    var baz = "I'm new to coding";
}
foo();
console.log(bar); //Output: Hello world
console.log(baz); //Reference Error: baz is not defined</code></pre><figcaption>Breaking Closure without var keyword</figcaption></figure><p>notice we haven't used <code>var</code> keyword in front of declaration <code>bar</code>. JavaScript first looks for its variable declaration on its local scope. If it can't find a local declaration, it goes up one level in scope and looks for <code>bar</code> declaration. On the above example, one level up to <code>foo()</code> scope is global scope. If it can't find in its parent scope it automatically declares your variable with <code>var</code> keyword like,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var bar;
function foo() {
    bar = "Hello world";
    var baz = "I'm new to coding";
}
foo();
console.log(bar); //Output: Hello world
console.log(baz); //Reference Error: baz is not defined</code></pre><figcaption>Interpretation of variable hoisting on a scope</figcaption></figure><p>and no matter how deep the foo function scope is, JavaScript will keep looking at its parent scopes till it finds or declares <code>bar</code> variable. </p><h3 id="es6-declarations">ES6 Declarations</h3><p>What happens to <code>let</code> and <code>const</code> keywords of ES6? Do they get hoisted? For that let's see what they output if you just declare them and don't assign a value same like what the <code>var</code> variables gets hoisted.</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">let foo;

console.log(foo); Output: undefined

const bar; //Syntax error: missing initializer in const declaration
</code></pre><figcaption>ES6 let keyword hoisting</figcaption></figure><p>so let's see if JavaScript hoist <code>let</code> and <code>const</code></p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScrit">console.log(foo); //Output: undefined
let foo = "Hello world";

console.log(bar); //ReferanceError: cannot access bar before initialization
const bar = 200;</code></pre><figcaption>ES6 let and const keyword hoisting</figcaption></figure><p>the fact that both the variables are available to <code>console.log</code> proves that they too get hoisted. But in the case of <code>const</code>, it is different. Declaring <code>const bar;</code> without assignment produces SyntaxError, because of this JavaScript hoist them but doesn't allow you to access the <code>const</code> variable before its initialization. So yes, they too gets hoisted. </p><p>To keep the post small and concise, I am splitting variable and function hoisting into two posts.  </p>]]></content:encoded></item><item><title><![CDATA[JavaScript: Self-invoking anonymous function blocks]]></title><description><![CDATA[Warning: long post ahead! 😒]]></description><link>https://codesips.io/javascript-self-invoking-anonymous-functions/</link><guid isPermaLink="false">5eb569cb9b194f1722ef40d3</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Fri, 08 May 2020 20:47:19 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1551024709-8f23befc6f87?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1551024709-8f23befc6f87?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Self-invoking anonymous function blocks"><p>We have learnt scopes and closures in JavaScript with my previous posts. Combining these two core concepts, JavaScript gives us a beautiful syntax called self-invoking anonymous functions. It simply means an unnamed function that executes itself. This special syntax can give us some extraordinary powers 💪,</p><ol><li>Power to expose only selected set of variables and methods to its outer scope.</li><li>Power to close down on variable and method name clashes with other code blocks or third party libraries.</li><li>Power to control JavaScript asynchronous executions. </li><li>With all the above powers, comes the greater responsibility of writing your open source libraries for JavaScript using self-invoking anonymous function blocks. </li></ol><p>Now let's take a look at its syntax. It's very simple.</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">(function() {

})()</code></pre><figcaption>Syntax of self-invoking anonymous function</figcaption></figure><p>The syntax is self-explanatory. Why self-invoking? Because the last <code>()</code> brackets executes the function. Why anonymous? Because the function doesn't have a name. You can have as many anonymous functions as you want in JavaScript. </p><blockquote>One rule to declare anonymous functions is to have a wrapping <code>()</code> brackets. In other words, you can pass an anonymous function where ever you see a wrapping <code>()</code> brackets. Eg,</blockquote><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">function executeAnonymousFunction(fn) {
	fn(); //Prints hello world when our anonymous function gets invoked at this place. 
}
executeAnonymousFunction(function() { // Note: anonymous fn passed as parameter
	console.log("Hello world");
});

or

setTimeout(function() {
	console.log("hello world"); //prints hello world after 1 second.
}, 1000);</code></pre><figcaption>Anonymous functions within ()</figcaption></figure><p>Now let's take a look at how self-invoking anonymous functions or self-executing anonymous functions give you all the powers that we talked about earlier.</p><h3 id="power-to-expose-a-selected-set-of-variables-and-methods-to-the-outer-scope-">Power to expose a selected set of variables and methods to the outer scope.</h3><p>Let's take a code example,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var myLibrary = (function() {
  var privateVariable = "I'm a private variable";
  var publicVariable = "I'm a public variable"
  
  function privateMethod() {
    console.log("I'm a private method");
  }
  function publicMethod() {
    console.log("I'm a public method and I have access to:");
    console.log(privateVariable);
    console.log(privateMethod());
  }

  // Expose only public items
  return {
    publicMethod: publicMethod,
    publicVariable: publicVariable
  }
})();

myLibrary.publicMethod(); // Prints all console.logs
console.log(myLibrary.publicVariable); // Prints I'm a public variable

console.log(myLibrary.privateVariable); // undefined
myLibrary.privateMethod(); // Uncaught TypeError: myLibrary.privateMethod is not a function</code></pre><figcaption>Encapsulate methods and variables</figcaption></figure><p>You can see that the private methods and variables are well encapsulated within our anonymous function, make themselves available within the block, but not outside.</p><h3 id="power-to-close-down-on-variable-and-method-name-clashes-with-other-code-blocks-or-third-party-libraries-">Power to close down on variable and method name clashes with other code blocks or third party libraries.</h3><p>Again let's look this through code example,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">var myLibraryOne = (function() {
    var bar = "Hello world"; // same variable name 
    function foo() { // same method name
    	console.log(bar);
    }
    // some other operations
    return foo;
})();
var myLibraryTwo = (function() {
    var bar = "Hello world"; // same variable name
    function foo() { // same method name
    	console.log(bar); 
    }
    // some other operations
    return foo;
})();</code></pre><figcaption>Prevents variable and method name clashes</figcaption></figure><p>Both of those self-executing anonymous functions have same-named variables and methods. But they never complain that the variable is already declared. Thus it avoids clashes with other libraries and code blocks. </p><h3 id="power-to-control-javascript-asynchronous-executions-">Power to control JavaScript asynchronous executions.</h3><p>Let's take this code,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">for (var i = 0; i &lt; 5; i++) {
    setTimeout(function() { // asynchronous operation
    	console.log(i);
    }, 1000 * i);
}</code></pre><figcaption>Asynchronous code with bug</figcaption></figure><p>I have been asked this exact question in many interviews. Anyone assessing the code would think the <code>console.log</code> will print,</p><pre><code>prints: 0 // after 0 second
prints: 1 // after 1 second
prints: 2 // after 2 seconds
prints: 3 // after 3 seconds
prints: 4 // after 4 seconds</code></pre><p>And if you have answered the above, the interviewer might have kicked you out of the door! And if he doesn't, you please kick him out.</p><p>The answer for the above code is quite different and it is,</p><pre><code>prints: 5 // after 0 seconds
prints: 5 // after 1 seconds
prints: 5 // after 2 seconds
prints: 5 // after 3 seconds
prints: 5 // after 4 seconds</code></pre><p>Yes, it prints '5' five times at various intervals! </p><p>This is because the JavaScript event loop executes the code in a unique order. It priorities synchronous operations (in this code example it is the <code>for</code> loop) over asynchronous operations. So, the <code>for</code> loop registers all <code>setTimeout</code> for later execution. By the time <code>for</code> finishes, the value for variable <code>i</code> is <code>5</code> in the memory. Then comes the asynchronous operations like <code>setTimeout</code>. And this is why the <code>console.log</code> can only read <code>5</code> for variable <code>i</code> from the memory.</p><p>How can we fix this? The magic power here is the self-invoking anonymous functions. How is it going to help? let's take a look,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">for (var i = 0; i &lt; 5; i++) {
    (function(i) {
        setTimeout(function() { // asynchronous operation
            console.log(i);
        }, 1000 * i);
    })(i); // This is how we pass parameters to self-invoking functions
}</code></pre><figcaption>Asynchronous code fixed with self-invoking anonymous function</figcaption></figure><p>The above code will print exactly the result we wanted,</p><pre><code>prints: 0 // after 0 second
prints: 1 // after 1 second
prints: 2 // after 2 seconds
prints: 3 // after 3 seconds
prints: 4 // after 4 seconds</code></pre><p>Self-invoking anonymous functions give an individual private scope of <code>i</code> for each <code>setTimeout</code> we register to JavaScript event loop or eval loop. It means we have five times <code>i</code> declared with different values from 0 to 4 in the memory, each with its scope wrapped. Pure magic 🧝‍♀️!</p><p>In real-world project building, you might be asked to write a code to fetch a list of songs from an API and for each song, you will be asked to fetch its artist name using a different API. Something like this,</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">fetchSongsList(function(songs) {
    for (var songIndex=0; songIndex &lt;= songs.length; songIndex++) {
    	fetchSongArtistBySongId(songs[songIndex].id, function(artist) {
            //Artist for song blah blah.
        });
    }
});</code></pre><figcaption>Real world example - bug</figcaption></figure><p>If you are following my post keenly, you would have immediately caught what's wrong with the above code. How to fix it? With the magic self-invoking anonymous function voila!</p><figure class="kg-card kg-code-card"><pre><code class="language-JavaScript">fetchSongsList(function(songs) {
    for (var songIndex=0; songIndex &lt;= songs.length; songIndex++) {
        (function(song){
            fetchSongArtistBySongId(song.id, function(artist) {
                //Artist for song blah blah.
            });
        })(song);
    }
});</code></pre><figcaption>Fixed code with self-invoking asynchronous function</figcaption></figure><p>Last but not least,</p><h3 id="power-of-writing-your-libraries">Power of writing your libraries</h3><p>Great soles who wrote popular libraries like <a href="https://jquery.com/">JQuery</a>, <a href="https://underscorejs.org/">underscore </a>or <a href="https://lodash.com/">lodash</a> would have started writing their first line of code with self-invoking anonymous function for their libraries. Request you to go and read the open-source library's codebase. You can learn a lot more from them.</p><p>Now that you know everything about it, you have the power to start writing your JavaScript library. </p><p>If you have reached this far, precious 💍 things in life will find your way.</p><p>With that note, adios.</p>]]></content:encoded></item><item><title><![CDATA[JavaScript: Closures]]></title><description><![CDATA[Hide your secrets 😉]]></description><link>https://codesips.io/javascript-closures/</link><guid isPermaLink="false">5eb450449b194f1722ef3f81</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Thu, 07 May 2020 19:56:41 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1559443922-3f698a0ff27a?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1559443922-3f698a0ff27a?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Closures"><p>This is the second part of the post on JavaScript core concepts series. In this post, we will look into JavaScript closures.</p><h3 id="closures">Closures</h3><p>Whenever you create a function, JavaScript creates a local scope of all its parameters and variables available within that function. This means all parameters and variables are available only for that function declaration and not outside of it. This act is called closure. So if you would like to encapsulate any variable exposure to global scope, closure is what you are looking for. Let's have a look at closure with this code.</p><pre><code>function closeMyVariablesAndParams(param) {
	var foo = "Hello " + param;
    
	console.log(foo); // prints Hello codesips
}
closeMyVariablesAndParams("codesips");
console.log(param); //Error: param is not defined
console.log(foo); //Error: foo is not defined</code></pre><p>It also means, no matter how deeply nested they are, the child function will have access to all of its parents' variables and parameters but not the other way around.</p><pre><code>var globalScopedVar = "I am globally available";

function grandParentFn() {
	var grandParent = "I'm available to myself also to all my children";
    
	function parentFn() {
		var parent = "I'm available to myself also to all my children";
        
		function childFn() {
			var child = "I'm only available to myself";

			console.log(globalScopedVar); //Prints
 			console.log(grandParent); //Prints
			console.log(parent); //Prints
			console.log(child); //Prints
		}
	}
}</code></pre><p>As you can see, every time you create a function JavaScript creates a local scope for your function and this behaviour is called closures. </p>]]></content:encoded></item><item><title><![CDATA[JavaScript: Scopes]]></title><description><![CDATA[To what extend your variables can go for you?]]></description><link>https://codesips.io/javascript-scopes/</link><guid isPermaLink="false">5eb2f06d9b194f1722ef3dec</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Wed, 06 May 2020 19:54:39 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1560179304-6fc1d8749b23?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1560179304-6fc1d8749b23?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="JavaScript: Scopes"><p>Some of the most fundamental concepts of JavaScript are hoisting, self-executing function blocks, closures, and scopes. They helps us understand how JavaScript relate variables and methods given a block of code. Learning how they work helps us write bug-free, controlled coding. I never been to an interview without a question from these concepts.</p><p>In the following series of posts, we will look at them in detail starting with this post about scopes.  </p><h2 id="scopes-">Scopes 🔭</h2><p>Scopes are, availability of variables or methods to your block of code. Your block of code could be an if condition, for loop, function or simply global. Let's get to coding,</p><pre><code>console.log(this); // prints window object</code></pre><p>when you try typing the above code on your browser's developer console, it will print a big Window object, or on Node.js it will print a big global object. This is called the <em><strong>Global Scope</strong></em>. You can write your own variable on the global scope, which will obviously be available on all your if conditions, for loops and functions no matter how deep they go. It also exposes your variable to all third party libraries if you include them in the global scope.</p><pre><code>var foo = "hello world";
console.log(window.foo); // prints hello world
</code></pre><p>The second type of scope is called <em><strong>Local Scope</strong>. </em>Local scopes are variables available within your function. Let's have a look,</p><pre><code>var foo = "Hello";

function america() {
	var bar = "Howdy";
	console.log(foo); // prints Hello
	console.log(bar); // prints Howdy
}

console.log(bar); // *Error: bar is not defined*
console.log(foo); // Prints Hello

america(); // Function declared on global scope, so the function is available globally</code></pre><p>As you can see the variable <code>bar</code> is only available within <code>america()</code> method and not  globally. </p><p>The last type of scope is called <strong><em>Block Scope. </em></strong>Block scopes are only available on ES6, so you can use it on the latest Node.js but not widely supported by all browsers. </p><p>The secret recipe to write block scope variables in JavaScript is by declaring a variable with <code>let</code> keyword instead of <code>var</code>. Let's take our <code>america()</code> method and implement a block scope.</p><pre><code>function america() {
	var bar = "Howdy";
 	if (bar === "Howdy") {
		let baz = "YeeHaw!"; // Notice let keyword
        
		console.log(baz); // prints YeeHaw!
		console.log(bar); // prints 
	}
    
	console.log(baz); // *Error: baz is not defined*
}
america();</code></pre><p>Notice how variable <code>baz</code> declared with <code>let</code> is only available within the parentheses <code>{}</code> of  <code>if</code> condition. So variables declared with <code>let</code> encapsulates itself to whichever parentheses <code>{}</code> based code block. It could be <code>for</code>, <code>while</code>, <code>switch</code>, <code>function</code>, etc. </p><p>If you declare variable <code>baz</code> with keyword <code>var</code>, something special happens with JavaScript. The output on the last <code>console.log</code> will be <code>undefined</code> instead of <code>not defined</code> error. This special case is called variable "Hoisting". Which we can cover on another post. </p><p>These are three types of scopes in JavaScript. Understanding them will enable you to write bug-free code, control what to expose where, and generally become a better developer. </p>]]></content:encoded></item><item><title><![CDATA[Node.js event loop, better explained.]]></title><description><![CDATA[You think you know it, but you don't!]]></description><link>https://codesips.io/node-js-event-loop-better-explained/</link><guid isPermaLink="false">5eb2d88d9b194f1722ef3d3f</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Wed, 06 May 2020 16:27:01 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1570598912132-0ba1dc952b7d?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1570598912132-0ba1dc952b7d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Node.js event loop, better explained."><p>There are many versions of event loop tutorials that you can find around the web. At least for me, most of them are confusing or logically doesn't make any sense.</p><p>I find Bert Belder's keynote on event loop easy to understand. It makes sense on how JavaScript returns you the results at different intervals when performing various operations. I can clearly understand the differences between <code>setTimeout()</code> <code>setInterval()</code>, <code>process.nextTick()</code> and <code>setImmediate()</code>. Without further ado,</p><figure class="kg-card kg-embed-card"><iframe width="480" height="270" src="https://www.youtube.com/embed/PNa9OMajw9w?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h3 id="why-i-am-writing-this-post">Why I am writing this post?</h3><ol><li>JavaScript execution patterns are difficult to understand for anyone transitioning from a type based languages. And this keynote may help them rewire their brains!</li><li>JavaScript backend developers may have asked to explain Node.js event loop probably on every single interview he/she may have attended. They can prepare confidently from this keynote.</li><li>For interviewers who think they know Node.js event loop but don't.</li><li>For myself so whenever I forget, I can come and refer my post.</li></ol><p>At the time of writing this post, shockingly only 44k people have viewed this wonderful keynote. I'm sure there are more than 44k Node.js developers in the world! 😒</p>]]></content:encoded></item><item><title><![CDATA['falsy' values in JavaScript]]></title><description><![CDATA[It's easy to filter 'falsy' values, but one has to be careful!]]></description><link>https://codesips.io/falsy/</link><guid isPermaLink="false">5eb1c8dd9b194f1722ef3ce5</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Tue, 05 May 2020 20:46:56 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1551538827-9c037cb4f32a?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1551538827-9c037cb4f32a?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="'falsy' values in JavaScript"><p>All values when passed to <code>Boolean()</code> returns false are 'falsy' values. </p><p>The below are the finite set which is considered as 'falsy' values in JavaScript. All others are considered as 'truthy'. It's like vowels and consonants in English alphabets.  </p><pre><code>false
0
'' or `` or ""
0n //BigInt
undefined
null
NaN</code></pre><p>It's very easy to filter the above 'falsy' values in a variable,</p><pre><code>let a = false;
if (a) {
	//does not enter
}

or 

if (Boolean(a)) {
	//does not enter
}</code></pre><p>But one has to be careful when dealing with <code>0</code>, <code>false</code>, or <code>null</code> as users may genuinely what to input those values to your API or DB etc.  </p><p>The below method ignores <code>0</code>, <code>false</code>, and <code>null</code> but only check for empty strings, undefined, NaN and empty object values. If you find it useful, please feel free to use it. </p><!--kg-card-begin: html--><script src="https://gist.github.com/var-kar/4289b5a2350605d70f9ec9d7d328ef5d.js"></script><!--kg-card-end: html--><p>You can replace <code>typeof value === 'string'</code> and <code>isNaN(value)</code> with more reliable checking. Links below.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/relaiable-way-to-check-datatypes-in-javascript/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Reliable way to check datatypes in JavaScript</div><div class="kg-bookmark-description">Many versions have come &amp; gone, but this one liner is always a winner 🏆!</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.ico" alt="'falsy' values in JavaScript"><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1545438102-799c3991ffb2?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="'falsy' values in JavaScript"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/checking-javascript-nan-the-right-way/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">NaN? isNaN? Who’s NaN👵? Checkin’ out JavaScript NaNs the right way.</div><div class="kg-bookmark-description">Hint💡: Please don’t use isNaN()</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.ico" alt="'falsy' values in JavaScript"><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1536935338788-846bb9981813?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="'falsy' values in JavaScript"></div></a></figure>]]></content:encoded></item><item><title><![CDATA[Check if a variable is an integer or a float in JavaScript.]]></title><description><![CDATA[Int or Float, I got methods that can make them bust 🤟]]></description><link>https://codesips.io/check-for-integer-and-float-in-javascript/</link><guid isPermaLink="false">5eb1a3349b194f1722ef3c51</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Karthik Vasudevan]]></dc:creator><pubDate>Tue, 05 May 2020 19:36:44 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1470337458703-46ad1756a187?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1470337458703-46ad1756a187?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Check if a variable is an integer or a float in JavaScript."><p>At the time of writing this post ES6 is not widely available on all browsers. So the purpose of this post, is to find a reliable solution to check if the variable is an integer or a float in ES5.</p><p>Unlike in other languages, integers and floats are not native data types in JavaScript. For both these types JavaScript assigns <code>Number</code> as it's common datatype.</p><h3 id="integer">Integer</h3><p>We can find if a variable is an integer or not by using ES6's <code>Number.isInteger()</code> method. But that's just available only in ES6. </p><p>The more reliable two methods to check for an Integer in ES5 are,</p><!--kg-card-begin: html--><script src="https://gist.github.com/var-kar/de538480b1f8d6439461e878d6ecfab8.js"></script><!--kg-card-end: html--><p>Please go ahead and pick one and leave the worry to the <code>isInt()</code> method that we made. </p><h3 id="float-">Float <strong><a href="https://emojipedia.org/woman-swimming/">🏊‍♀️</a></strong></h3><p>Unlike ES6's <code>Number.isInteger()</code> method to check for Integers, we have nothing of that sort for float. </p><p>This forces us to make our custom method. </p><!--kg-card-begin: html--><script src="https://gist.github.com/var-kar/2713d15e781530919c2e39754aee44ca.js"></script><!--kg-card-end: html--><p>Both <code>isInt()</code> and <code>isFloat()</code> gives you a solid way to check for integer and float in JavaScript which doesn't require any compiler like Babel. </p><p>You can make it even more robust by replacing the <code>typeof num === 'number'</code> and <code>isFinite(num)</code> conditions with <code>typeOf()</code> and <code>isInfinity()</code> methods that we made on our previous posts. You can find the links below.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/relaiable-way-to-check-datatypes-in-javascript/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Reliable way to check datatypes in JavaScript</div><div class="kg-bookmark-description">Many versions have come &amp; gone, but this one liner is always a winner 🏆!</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.ico" alt="Check if a variable is an integer or a float in JavaScript."><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1545438102-799c3991ffb2?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Check if a variable is an integer or a float in JavaScript."></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://codesips.io/javascript-infinity/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">JavaScript: Infinity War</div><div class="kg-bookmark-description">Don’t get too excited. We are not showing Avengers: Infinity War</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://codesips.io/favicon.ico" alt="Check if a variable is an integer or a float in JavaScript."><span class="kg-bookmark-author">Karthik Vasudevan</span><span class="kg-bookmark-publisher">codesips</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1546171753-97d7676e4602?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=2000&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Check if a variable is an integer or a float in JavaScript."></div></a></figure>]]></content:encoded></item></channel></rss>