<?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 Jainishshah on Medium]]></title>
        <description><![CDATA[Stories by Jainishshah on Medium]]></description>
        <link>https://medium.com/@jainishshah12?source=rss-6a2a31dd9c44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*30fvbjB8WopsJ3S2-RoFzQ.jpeg</url>
            <title>Stories by Jainishshah on Medium</title>
            <link>https://medium.com/@jainishshah12?source=rss-6a2a31dd9c44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:44:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jainishshah12/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[Understanding Client Side Routing — what made Single Page Applications possible]]></title>
            <link>https://jainishshah12.medium.com/understanding-client-side-routing-what-made-single-page-applications-possible-5f2851a96f2d?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f2851a96f2d</guid>
            <category><![CDATA[vue-router]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[client-side-routing]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Sat, 30 Jul 2022 14:03:30 GMT</pubDate>
            <atom:updated>2022-08-01T05:38:29.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding <strong>Client Side Routing</strong> — what made Single Page Applications possible</h3><p>Today you have every service you can possibly think about on the internet from booking tickets, banking, and trading to even applying/receiving government documents. Over the course of time, these applications have evolved to be more efficient by using tech-stack like WebAssembly, Client Side Routing, etc that has made push notifications, faster load times, smooth surfing, etc possible. One of the major talked about pieces in the FE ecosystem today is the rise of Single Page Applications (SPA’s) with more and more companies adopting this.</p><p>Let’s review Udemy a leading online education courses marketplace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mny1HxQc4EKG5Z0Yddd2AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSxJYgdY4uV2d1etkmBsEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5W5T6gSvvoWbN-nfubbWQ.png" /></figure><p>Did you notice something peculiar in network requests?</p><p>Let’s take another example of Pinterest and observe the network tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZHkS66pmKYNMorV4zyylg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fduWF0qePwjZ0pCadlHU5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-a0vq5ZycgDP8cGpPgl0DA.png" /></figure><p>PS (The Network tab was cleared before navigating to each page). Now did you find anything peculiar?</p><p>Yes an <strong>HTML file request</strong>. If you see in the case of Udemy each time I visit a new webpage I see a request for an HTML page is sent to the server and I get a fresh HTML document every time. But in the case of Pinterest, there is no such thing, both of these platforms enjoy high traffic and both work smoothly but somewhere there is an inherent difference in the way the FE of both these are implemented. <strong>What Udemy does is Server Side Routing (SSRouting)and what Pinterest does is Client Side Routing (CSRouting).</strong></p><p>As the term suggests the routing happens on the Client side vs Server side and Server side routing has been a traditional implementation for decades.</p><p>Note* <strong>routing is different from rendering. </strong>You<strong> </strong>would have also come across<strong> Client Side Rendering and Server Side Rendering, </strong>this has nothing to do with routing. In the former case, the JavaScript is run on the Server side meaning the entire webpage is created on the server and then delivered to the UI while in the latter case server sends HTML and javascript scripts to the client and the client runs that javascript, this includes making an XHR request to the backend for fetching data and then rendering it, etc.</p><p>Like Authorization and Authentication are often mixed to be the same thing with the advent of oAuth, the same issue lies with routing and rendering after CSRouting. 😅</p><p><strong>Routing is the process through which the user is navigated to different pages on a website. Rendering is the process of putting those pages on the UI. Every time you request a route to a particular page, you are also rendering that page, but not every render is an outcome of a route. Their close association helps in speculating their effect on the <em>efficiency</em> and <em>speed</em> of an application. </strong>(src <a href="https://www.pluralsight.com/)">https://www.pluralsight.com/)</a></p><p>Ok, so they are just two different methods of doing routing, what major difference does it make? I don’t see any great thing happening on the webpage then why was CSRouting even implemented in HTML5? What benefits does it provide and to add more to that do I need to migrate my application to use CSRouting?</p><p>CSRouting was developed to solve specific problems with SSRouting. Let’s take an application, break it down and find those problems</p><p>A short list of What a web page usually contains.</p><ol><li>Header</li><li>Footer</li><li>Sidebar (if needed)</li><li>Body</li><li>Ad/Media Placement</li><li>CSS Themes</li></ol><p>Apart from the body changing, all other components don’t generally change from page to page, right? Now suppose you navigate to a different page, a request is sent to the server you see a lag/refresh in the page and once all resources are loaded then you see the page. So we can list down the following issues from this observation.</p><ol><li>Lag/Latency in the application while navigating spoils the User Experience</li><li>Re-downloading of resources (CSS, external packages, etc) and re-building of the components like header/footer/sidebar which were already built, and this step was not required.</li><li>Abstract issues like net speed, and time to load <br>- We live in world of 4G+/5G, today we complain even about 40 Mbps speeds but remember India before 2016, high data rates and slow speeds up to 2Mbps.<br>- This will drop the number of DAU rapidly.<br>- Imagine how long will it take to render the page too.</li></ol><p>Certain issues can be resolved by implementing efficient caching mechanisms on the browser but lag/refresh and recreation of components create a major bottleneck in performance and issues in UX.</p><p>This is where the <strong>History API of HTML5</strong> comes into the picture, it enables us to handle routing in Web-browser which we can leverage using JavaScript.</p><p>So managing routing on the UI we can solve the issue of page refresh and rebuilding of components, this will be smooth from a UX perspective. You have your entire application loaded in the first call itself which lets the browser know where to use History API or when to call the server.</p><p>So CSRouting helped to do the following</p><ol><li>Removing frequent server requests</li><li>Improving page rendering.</li><li>Doing away with full page reloads.</li><li>Providing rich site interactions. — specifically important if you are an analytics platform.</li></ol><p>But SSRouting has been there for a very long time, it must have provided some benefits that soo many people built apps with these</p><ol><li>Separation of concern and loading only limited data</li><li>Security<br>- Access Control over restricted URLs</li><li>Easy SEO optimizations <br>- SEO depends on meta tags (partly), by having multiple requests for multiple routes you can update these meta tags and this will make it easier for bots to parse all routes in your application and then map respective tags with your routes</li></ol><p>CSRouting too has many cons</p><ol><li>Difficult to implement and added complexities.</li><li>The entire app loading on the first call to a server, this gives a <strong>higher initial page load</strong>. Also, this results in unnecessary data being loaded that which client has not requested for</li><li>Security Concerns — difficult to implement <strong>navigation guards</strong> to restrict the user to access pages he is not allowed to</li><li>SEO issues — Client-side routing and rendering convert JavaScript to HTML, making search engine crawling less optimized.</li><li>Have fallback implementations for old browsers</li></ol><p>I know you are tired but we are almost at the end of this.</p><p>So if there are these many issues with crucial business ones like SEO why do we use CSRouting? Here are some of the reasons.</p><ol><li>External libraries like react-router, vue-router<br>- They take care of navigation guards and dynamic routing<br>- Implements fallbacks for legacy browsers and also handles browser interactions like back/forward states.<br>- Easier to implement ( subjective )<br>- Solves initial page load time issue by lazy-loading bundles of a specific page</li><li>Better performance and greater User Experience.</li><li>Problems like Nested routes, Access Controls, and Redirection are now solved</li></ol><p>All the benefits Client Side Routing and Client Side Rendering provide help to achieve Single Page Applications.</p><p>It is safe to say that if you have a SaaS-based product it is safe and better to implement Client Side Routing. If you have a high usage of SEO you should go for Server Side Routing. Also if all your app does is serve static content or has medium to less traffic use Server Side Routing and Rendering as implementing CSRouting is a heavy task.</p><p>If you look a little bit closer you’ll be able to see that what CSRouting actually does is give more power to JavaScript and take more and more compute load away from Server Side to the Client Side. This is debatable so share your views in the comments below.</p><p>For any additional information reach out to me at jainishshah12@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f2851a96f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures — The way encapsulation and Module patterns work in JavaScript]]></title>
            <link>https://jainishshah12.medium.com/closures-in-javascript-fb7dcf063547?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7dcf063547</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[basics-of-javascript]]></category>
            <category><![CDATA[javascript-in-details]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 06:30:23 GMT</pubDate>
            <atom:updated>2021-08-13T05:46:39.816Z</atom:updated>
            <content:encoded><![CDATA[<p>Hola Js Devs, I am sure you would have heard the term “closures” during development or even during interviews. But are you sure you know closures thoroughly? Even if you haven’t this article will help you understand it in detail. I guarantee that you might have used closures without even knowing (this happened in my case) and you’ll have a eureka moment after realizing you have been using it all along be it in react/angular/node etc. Well, Buckle up boys and girls.</p><p>The general definition of closures goes as <strong>“Closure is when a function can remember and access its lexical scope even when that function<br>is executing outside its lexical scope.”</strong></p><p>And your reaction would be something like……</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*WzAtL5r9EG4k3sX-" /></figure><p>Well, chill out !!!! Let’s break down this statement and try to understand what it says.</p><ol><li>Access/Remember Lexical scope</li><li>Function executing outside its lexical scope</li></ol><p>Too many jargons aren&#39;t they. Let’s take an example then</p><pre>function doSomething(){<br>   var a = 5;<br>   <br>   function printIt(){<br>     console.log(a);<br>   }   </pre><pre>   return printIt;</pre><pre>}</pre><pre>var closureFn = doSomething();</pre><pre>closureFn();</pre><p>What do you think the output of the above code will be?</p><p>Your initial guess would be it’s <strong>“undefined”</strong>. But why? When you execute doSomething() it returns some value and the function execution is done. Since this function is not used anywhere else, the natural thing the<strong> “engine”</strong> would do is to invoke the garbage collector and free up the memory. So the entire scope of doSomething() should be deleted. And when the closureFn() is called it shouldn’t get any value of “a” and print <strong>“undefined” </strong>in “<strong>non-strict”</strong> mode.</p><p>Sadly you are wrong, the output will be “5”. But why is that? Well, it&#39;s the magic of <strong>“closure”</strong>.</p><p>Let’s talk a bit about <strong>“lexical scope” </strong>I have already explained about lexical scope <a href="https://jainishshah12.medium.com/yeh-lexical-scope-hai-kya-da08a1601f2f"><strong>here</strong></a>, please go through it if you are unfamiliar with it. When the engine first compiled and executed the doSomething function it created the scope of that function which looks like</p><pre>Scope: [ (doSomething) =&gt; { a : 5, printIt: pointer to the fn&#39;s location in the heap}]-&gt;[(globalScope) =&gt; {}]</pre><p>Our doSometing function also declares a function printIt. It is stored in the heap somewhere and a reference to it is linked in the scope. The reference to printIt is returned and stored in the closureFn. As you would expect the garbage collector comes into the picture but how would it decide whether free up the memory used by doSomething ? Well the algorithm that works in the background works something like this</p><p>Find “<strong>live</strong>” objects and free up all the dead memory from the heap. The objects that have been instantiated are linked to other objects if they are connected (In this case Scope). All the objects that are linked are known as live objects and are preserved and the rest of the heap is cleared. Since the “printIt” is returned its scope is linked to “doSomething’s” scope and it&#39;s a live object. In this way, the variables and functions in the scope of doSomething are still preserved. Not only of doSoemthing’s but also of all the other objects that may have been chained together. eg</p><pre>function grandParentDoSomething(){  <br>  var a =5<br>  function parentDoSomething(){ <br>   var b= 10;<br>   function doSomething(){ <br>      var c = 15;<br>      function printIt() {<br>       console.log(&quot;HEY&quot;)<br>      }<br>      return printIt;  <br>    }<br>    doSomething() <br>  }<br>  parentDoSomething(); <br>}</pre><pre>var chainedClosure  = grandParentDoSomething();</pre><pre>/* Here all the variables a, b, c are preserved*/</pre><p>I hope you get the gist of how it works.</p><p>Let&#39;s talk about what are some of the use cases</p><ol><li>Module Pattern in JS ( modules are created using this)</li><li>Security Purpose ( Just like protected keywords in Java)</li></ol><p>Well all good things do come with some side-effect</p><p>The biggest disadvantage of Closures is <strong>“High Memory Consumption”</strong>. If you implement closure incorrectly you have sure shot to over-utilize the available memory and your application will crash.</p><p>I guess by now you have understood what closures are and how they work. Let’s take few examples and determine what the output will be.</p><pre>function wallet(){<br> <br> var currentAmount = 1000;</pre><pre> function deposit(amt){<br>  currentAmount += amt;<br> }<br>   <br> function withdrawal(amt){<br>   currentAmount -= amt;  <br> }</pre><pre> function currentBalance(){</pre><pre>  return currentAmount;<br> }</pre><pre>return {deposit, withdrawal, currentBalance };</pre><pre>};</pre><pre>var walletA = wallet();<br>console.log(walletA.currentBalance());  // 1000<br>walletA.deposit(50);<br>walletA.withdrawal(200); </pre><pre>console.log(walletA.currentBalance());  // 850</pre><p>You can get an idea of how the protected variables are implemented in JS using closures. ( Note: this code is just for demo purposes, you will have to write some more logic to check only integer values are passed and some error handling also if the data that is returned is non-primitive ie an object always send a copy destructuring it i.e. use spread operator. Objects are returned by reference so if you don’t send a copy you are violating the integrity of the data).</p><p>Let’s take one more example and it&#39;s a common interview question.</p><pre>function() print{ </pre><pre>   for(var i=1;i&lt;=6;i++){<br>    setTimeout( function(){ console.log(i); }, 1000 ); <br>   }</pre><pre> }</pre><p>Try to solve it yourself and answer it in the response. Will be publishing the answer next week.</p><p>Hope you enjoyed reading the article and learned something. Feel free to reach out to me via email jainishshah12@gmail.com</p><p>LinkedIn <a href="https://www.linkedin.com/in/jainish-shah-223137121/">https://www.linkedin.com/in/jainish-shah-223137121/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7dcf063547" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding “this” in JavaScript — The Complete Guide]]></title>
            <link>https://medium.com/codex/understanding-this-in-javascript-the-complete-guide-c4c21fe15ff8?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4c21fe15ff8</guid>
            <category><![CDATA[js-engine]]></category>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[this-in-javascript]]></category>
            <category><![CDATA[execution-context]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 10:43:08 GMT</pubDate>
            <atom:updated>2021-07-28T06:56:18.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VhXB2I0VraR9oGVK" /><figcaption>Photo by <a href="https://unsplash.com/@zacharykeimig?utm_source=medium&amp;utm_medium=referral">Zachary Keimig</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Understanding “this” in JavaScript — The Complete Guide</strong></h3><p>Namaste Devs, I am sure you have confused yourself with “this” in JS while learning and even in interviews. Someday sitting in front of your system reading this piece you’ll have a eureka moment. I’ll try to explain both the traditional way “this” works and the newer implementation in ES6 (arrow functions). So sit tight.</p><p>Simply speaking “this” is the <strong>reference to the object that contains the current function</strong>. As simple as that, but what is the current object, and how it changes dynamically while your code runs is a little confusing.</p><p>The value of this will depend on where the function is called on run-time which you’ll call the <strong>“call-site”</strong> in technical terms. There are multiple ways to call a function, I’ll show 2 of them here for sake of simplicity</p><pre>function doSomething(a){<br>   console.log(a);<br>}</pre><pre>var obj = {<br> key: &quot;value&quot;,<br> doSomething: function(){ console.log(&quot; namaste&quot;); }<br>}</pre><pre>// you can call the function doSomething like this</pre><pre>doSomething(&quot;jainish&quot;); // jainish<br>obj.doSomething(); // namaste</pre><p>Well, this you already know, so what point do you think I want to make from this? Just look at how we have called the functions. Is there something different about them? If there is, how important is the difference?</p><p>The answer to this is <strong>“execution context”</strong>. But WTF is context and how is it useful. To explain this let me drill down on how JS works behind the hood.</p><p>Let’s understand what happens when a simple JS program is executed.</p><ol><li>The <strong>global execution context</strong> is created and pushed on the execution stack.</li><li>The engine then executes the code.</li><li>If a function call is encountered, the engine will first compile the code during which a new <strong>execution context</strong> is created and pushed on the execution stack and finally the code is executed</li><li>Once execution is complete the fn execution context is popped out</li></ol><p><strong>“Execution Context”</strong> is an abstract concept in JS. It’s an object that holds certain information that the function will require to execute. This information contains multiple properties. To name a few.</p><ol><li><strong>Activation/Variable object</strong> =&gt; stores information about the arguments passed to the function, variables and functions declared in that function.</li><li>Creations of <strong>Scope Chain</strong>. (<a href="https://jainishshah12.medium.com/yeh-lexical-scope-hai-kya-da08a1601f2f">you can read more about it here</a>)</li><li>Value of <strong>this</strong>.</li></ol><p>Global execution context is similar to function context, except it&#39;s loaded in the stack by default.</p><p>This doesn’t exactly answer the difference between the 2 doSomething function mentioned above but it shows that “<strong>this</strong>” is dynamic in nature and changes according to the call site (<strong>value of this is based on what context is on the top of the execution context stack</strong>).</p><p>There are 4 simple rules that describe how “this” works</p><ol><li>Default binding</li><li>Implicit binding</li><li>Explicit binding</li><li>“new” operator</li></ol><p>Of course, there are certain exceptions we’ll talk about (Note: Arrow functions of ES6 use some different mechanism, understanding these rules first will help you understand how Arrow functions work)</p><pre>function doSomething(){<br>  console.log(this.a);<br>}</pre><pre>var a = 6;</pre><pre>doSomething(); //6</pre><p>You can see that we have declared the function in the global space (not is a function). When we execute this function it prints 6. But why?</p><p>Answer: We talked about the execution stack, by default the global execution context is on top of the stack. When we call something, its execution context will be pushed and will be on top of the stack. Since this function belongs to the global object the value of this will be the global object (global in Node.js and window in browser env). The global object has the property “a” and thus the output will be 6. This is an example of <strong>“default binding”</strong></p><pre>function doSomething(){<br>  console.log(this.a);<br>}</pre><pre>var a = 6;<br>var obj = {<br>  a : 12,<br>  doSomething: doSomething<br>};</pre><pre>obj.doSomething(); //12</pre><p>What changed here ? In this case, we called doSomething with prefix (“obj.”). Calling the function in this way will set the value of “this” in the function’s execution context as “obj” (a reference to the object obj). obj has property “a” and so the value printed will be 12. Prefixing the function call with an object reference is an example of <strong>“implicit binding”</strong>. You are implicitly calling a function of an object.</p><pre>var a = 6;<br>var obj = {<br>  a : 12,<br>  doSomething: function() { console.log(this.a) }<br>};</pre><pre>var foo = obj.doSomething;</pre><pre>foo(); //6</pre><p>Damn!!! We just learned that calling a function with obj reference will print 12, but wtf did it print 6. Here comes an important concept. A function definition is stored in the heap and when you are assigning “foo” with obj’s doSomething you are actually passing the reference of that function in memory. There is no interlinking between the object reference and function on where it’s declared, but it depends on where the function is called. Taking the execution context into the picture. Global Execution context is on top of the stack. You call the function foo which is a property of the global context and so while executing foo the value of this will be set to the global context. So the answer 6.</p><p>I hope till now you are able to understand the “object” that we are taking into the picture. If not please re-read up to this point again.</p><p>Implicit and default binding is a way that the <strong>“JS engine makes decisions on the value of this”</strong>. But what if you as a developer you want to set this value. In what scenarios will you want to specify this value? What mechanism is provided in the language for this?</p><p>Let’s take an example.</p><pre>var input = 1;</pre><pre>function square() { <br> let cbFn = function(){ console.log(this.input*this.input) };<br> setTimeout( cbFn , 1000);<br>};</pre><pre>var obj = {<br> input : 3,<br> square: square<br>};</pre><pre>obj.square(); // 1</pre><p>I am pretty sure you would have guessed that the answer will be 9 but why did it print 1 !! This time we even called function with the reference to the object. Boy, I am tired….. OK just bear with me for a min. It&#39;s simple… The answer is the execution context stack.</p><p>When you called the function obj.square(), the square function was pushed on the execution context stack with the “this” pointing to “obj”. If instead of setTimeout you would have printed the squaring logic it would have print “9”. But what went wrong. See when you did setTimeout the engine kept it aside for executing at some time later. Doing this the square function execution was over so this lead to poping its execution context out of the stack. When the setTimeout resolved it was pushed to the stack with the global object at the top of the stack. As you can see now that his function will be called as a part of the global object and so it will pick the input value “1” and print “1”.</p><p>How will you fix it? This is where you should have some mechanism where you can explicitly set the value of this in the function in setTimeout to be obj. Another example is <strong>“event handlers”</strong>. When you add a call back on the event handlers you have to make sure that the value of “this” will be a reference to that DOM element only.</p><h4><strong>call, bind, apply</strong></h4><p>These three functions help to explicitly set the value of “this” to the object we want.</p><p><strong>Call and Apply immediately call the function</strong> with given “context” and arguments. While <strong>bind returns a function</strong> with the context(this) set that can’t be changed.</p><pre>function foo() { <br>  console.log(this.key);<br>}</pre><pre>var objA = { key : &quot;A&quot; };<br>var objB = { key : &quot;B&quot; };</pre><pre>foo.call(objA) // A<br>foo.call(objB) // B</pre><pre>// Apply works the same way , there is a small difference between  // call and apply on format of arguments passed to it</pre><pre>var bindedFoo = foo.bind(objA);</pre><pre>bindedFoo(); // A;</pre><pre>var doubleBindedFoo = bindedFoo.bind(objB);</pre><pre>doubleBindedFoo() // A (Once binded the value of this can&#39;t be changed)</pre><p>The above example shows a basic structure how dynamic binding works. Let’s take the setTimeout example again and modify it to solve the issue</p><pre>function doSomething(){<br> let cbFn = function () { console.log(this.input*this.input )};<br> let bindedcbFn = cbFn.bind(this);<br> setTimeout( bindedcbFn , 1000 );<br>}</pre><pre>var obj = { <br>     input : 3, <br>     doSomething: doSomething <br>};<br></pre><pre>obj.doSomething(); // 9</pre><pre>// One great example can be of debounce method (&quot;primarily used in // search, suggestion =&gt; while the user is typing don&#39;t make API    // calls , instead delay the execution till user finishes typing&quot;)</pre><pre>function debounce(fn,timeout) {<br> let timer;<br> <br> return  function (...args) { <br>     let context = this;<br>     clearTimeout(timer);<br>     setTimeout(  function() { fn.apply(context,args) } , timeout );<br>    };<br>}</pre><p>So these are the ways to explicitly bind “this” . You might have used constructor functions. But do JS really have classes and does constructors make sense?? Turns out construction fn is just a regular function . Using <strong>“new”</strong> keyword in front of any function makes it a constructor fn. But what does the “new” keyword does.</p><p>In case a construction function don’t return an object the “new” keyword will create a brand new object and return it. But where does “this” comes into picture ? It turns out when you call a function with “new” keyword . <strong>JS creates a new object in background and passes reference of newly created object to the function , thus making this new object “this” .</strong></p><pre>function Name(fname, lName) {  <br>   this.fname = fname; <br>   this.lName = lName;  <br>}</pre><pre>var newObj = new Name(&quot;jainish&quot;, &quot;shah&quot;);<br>console.log( newObj.fname + &quot;  &quot; + newObj.lname); // &quot;jainish shah&quot;</pre><p>Finally…. We have covered all 4 rules here. But what if more than one rule occurs at the same time we need some precedence rule</p><ol><li>new binding</li><li>explicit binding</li><li>implicit binding</li><li>default binding</li></ol><pre>function foo() {<br>  console.log(this.name || &quot;name not defined&quot;);<br>}</pre><pre>var obj = { name: &#39;jainish&#39; };<br>var bindedFoo = foo.bind(obj);<br>bindedFoo() // jainish</pre><pre>var newFoo = new bindedFoo(); // name not defined</pre><p>You can clearly see that even though bindedFoo fn had “this” set to obj it was overridden by “new” keyword. This contradicts statement above that “once binded “this” of fn can’t change value” , that is not completely true. It is highly dependant on the implementation of “bind” method. (Checkout the mdn docs for polyfill)</p><p>This brings us to the end of the article. I know it is pretty long , but hey size matter 😂😂. I will cover “Arrow functions” in next piece. I hope you learned something new and Sio Nara untill next one.</p><p>For further queries , reach out to me @ jainishshah12@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c21fe15ff8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/understanding-this-in-javascript-the-complete-guide-c4c21fe15ff8">Understanding “this” in JavaScript — The Complete Guide</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying pass by value and pass by reference in JavaScript once and for all]]></title>
            <link>https://jainishshah12.medium.com/demystifying-pass-by-value-and-pass-by-reference-in-javascript-once-and-for-all-cd7c57292680?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd7c57292680</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[basic-of-programming]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 16:14:01 GMT</pubDate>
            <atom:updated>2021-02-12T16:14:01.512Z</atom:updated>
            <content:encoded><![CDATA[<p>When I pass something to a function will it be passed by value or passed by reference? You would definitely have stumbled upon this concept no matter which programming language you use. If you come from C/C++ background like me you know that you have the choice in your hand. To pass by reference you’ll accept the argument as a pointer else as a primitive value like</p><pre>int function abc(int a){} =&gt; pass by value <br>               OR <br>int function abc(int *a){} =&gt; pass by reference</pre><p>In short, if you want your called fn to manipulate the value, you pass a reference (pointer) else you send a copy of the value.</p><p>But that is in C/C++ ( P.S: best languages ever), now we are in JavaScript env. You don’t have the capability to explicitly send something as a reference and there is no concept of the pointer so how do you do determine what’s going on?</p><p>Don’t freak out, I am here for the rescue. And I’ll make a bold statement here <strong>“Every argument passed in JavaScript is passed by value” </strong>i.e a copy of that variable is passed. Let’s take an example here</p><pre>function doSomething(x){<br>  x = x*x;<br>  console.log(x)<br>}<br>var y = 10;<br>doSomething(y); // 100<br>console.log(y); // 10</pre><p>OK so when is called doSomething() with y, the copy of that value was passed and assigned to a and so the output was 100 while the value of y still remained 10.</p><p>But here I give you the chance to prove me wrong. Take a look</p><pre>function doSomething(argObj){<br>  argObj.value = &quot;shah&quot;;<br>}<br>var obj = {<br>  name: &#39;jainish&#39;<br>};<br>console.log(obj.name); // jainish<br>doSomething(obj);<br>console.log(obj.name); //shah</pre><p>Well… well… well… I’ll give you a moment to cheer. You have the perfect argument to counter me. “Hey Jainish, if everything is sent as a copy why did my actual object change its value ? You are such a fool to make a bold statement like that, stop writing shit you don’t fully understand” (Well I assume the hate here will be similar to Twitter, don’t judge me ).</p><p>Guess what I still stand by my statement. But if I still say I am right and you are also right, who’s actually right then ??? Well, we both are!!!</p><p>The answer lies in how JS works under the hood. You see there are two types of values in JS. Primitives and non-primitives. The primitives are [Number, Symbol, String, Boolean, BigInt, Undefined] and non-primitive is [Object] (Let’s keep Null, Function, NaN, etc out for a minute for sake of simplicity).</p><p>The values of primitive are fixed (eg Number is in the range -(2⁵³ − 1) and 2⁵³ − 1)). So when the code is being executed these values are actually stored in the <strong>“stack”</strong>. While non-primitives like <strong>Object</strong> (Arrays, Maps, Sets too, but they are derived from Object only) don’t have a fixed length so they are stored in “<strong>heap</strong>”. The variable that holds the primitives has the <strong>“value” </strong>stored in them while the variable that holds non-primitives have <strong>“reference” </strong>to the memory in the heap.</p><pre>var x = 6 ; ======&gt; x[6] (memory block actually hold the value 6)<br>var z = {name:&#39;jainish&#39;} ==&gt; z[refToHeap]==&gt;heap[ {name:&#39;jainish&#39;} ]<br>(variable z have the value of the memory location)</pre><p>Ok now coming to my statement, when you call a function the JS engine compiles the code and then copies the value accordingly. So in the case of primitive, it copies the value itself and in the case of Obj, it copies the reference.</p><pre>function abc(x){<br>  x = x*x;<br>  console.log(x);<br>}<br>var y = 6;<br>abc(6);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*5d3kO_LF-SKsBmjU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*2ts9cuIo1KmddG8u.png" /></figure><p>The value 6 is copied in a new memory location defined by variable “x”</p><pre>function abc(argObj){<br>  argObj.name = &quot;shah&quot;;<br>}<br>var obj = {name: &#39;jainish&#39;};<br>console.log(obj.name);<br>abc(obj);<br>console.log(obj.name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*SBzhuImd0V3koZuQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*NuiZLPDmWSfUIWb5.png" /></figure><p>the function copies the reference (value) of the Obj to argObj (So it’s still “pass by value”). But since manipulation to this value affects the reference, the changes will be reflected in both Obj and argObj. And since we are copying a reference here it’s referred to as “pass by reference”.</p><p>How to avoid this =&gt; Simple pass a different memory location (how ? easy peasy in ES6+ you can you Object destructuring [{…Obj}] ). Else you can assign argObj to different memory location like</p><pre>function abc(argObj){<br> argObj = { <br>      name: &#39;shah&#39; <br>  };<br>}<br>var obj = {name : &#39;jainish&#39;};<br>console.log(obj.name); // jainish<br>abc(obj);<br>console.log(obj.name); // jainish</pre><pre>abc({...obj});</pre><pre>console.log(obj.name) // jainish;</pre><pre>// In destructuring a new Obj is created so the reference will <br>// always be different. In this case you are not even using the <br>// reference of obj when you call the function abc</pre><p>We are finally done here. It was a long one but hey if it helped you I am very happy. Ok, I’ll take one more example and I want you to figure it out yourself. It’s on a different topic but if you find the answer do add a response to this article.</p><pre>function doSomething(){ <br>  for(var i=0;i&lt;10;i++){<br>   setTimeout( function(){ console.log(i) }, i*1000);<br>  }<br>}</pre><p>For further queries feel free to reach out at <strong>jainishshah12@gmail.com</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd7c57292680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yeh lexical scope hai kya?]]></title>
            <link>https://medium.com/swlh/yeh-lexical-scope-hai-kya-da08a1601f2f?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/da08a1601f2f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[lexical-scope]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Fri, 05 Feb 2021 07:03:23 GMT</pubDate>
            <atom:updated>2021-02-05T07:10:49.116Z</atom:updated>
            <content:encoded><![CDATA[<p>Hola Developer!!!! Well I know that is a bit dramatic title, but that truly describes my feeling when I read this term again and again be it understanding how “this” works in JS or what is a closure or solving console questions. Lexical scope is one of the fundamental concepts in JavaScript, so let me demystify this cool thing.</p><p>Every program, written in any language has only one job =&gt; perform computation. Now to run some specific business logic the program might need to store some variables and access them later this is what gives your program a state and variables are key to do that. But can we just use any variable anywhere? No, right. Well, there are some rules regarding what variables the current running piece of code can access. These sets of rules are called <strong>Scope</strong>.</p><p>In JavaScript, you have the functional scope, block scope, and global scope, but what do they even mean? To understand this we will have to drill down a little into how JS works under the hood, let me introduce to you the <strong>“Engine”. </strong>There is a common misconception that JS is an interpreted language. Well, it’s not (until someone develops an engine that doesn’t do optimizations). Your JS code will be compiled few microseconds or even smaller time frames before your code executes. But why do we need to compile JS even? Well the JS engine uses all kinds of tricks to optimize your code for faster execution. A certain example can be that even before executing the code the engine will know what identifiers(variables/function) will be present in the code so that during execution it is faster to retrieve.</p><p>At this point, you might be thinking what am I blabbering about, what relation does it have with scope. Well don&#39;t be mad, I promise by the end of the blog you’ll find it useful.</p><p>So where were we… oh ok the engine. Yaa so let’s take a piece of code and understand the compilation phase and execution phase and creating of Scope.</p><pre>var c = 5</pre><pre>function doSomething(a){</pre><pre>    function printIt(b){<br>       console.log(a + b + c);<br>     }</pre><pre>    printIt(3);</pre><pre>}</pre><pre>doSomething(2);</pre><p>A simple piece of code right. But here’s a question how does the function printIt() even know the value of “c” or “a” or “b”.</p><p>Let’s drill down. When the compiler encounters this piece of code it will parse it</p><ol><li>There is a method called doSomething, the compiler will see this as a function declaration and will store this definition in heap and without going into this function it will move on</li><li>The compiler will see there is a call to this function and the code ends so this piece of code will go to the “engine” for execution</li><li>the engine will ask the compiler where the definition of fn() is and then execute with parameter 2.</li><li>Again the compiler will come into the picture as a new fn is encountered. This is basically called function scope( Each time a new function is encountered a separate scope is created). All variables and fn declarations will be available to this fn only and its instances (if any) and not anything outside this.</li><li>The compiler will then parse through the doSomething fn. It will ask scope to declare a variable “a” and then assign to it the value 2.</li><li>This is what the scope will look like now</li></ol><pre>Scope : [(of DoSomething) =&gt; { a: 2} ]-&gt;[global =&gt; {c : 5}]</pre><p>7. Again this parsing will go on, the definition of printIt will be stored and the engine will execute the printIt() with parameter 3.</p><p>8. This is what scope will look now</p><pre>Scope : [ (of printIt) =&gt; {b : 3}]-&gt;[(of DoSomething) =&gt; { a: 2} ]-&gt;[(global) =&gt; {c : 5}]</pre><p>9. Now when the engine will execute the printIt function it encounters console.log()</p><p>10. The engine will first ask where the console is and then find the log fn. When the log fn asks for values of “a”, “b”, “c”, engine will ask Scope for its values. The scope will find “b” in the current scope and return its value, it doesn’t find “a” in the current scope and will move up the chain to find the value of “a” (in the doSomething scope). Again for the value of c, it will move up the chain to find “c” in the global scope.</p><p>11. Once all the values are retrieved you get the result “10” printed on the console.</p><p>Well, this is what lexical scope is.</p><p>We learned 2 things function scope and global scope. But what is block scope now?</p><pre>&#39;use strict&#39;<br>function abc() {<br>  var a = true;<br>  if(a){<br>      var z = 5;<br>   } else {<br>      var z = 6;<br>    }<br>   console.log(&quot;z = &quot;, z);<br>}</pre><pre>abc();</pre><p>Take the above function for example, what do you think the console.log() would print? And what should logically it print?</p><p>Well, ideally it should print “undefined” in non-strict mode. Since the variable z is declared in the if-else clause block it shouldn’t be accessible outside it. The engine will make the Scope check for the value of “z”.</p><pre>Scope : [ (abc) =&gt; { a : true}]-&gt;[ (global) =&gt; {}]</pre><p>As usual, the scope will move up the chain till the global scope and will find no variable called z. In “non-strict” mode it will print “undefined” and in “strict” mode will throw “Reference Error”. ( Discussion of ‘strict’ vs ‘non-strict’ is beyond the scope of discussion for this read)</p><p>But sadly, the result of console.log() will be <strong>“z = 5”</strong>. But why ??</p><p>Well, the reason is JavaScript is built in this fashion, everything is functional scope. So even if you have something declared in <strong>if-else</strong> or <strong>for/while/do-while </strong>loops clause or in any block, that variable is populated in the scope of that function. So the scope will look something like this after the engine has executed the code.</p><pre>Scope =&gt; [(abc) =&gt; {a: true, z: 5}]-&gt;[(global) =&gt; {}]</pre><p>To solve this problem two new keywords “let” and “const” were introduced in the ES6 (ES2015) version of JS.</p><pre>function abc() {<br>  var a = true;<br>  if(a){<br>      let z = 5;<br>   } else {<br>      let z = 6;<br>    }<br>   console.log(&quot;z = &quot;, z);<br>}</pre><pre>abc();</pre><p>Now using the “let” keyword you’ll get “Reference Error” when the engine executes console.log(z);</p><p>And the scope will look like this.</p><pre>Scope =&gt; [(abc) =&gt; {a: true}]-&gt;[(global) =&gt; {}]</pre><p>So this is the end of this article, It was a long read but I hope you learned something today or had your concepts refreshed. In case of any discrepancy do reach out. For any further communication, you can reach out to me at jainishshah12@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da08a1601f2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/yeh-lexical-scope-hai-kya-da08a1601f2f">Yeh lexical scope hai kya?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Security Policy — What You Need to Know?]]></title>
            <link>https://medium.com/swlh/content-security-policy-what-you-need-to-know-ffbce22336d6?source=rss-6a2a31dd9c44------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffbce22336d6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[content-security-policy]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Jainishshah]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 13:02:45 GMT</pubDate>
            <atom:updated>2020-12-15T21:00:34.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Content Security Policy - What You Need to Know?</h3><p>Aloha developers, this is Jainish, SDE-1 @ Innovaccer Analytics. To give you a brief I am a JavaScript Dev working on creating resilient reusable components in React.js. I and my team are working on creating a platform for hosting, creating, and managing Dashboards for our Health Care partners in the United States. We have created a plethora of features like Click Based Dashboard creations, Permission Module for ACL, easy Alerts Creation, to name a few.</p><p>Last week I was in a Sprint Planning meeting, discussing creating a Publish Management Service for maintaining the controlled flow of Dashboards in our platform. As a part of this feature, the users will easily be able to push created PowerBi powered dashboards(.pbix file) to our platform and need not worry about setting basic permissions and configurations.</p><p>We came up with an end-to-end workflow where first the file will be uploaded to AWS S3 bucket, once the upload is complete we call REST-API with all metadata to ask the backend to trigger a job that will take care of all the configurations. Sounds easy peasy right??</p><p>We had 2 plans either to integrate ASW-SDK in node.js, used as a jump server in our case, or using the amazing concept of Pre-Signed URL provided by AWS. We chose to use the latter. The process is simple</p><ol><li>Provide metadata about directory structure and file and generate the pre-signed URL.</li><li>Use this pre-signed URL and Promise base HTTP-client library like Axios/Fetch API to upload this file to S3.</li></ol><p>All parts worked pretty fine, but the last step of uploading failed giving an <strong>error</strong>: <strong>Refused to connect to ‘${pre-signed URL}’ because it violates the following Content Security Policy directive: “connect-src”</strong>. At this point, I had no clue what CSP even was. I went to reading out a few blogs and found a fix. From my experience, this is what we must know about how modern browser works.</p><p>Well, many of you would have heard about XSS in Web Security class. Lets’s recap this a bit.</p><p><strong>“Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end-user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.”</strong></p><p>The statement stands for itself, but to give you a little more background let&#39;s talk about how Web Security works.</p><p>The basis of the Web Security model is “<strong>same-origin policy</strong>” i.e Code from one origin “https://goodOrigin.com” only should have access to its data and some other origin eg “https://badorigin.com” should never be allowed. This provides goodOrigin isolation from the rest of the web, and this sounds wonderful. But in practice, attackers have found a way around it.</p><p>Browser by default will accept all the code that comes up with the page from goodOrigin considering it to be true as there is no violation of the same-origin policy. This is how it should work, but wait till it gets tricky, what if the attackers inject some malicious code that is shipped along with the intended code. In a way, the attacker bypassed the “same-origin policy”. Since browsers will believe this to be legitimate it will run those scripts and we are DOOMED!!!!! . Millions of dollars in litigation depending on the type of data you deal with.</p><p>For preventing this we need the browsers to be smart, but how will browsers know what is legitimate and what is not? You guessed it right, CSP.</p><p>Instead of trusting everything received from the server, CSP creates a Content-Security-Policy HTTP header. It is where you define the list of all the allowed origins from where the scripts can be loaded and executed. Even if the attacker manages to inject the script, he will not be able to modify the http header and the browser will check that it violates the CSP and will throw an error instead of executing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*vCUQ1BrnUD0gWlTMeKWJDA.png" /></figure><p>There is a list of directives that you can find <a href="https://developers.google.com/web/fundamentals/security/csp">here</a>. eg Let say you want to execute some script from “apis.google.com”. You can add ascript-src directive that controls a set of script-related privileges for a specific page. Since we want scripts from goodOrigin and &quot;apis.google.com&quot; to run. We&#39;ll specify Content-Security-Policy: script-src :&#39;self&#39;,https://apis.google.comin our<strong> r</strong>esponse headers. The browser dutifully downloads and executes JavaScript from apis.google.com over HTTPS, as well as from the current page&#39;s origin.</p><p>But my problem is still not solved yet, I want to connect to my S3 bucket, I am not loading any script, so why should it fail !!. Turns out CSP is more than just scripts. It also enforces fonts, images, styles-scripts, Url over which you can connect to via XHR/WebSockets, etc. In my case, I was trying to make an XHR request, so I had to use the <strong>connect-src </strong>directive where I defined the base URL of the S3 bucket “https://{BucketName}.s3.amazonaws.com and Voila, we are done.</p><p>Note: if the CSP is not defined, the browser will trust everything it gets. So if I hadn’t defined CSP in the first place I would have never encountered this issue. It is though a good practice to implement CSP if you deal with sensitive data. Also, this is not just a single way to implement it. We can specify CSP in the &lt;head&gt; section of HTML but the most secure way is the HTTP header as it can’t be tampered with. CSP just reduces the risk of XSS and is not a complete solution as we have smart people who know how to get a way around.</p><p>Hope you found this article interesting and you probably learned something. Also, it&#39;s the first article I have written and I know there is a scope of error. Constructive Criticism is always welcomed.</p><p>You can contact me on my email: “jainishshah12@gmail.com” for further communication.</p><p>Ref:</p><ul><li><a href="https://owasp.org/www-community/attacks/xss/">Cross Site Scripting (XSS) | OWASP Foundation</a></li><li><a href="https://developers.google.com/web/fundamentals/security/csp">Content Security Policy | Web Fundamentals | Google Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffbce22336d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/content-security-policy-what-you-need-to-know-ffbce22336d6">Content Security Policy — What You Need to Know?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>