<?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 Kush Misra on Medium]]></title>
        <description><![CDATA[Stories by Kush Misra on Medium]]></description>
        <link>https://medium.com/@kushmisra7?source=rss-4dd1cbd61545------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xf_YuzhKHUE-Vt7d.jpg</url>
            <title>Stories by Kush Misra on Medium</title>
            <link>https://medium.com/@kushmisra7?source=rss-4dd1cbd61545------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:23:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kushmisra7/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[Push intelligence in your Components backed by ElasticSearch!]]></title>
            <link>https://medium.com/@kushmisra7/push-intelligence-in-your-components-backed-by-elasticsearch-d5761ab4383d?source=rss-4dd1cbd61545------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5761ab4383d</guid>
            <category><![CDATA[ui-interaction]]></category>
            <category><![CDATA[intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Kush Misra]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 18:57:36 GMT</pubDate>
            <atom:updated>2021-04-09T18:57:36.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*oK0JQymrJCK8PGuGNDaVZA.jpeg" /></figure><p>There are a lot of places where we use a search component that is backed by tons of data. ElasticSearch comes as a natural solution to almost all such problems as it provides an easy and efficient way to manage and search vividly across data. I strongly recommend that you go through ElasticSearch if you have lots of data and want fast and seamless searching.</p><p><a href="https://www.elastic.co/what-is/elasticsearch">What is Elasticsearch?</a></p><p>From hereon this article expects that you have your search component backed by elastic search. Please move to the next section if you have a fair understanding of the difference between an efficient and an intelligent component.</p><p>Let&#39;s take an example of a general <strong>Autocomplete suggestion component</strong>. Assume it to be a simple UI component that sends whatever is typed in it to the elastic server and shows whatever results are returned. As it&#39;s backed by ElasticSearch, you will get really nice speed and if you have correct analyzers set in elastic search then you will get good meaningful results as well. But will your autocomplete be intelligent enough? … umm … maybe not !!</p><p>There are two aspects to the results which are returned by the elastic search. Whenever a user types something, there are two pieces of information that are there with you, based on which you can decide what results to show:</p><ol><li>Search query which user typed.</li><li>Metadata about the user: Who is the user actually? In what geographical location is your component used? and any other meta data about the user which might be useful in your context.</li></ol><p>Generally, Autocomplete components focus on 1st part (the search query) and try to return results. To tackle 1st problem you should have good rules (optimized indexing, analyzers, etc. ) set in elastic search and it will automatically take care of the rest. <strong>If you cater to only 1st part, you will be building an efficient auto-complete at best, but not an intelligent one</strong>. An intelligent autocomplete is one which is able to decipher user metadata, get feedback on what the user selected, and learn on its way. Such autocompletes, over time, show the most optimized results.</p><p>Let&#39;s take an example to understand this. Suppose that you are using an autocomplete suggester which shows a list of all cities which are relevant to the text you typed. Also, suppose that you live in India. As we have all the cities in our backend, we have a lot of data. Now, if you type any letter, say “D”, there are a lot of cities which can be returned. If we only focus on the search query (in this case “D”) then any city starting with D should come. An <strong>efficient auto-complete</strong> whose scope is only searched query will return all the cities starting with “D” with the same weight. But in case you have previously selected Delhi once, then an <strong>intelligent (and efficient of course :P ) autocomplete</strong> will return “Delhi” with more weight as compared to other results. This is just an example, where we used history to determine which result should have more value. We could have also used the geographical location to suggest nearby cities first.</p><p>Now, once you have understood what our aim is, let&#39;s deep dive into how to make our autocomplete suggester intelligent.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl2Je1bFuOpkNpyqYM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl2Je1bFuOpkNpyqYM%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl2Je1bFuOpkNpyqYM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="333" frameborder="0" scrolling="no"><a href="https://medium.com/media/311353b307627e8294e20f9fd326f1d0/href">https://medium.com/media/311353b307627e8294e20f9fd326f1d0/href</a></iframe><p>There are two aspects that are involved in making your component intelligent:</p><ol><li><strong>Static meta-information</strong>. This can include the type of user, location of the user, and any other metadata which can affect your search results. This information is not expected to change and will (in almost all cases) remain the same throughout time. Meta-information about documents can also be very useful in addition to meta-information about users.</li><li><strong>Usage history of the user</strong>. The usage history of the user is more important of the two according to me. It&#39;s because this can eventually remove the need to have user metadata. What did users select for a given query in the past is very crucial in understanding what they might select in the future as well.</li></ol><p>For catering to 1st aspect, elastic search has something called <strong>function_score</strong>.</p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html</a></p><p>It lets you change the score of a given document (against a certain query). As static meta-information is not changing, you can prepopulate your document in elastic search with meta-information and later use it inside function_score in elastic search. For example, let&#39;s say we want to suggest cities that are closer to the user’s current location. Then for every city in your document (in elastic search), you can also save its country and its continent. When a user types something, say “D”, all cities starting with “D” will be passed through <strong>function_score</strong>. We will also pass the current location (city, country, and continent) of the user in params to function_score. If a city has the same continent as that of the user’s country, we will increase its relevance by returning a higher score. If the country is also the same, then we will increase the relevance even more. This way we will be able to suggest countries that are nearer to the current user.</p><h4>Normalized score in Elastic search</h4><p>There is no way to get a normalized score from elastic search. The score for every document is a pure function of that document itself. Hence to get a normalized score, you will have to send a query (pilot query) and get max_score out of it. Then you will have to send another query and use function_score to normalize the scores of every document using max_score you got in the pilot query. I’ll suggest you make your pilot query very light by specifying the size as 1.</p><p>For deriving inference from the user’s historical usage, we will have to save something about usage history somewhere. If you already have an ML model which can take in user metadata and user search query and return you some metric which helps you rank results better then you can integrate it in between your frontend and elastic server. Read <a href="https://medium.com/@DoorDash/powering-search-recommendations-at-doordash-8310c5cfd88c#:~:text=Personalization%20in%20Elasticsearch,-Now%20let&#39;s%20discuss&amp;text=This%20script%20has%20access%20to,to%20get%20the%20desired%20ranking.">this</a> for more reference.</p><p>But what if you are starting from scratch ?? you don&#39;t have any user information stored ?? Don&#39;t worry, we have a way ahead for you as well :). There is a very nice blog by elastic search to increase the relevance of documents by their popularity, which doesn&#39;t require any previous data. I highly recommend going through <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/boosting-by-popularity.html"><em>this</em></a> post. It simply says that we should keep a field called popularity in our document and increment it by one whenever a user selects it. Then whenever we are returning results from elastic search, more relevance will be given to docs with higher popularity. We can also update a separate database whenever the user selects an option, this will create a usage database for us to use. This is the most basic form of intelligence you can add to every autocomplete suggester. This will work when you don&#39;t have any user data or any other data to start with.</p><p>Also, note that not only this will give you a headstart in personalization, it will also build a dataset for you. You can later use it to train a better ML model and make it sit between UI and elastic search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5761ab4383d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phonetic posteriorgrams and the magic theycan do for audio!]]></title>
            <link>https://medium.com/@kushmisra7/phonetic-posteriorgrams-and-the-magic-theycan-do-for-audio-ae426edd3de2?source=rss-4dd1cbd61545------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae426edd3de2</guid>
            <category><![CDATA[phonetics]]></category>
            <category><![CDATA[audio-programming]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[voice-conversion]]></category>
            <dc:creator><![CDATA[Kush Misra]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 10:05:05 GMT</pubDate>
            <atom:updated>2020-08-23T10:05:05.477Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phonetic posteriorgrams and the magic they can do for audio!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCR9T1iF5Z3AypwxM3M9MQ.jpeg" /></figure><p>Not to beat around the bush, let&#39;s just start with what phonetic posteriorgram is, how to generate it, and finally how to use it in different applications.</p><p>Whenever we speak, there are certain sounds we make. Just like alphabets are the basic building blocks to record what you have said in a language context. Phonemes are the basic building blocks to record what you have said in vocal context (basically the sound you make). Wait, but what exactly do you mean by vocal context :confused:?</p><p>So whenever you write something, the meaning of what you have written is defined (if you don&#39;t write ambiguous sentences on purpose). But the way it is spoken is different. Someone might say it in a way and someone else might speak it in a different way. There are many differences such as accent, understanding, etc. Hence in a language context, you define the meaning and keep the vocal part variable. Whereas, in case of vocal context, you keep the vocal part (how to speak it, the sound of it) constant and the meaning it has to convey as a variable. After we analyze our audio in vocal context (using phonemes), everyone who can understand it will speak it in exactly the same way as you did.</p><blockquote>A <strong>phoneme</strong> is the smallest unit of sound in speech. Any of the perceptually distinct units of sound in a specified language that distinguish one word from another.</blockquote><p>Despite there being just 26 letters in the English language there are approximately <strong>44</strong> unique sounds, also known as <strong>phonemes</strong>. For a list of them please refer: <a href="https://www.dyslexia-reading-well.com/44-phonemes-in-english.html">https://www.dyslexia-reading-well.com/44-phonemes-in-english.html</a> .</p><p>Now phonetic posteriorgram is a record of which phoneme you told at what time. For example, if you spoke for 10 minutes, then an audio file will record your amplitude (, pitch, etc) movements over time and a phonetic posterior gram will record which phoneme you told when. The phonetic posteriorgram is a graph in which the x-axis is time and the y-axis contains distinct phonemes. For any given time in x-axis, there can be a number of phonemes you spoke. Hence you will get a probability of which phoneme out of all you likely said. For example, the below image is an example of “basketball and baseball”. The darker a point, more the probability of that particular phoneme ( make a horizontal line through the point and phoneme will be the point at which this line touches y-axis) being spoken at that particular time ( make a vertical line through the point and time will be the point at which this line touches x-axis). Hence you can visualize phonetic posteriorgram as a probability distribution of which phoneme you spoke and when.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*4gVoJ0WKY69lBK5K9p4_JQ.png" /></figure><p><strong>How to generate a phonetic posteriorgram ?</strong></p><p>You can train a neural network that will take audio as an input and output a phonetic posteriorgram. It can be a Bi-LSTM network. You need to take some dataset which has this phoneme knowledge in it. <br>Some good datasets to train your model with are:</p><p>1. TIMIT Dataset: <a href="https://catalog.ldc.upenn.edu/LDC93S1">https://catalog.ldc.upenn.edu/LDC93S1</a><br>2. CMU Arctic dataset: <a href="http://www.festvox.org/cmu_arctic/">http://www.festvox.org/cmu_arctic/</a></p><p>Wait does that mean you will have to structure a model and train it (for days) to get this powerful thing to work?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*msbOIxVRvXwc5bG9-PNcHQ.gif" /></figure><p>Whereas it&#39;s possible to generate phonetic posteriorgram from scratch, you can always cut short and use already implemented ones. You will not get a good phoneme extraction model straight, but they are implemented as a part of some widely accepted works. These works are recognized by good conferences/journals and are a testimony to what power phonetic posteriorgrams hold and what are their applications. Some of them are :</p><p>1. <a href="https://github.com/guanlongzhao/fac-via-ppg">https://github.com/guanlongzhao/fac-via-ppg</a> : This uses phonetic posteriorgrams for accent conversion. It&#39;s very easy to extract out phonetic posteriorgram from this work as they have implemented this as the first step of their work. They have a pre-trained model also , which you can directly leverage. <br>2. <a href="https://github.com/andabi/deep-voice-conversion">https://github.com/andabi/deep-voice-conversion</a> : This uses phonetic posteriorgram for voice conversion. They have their “net1&quot; as a phoneme classifier and you can easily extract that out.</p><p><strong>Applications of phonetic posteriorgrams ?</strong></p><p>Phonetic posteriorgram is a tool to capture speech and has multiple applications associated. Some include :</p><p>1. <strong>Accent conversion</strong>: As phonemes tell you how something is spoken they become a natural choice for accent conversion. For example : say there is a person “A”, who spoke “Hi! hope you like this post”. We record it using a phonetic posteriorgram and then we train a decoder to read out this phonetic posteriorgram in person “B”’s voice. <br>2.<strong> Voice conversion</strong>: Voice conversion is also a very basic application of phoneme generation.<br>3. <strong>Fake Voice Generation: </strong>If you train a decoder which can read phonetic posteriorgram in someone’s voice ( which is also easy to do), then you practically have the power to make audios in which that person is heard speaking anything you want. (Don&#39;t use it for evil reasons, the cyber police are still there remember :stuck_out_tongue: ! )</p><p>If you find some good use case of phonetic posteriorgrams, do let me know <br>:joy:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae426edd3de2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One report for all test cases: Easily merging multiple tests reports]]></title>
            <link>https://medium.com/@kushmisra7/one-report-for-all-test-cases-easily-merging-multiple-tests-reports-b0f5e5211a2a?source=rss-4dd1cbd61545------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0f5e5211a2a</guid>
            <category><![CDATA[merging-test-reports]]></category>
            <category><![CDATA[karma]]></category>
            <category><![CDATA[istanbul]]></category>
            <category><![CDATA[mocha]]></category>
            <dc:creator><![CDATA[Kush Misra]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 20:03:12 GMT</pubDate>
            <atom:updated>2020-04-10T20:03:12.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6AoE2CuT7ZUHGJMp9qqIg.jpeg" /></figure><p>It&#39;s can be easily the case that you use different test runners for different kinds of your tests. You can choose to run the unit, interaction, and integration tests separately. You may have some smoke tests as well which run separately from exhaustive tests.</p><p>In such a case, you will get different test reports from every group of tests you run. This will pose problems in analyzing if test cases are actually sufficient for the whole application or not. With multiple reports at hand, the hefty task of knowing the exact code coverage will be left to your discretion, leaving you like Garfield below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZNnQvIYzIBmZAbrBR7%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZNnQvIYzIBmZAbrBR7%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZNnQvIYzIBmZAbrBR7%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/1df58df2523b118cdfba4175828cfe94/href">https://medium.com/media/1df58df2523b118cdfba4175828cfe94/href</a></iframe><p>But to your rescue, it is very easy to generate a combined test report from multiple test reports after Istanbul shifted to a mono-repo architecture.</p><p><a href="https://github.com/istanbuljs/istanbuljs">istanbuljs/istanbuljs</a></p><p>Irrespective of any test runner/ testing framework you use (eg karma, jest, cypress, etc), you can always instruct it to use istanbul for generating code coverage (if it&#39;s not using istanbul by default).</p><p>Whenever istanbul generates a report, it generates one thing in it which is of prime importance to us. That is <strong><em>coverage-final.json</em></strong> file. You can instruct istanbul through your test runner/ framework to generate coverage reports in a specified folder. So you will be having multiple coverage-final.json generated by different test groups.</p><p>You can use <strong>libCoverage </strong>from <strong>‘istanbul-lib-coverage’ </strong>to merge various coverage-final.json and generate a source map out of it. (<em>Below code is inspired from istanbul-lib-coverage readMe</em>):</p><pre>import libCoverage from &#39;istanbul-lib-coverage&#39;;<br>import _ from &#39;lodash&#39;;</pre><pre>let map = libCoverage.createCoverageMap();<br>let summary = libCoverage.createCoverageSummary();<br><br>_.forEach(coverageJSONs, (json) =&gt; {<br>     const jsonCoverageMap = libCoverage.createCoverageMap(json);<br>     map.merge(jsonCoverageMap);</pre><pre>});<br><br>// inspect and summarize all file coverage objects in the map<br>map.files().forEach(function(f) {<br>    var fc = map.fileCoverageFor(f),<br>        s = fc.toSummary();<br>    summary.merge(s);<br>});<br><br>console.log(&#39;Global summary&#39;, summary);<br>console.log(&#39;Merged coverage JSON&#39;, map.toJSON());</pre><p>In the example above, coverageJSONs is an array containing all the <strong>coverage-final.json</strong> generated. <strong>map.toJSON()</strong> will give an output similar to <strong>coverage-final.json </strong>and will contain information regarding merged coverage of all the coverageJSONs. <strong>summay</strong> variable will contain the overall summary (as in % of lines, branches, statements, functions, etc covered).</p><p>So far we have only generated a merged coverage map that has all the information regarding total combined code coverage. We can generate different formats of reports from this coverage map as follows:</p><pre>const libReport = require(&#39;istanbul-lib-report&#39;);<br>const reports = require(&#39;istanbul-reports&#39;);<br><br>// create a context for report generation<br>const context = libReport.createContext({<br>  dir: &#39;path/where/you/want/output&#39;,<br>  defaultSummarizer: &#39;nested&#39;,<br>  coverageMap: map, <br>// this is the map which we generated in above snippet<br>})<br><br>// create an instance of the relevant report class, passing the<br>// report name e.g. json/html/html-spa/text<br>const report = reports.create(&#39;html&#39;)<br><br>// call execute to synchronously create and write the report to disk<br>report.execute(context)</pre><p>The above snippet generates html report in the folder specified in ‘dir’. In fact you can specify any format listed here: <a href="https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib">https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib</a>.</p><p>This way, by combining the above two snippets, you can generate combined code coverage in any format you want.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F10843280&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fdone-and-done-spongebob-finished-just-did-it-gif-10843280&amp;image=https%3A%2F%2Fmedia.tenor.com%2F93OUVuCIk6MAAAAN%2Fdone-and-done-spongebob.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3582d6c98a46d7f3ba6819329c0a4317/href">https://medium.com/media/3582d6c98a46d7f3ba6819329c0a4317/href</a></iframe><p>If you don&#39;t have yet started with your testing infrastructure, it will be nice if you have a look at nyc (istanbul’s cli). It has some good features, including merging of test reports: <a href="https://github.com/istanbuljs/nyc#combining-reports-from-multiple-runs">https://github.com/istanbuljs/nyc#combining-reports-from-multiple-runs</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0f5e5211a2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS *This* made that simple]]></title>
            <link>https://medium.com/@kushmisra7/js-this-made-that-simple-244498deafc5?source=rss-4dd1cbd61545------2</link>
            <guid isPermaLink="false">https://medium.com/p/244498deafc5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[this]]></category>
            <dc:creator><![CDATA[Kush Misra]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 20:47:26 GMT</pubDate>
            <atom:updated>2019-09-03T20:47:26.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ktqrkdUYQCvEkTMjzQarUQ.jpeg" /></figure><p>… and one of the reasons for those hidden deeply felt tears is *this* in JS.</p><p>For better readability, I will refer to *this* keyword as *this* and normal English this as normal this.</p><p>*this* keyword can be a confounding factor for new as well as seasoned JS developers. Behaviour or *this* in JS is significantly different from the way *this* behaves in other languages such as C++, Java etc. Many times people tend to indulge in ways which can help them avoid encountering *this*. Using techniques such as that = this and getting a clear reference of *this* is one such example. While it is not outrightly wrong to use such techniques but using these only to avoid using *this* isn’t ethical on part of those who like to be called experienced JS developers. Furthermore, it will be more rewarding to embrace the power of *this* and free yourself from the everlasting fear of it.</p><p>Before jumping on to the rules, it should be clear that value of *this* depends only on the calling site. Same function being called in different ways can have different *this* inside it. Hence whenever you want to know what does *this* refer to inside any function, you should look for its calling site.</p><p>Majorly there are 4 rules that govern the value which this holds:</p><ol><li>Using new keyword</li><li>explicit binding</li><li>implicit binding</li><li>global reference (default)</li></ol><p>Lets deep dive into each one of these to see what really happens in them.</p><h3>1. Using new keyword</h3><pre>function pirate(name) {<br>  this.name = name;<br>}</pre><pre>var superbPirate = new pirate(&#39;Captain Jack Sparrow&#39;);</pre><pre>console.log(superbPirate.name);</pre><p>Comprehending this when you invoke a function using new keyword is by far the easiest. Every time you use new to access function, a brand new object is created and passed as *this* to the function. Hence you will get a brand new object as *this*, to which you can attach your desired properties. If function explicitly doesn&#39;t return anything, this brad new value which is referenced as *this* inside it is returned.</p><p>In the example considered, when we invoke pirate as new pirate(), a brand new object is made available to us inside pirate as *this*. We attach some properties to it and return nothing. By default *this* (to which we have attached properties) gets returned.</p><p>So care must be taken if you want to access something from this inside a function invoked using new.</p><h3>2. Explicit binding</h3><pre>function pirate() {<br>  console.log(this.name)<br>}</pre><pre>var superbPirate = {<br>  name: &quot;Captain Jack Sparrow&quot;<br>};</pre><pre>pirate.call(superbPirate);</pre><p>When it&#39;s utterly confusing what will be the value of *this* inside any function, you can explicitly specify this binding. Using apply, call and bind developer has the power to force what *this* should refer to.</p><p>call()/apply() can be used to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context (*this*) for calling the original function. So bind() can be used when the function needs to be called later in certain events when it&#39;s useful.</p><p>While it may seem fairly easy till now, it isn’t a cakewalk when rules are combined. Consider the following snippet and try to answer what will be printed.</p><pre>function pirate() {<br>  console.log(this.name)<br>}</pre><pre>var superbPirate = {<br>  name: &quot;Captain Jack Sparrow&quot;<br>};</pre><pre>var boundFunc = pirate.bind(superbPirate);</pre><pre>boundFunc();</pre><pre>var anotherSuperbPirate = new boundFunc();</pre><p>In this case, we have explicitly bonded superbPirate to pirate and stored the bonded function as boundFunc. Calling boundFunc() will essentially invoke pirate with *this* binded to superbPirate object. Hence when we try to output this.name we get “Captain Jack Sparrow”. But what will happen in case of invoking boundFunc with new?? Which rule will get precedence. New gets precedence over other rules and hence function pirate will receive a brand new object as this inside it. Referring this.name will result in undefined.</p><p>For your convenience, rules have been listed in precedence order above.</p><h3>3. Implicit binding</h3><pre>var superbPirate = {<br>  name: &quot;Captain Jack Sparrow&quot;,<br>  callOut: function() {<br>    console.log(this.name);<br>  }<br>};</pre><pre>superbPirate.callOut();</pre><p>In this case, superbPirate has a property callOut which is a function. Calling this function with property accessor (.) will lead auperbPirate object as *this* inside the function. In general, any function invoked as customObject.func() will have customObject as *this* inside the function.</p><p>While it may sound intuitive, there are some pitfalls here too,</p><pre>var superbPirate = {<br>  name: &quot;Captain Jack Sparrow&quot;,<br>  callOut: function() {<br>    console.log(this.name);<br>  }<br>};</pre><pre>var callOut = superbPirate.callOut;<br>callOut();</pre><p>What do you think will be the output in this case?? Remember to look for the calling site. The result we get is undefined. We will ponder over why we get undefined in some time, but let&#39;s tackle why *this* doesn&#39;t refer to superbPirate. It is because the calling site here is not superbObject.callOut, its just callOut. Copying the function superbPirate.callOut to another variable callOut only copies the function reference and hence variable callOut doesn&#39;t have even a dab of an idea that the function which is being called is in fact defined inside superbObject. Remember that objects don&#39;t own functions in JS.</p><p>Another thing which should be taken care of is shown below:</p><pre>var superbPirate = {<br>  name: &quot;Captain Jack Sparrow&quot;,<br>  callOut: function() {<br>    console.log(this.name);<br>    console.log(this.grandMaster);<br>  }<br>};</pre><pre>var greatestPirate = {<br>  grandMaster: &quot;Teak&quot;,<br>  son: superbPirate<br>};</pre><pre>greatestPirate.son.callOut();</pre><p>What will be the output here ?? calling site is pretty clear here. But here we have multiple value accessors. Will *this* refers to greatestPirate or greatestPirate.son ??</p><p>It is important to note that only last reference is regarded as that is the object which is actually calling the function. Hence in the example above greatestPirate.son (which is nothing but superbPirate) will be passed as *this*. Console.log(this.grandMaster) will result in undefined.</p><h3>4. Global reference (default)</h3><p>When a function is invoked stand-alone with none of the above rules applying, then *this* refers to the global object.</p><pre>var name = &quot;Captain Jack Sparrow&quot;;</pre><pre>function callOut() {<br>  console.log(this.name)<br>}</pre><pre>callOut();</pre><p>Here as the calling site is standalone, no implicit/explicit binding or calling using new keyword, *this* is a reference of the global object. Hence this.name will refer to the global name variable.</p><h3>Combining all of it together</h3><pre>function callOut() {<br>  console.log(this.name)<br>}</pre><pre>var name = &quot;Global Captain Jack Sparrow&quot;;</pre><pre>var superbPirate={<br>  name: &quot;Captain Jack Sparrow&quot;,<br>  callOut: callOut<br>}</pre><pre>var grandMaster={<br>  name: &quot;teak&quot;<br>}</pre><pre>callOut(); // Global Captain Jack Sparrow // global reference (default)<br>callOut.call(grandMaster); //teak // explicit binding<br>superbPirate.callOut(); //Captain Jack Sparrow // implicit binding<br>var pirate = new callOut();//undefined//new object passed as *this*</pre><p>All the rules can be seen applied in the above snippet.</p><h3>Using this in React</h3><p>In react (or web development in general) there are cases when you need to send some function as a callback function or invoke another function which is not defined in the context of present execution. *This* can be challenging in some of those cases and it is important to understand *this* to harness the full power of react.</p><p>There are some prebuild tools which can help you automatically bind *this* in react. One such tool is @autoencoder decorator. It bind a single function or all the functions in a class to class context. Hence *this* inside those functions will refer to the class context. So you need not worry what the value of *this* will be as it will almost always be the class context.</p><p>There is one small, yet straight-forward, pitfall here too. Somehow developers tend to miss some nuances of this even knowing the rules governing *this*.</p><pre><a href="http://twitter.com/autobind">@autobind</a><br>class Parent extends React.Component {<br>   function printThisReference() {<br>     console.log(this);<br>   }<br>}</pre><pre>class Child extends Parent {<br>   this.printThisReference();<br>}</pre><p>What will the output of the snippet above ? ( snippet is for demonstrating the concept and is not intended to run on JS platform as it is). Will @autobind do its magic or implicit binding will overpower it?</p><p>Here implicit binding wins. *this* will refer to Child component even though all the functions in Parent class are auto bond. These minor nuances should be taken care of while using this in JS.</p><p>It is no harm to activate a debugger inside the function and actually see what *this* refers to. This will clarify your doubts and doubly check that *this* refers to what you wanted it to refer.</p><h3>*This* and arrow functions</h3><p>Please note that the way in which ES6 arrow functions behave is different from normal functions, especially in regard to this binding. Arrow functions use the current context *this* (at runtime) and pass it as *this* inside the function body. In simple words, when an arrow function is encountered, *this* inside it refers to the context of the container containing the arrow function.</p><h3>want to dig deeper into JS</h3><p>I am also a newbie in JS , but whatever I have gone through made me realize that “you don’t know JS” is a really cool start for getting deeper into the concepts of JS and getting a good hold of how things work.</p><p><a href="https://github.com/getify/You-Dont-Know-JS">https://github.com/getify/You-Dont-Know-JS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=244498deafc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>