<?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 Pranav Jindal on Medium]]></title>
        <description><![CDATA[Stories by Pranav Jindal on Medium]]></description>
        <link>https://medium.com/@pranavjindal999?source=rss-c6351a9383e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5zahiwIyOEMlmoSkiMS5Qg.jpeg</url>
            <title>Stories by Pranav Jindal on Medium</title>
            <link>https://medium.com/@pranavjindal999?source=rss-c6351a9383e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranavjindal999/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I debug Javascript Code I didn’t write]]></title>
            <link>https://itnext.io/how-i-debug-javascript-code-i-didnt-write-6c405a6a9103?source=rss-c6351a9383e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c405a6a9103</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Pranav Jindal]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 07:33:21 GMT</pubDate>
            <atom:updated>2019-09-11T14:40:20.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WaJ9sVm3o3EGr2KktN1Ow.png" /></figure><h3>How I debug Javascript code I didn’t write</h3><p>When debugging a code that you have not written, especially JavaScript code, things get real messy and convoluted. Thanks to Javascript’s single threaded approach and <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">event-loop</a>, the code doesn’t generally move in a straight direction. There can be async/sync callbacks, XHRs, timeouts/intervals, event listeners, promises and what-not, that <em>“help” </em>make your code NOT work in a straight forward way and it becomes very easy to get lost in finding what direction the code is moving.</p><p>At times, this gets very frustrating to find out God-knows-what-part of code changed some value to what it was not intended to be. I work on an Angular.js application which is fairly complex and has a lot of watches, event listeners, async calls that make it quite hard to follow.</p><p>Let’s say, we have got a bug where $scope.notifications.usage_exhausted was intended to be true, but somehow gets changed to false when you click a button and you have no idea what code did that. Generally, you will start with an approach to find out what that value does, what that button does, where are the places that value is set, what all input fields have set that property as ng-model (angular&#39;s ways of defining auto-sync model to an input field), etc. This way works but it can waste a lot of time looking at code that is not the culprit and making you feel <a href="https://hackspirit.com/what-am-i-doing-with-my-life-5-steps-to-finally-work-it-out/"><em>what am I doing in life?</em></a> What if I could just somehow <em>watch</em> changes to $scope.notifications.usage_exhausted when I click that darn button?</p><p>Well, you can exactly do that with following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/215103cd60bd82ae099cb04ce10e1aaf/href">https://medium.com/media/215103cd60bd82ae099cb04ce10e1aaf/href</a></iframe><p>What this snippet does is, it replaces that property on object with JavaScript’s native <a href="http://javascript.info/property-accessors">getters/setters</a> that behave exactly like a normal property but with a debugger at your disposal whenever the property-you-want-to-watch changes. All you need to do is, watch the property when it was correct or not defined.</p><pre>// watch when it was correct or undefined<br>watchProperty($scope.notifications, &#39;usage_exhausted&#39;);</pre><p>Now, whenever $scope.notifications.usage_exhausted changes due to any code throughout the application, you’d get a breakpoint and all you need to see now is, the stack trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGwj2ACKiuAafwRoqB-dMg.png" /><figcaption>Auto debug point when the value changes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SKkAh57GOyKNSM-VR3l5Q.png" /><figcaption>Previous step in call stack</figcaption></figure><p>And you exactly know where the value got changed. Had you been debugging the problem the normal way, you’d have had couple of breakpoints till now and still be debugging.</p><p><strong>The scenario (button click) I mentioned is quite simple, but sometimes values change without any user action due to some delayed XHR calls, or timeouts/intervals, or anything async and that is when such cases become very difficult to pin-point the problem with traditional debugging approaches.</strong></p><h3>Watching Arrays</h3><p>You can similarly watch changes to array indices too, to find what code sets at a particular index.</p><pre>watchProperty($scope.projects, 3)</pre><p>This will trigger a debug point whenever 3rd element on $scope.projects is set. Though this won’t help when 3rd element is pushed into the array. To mitigate this issue, we can create a new function to watch any changes on an array and can be coded as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae1df9f62b3370a6893aa51db501abd/href">https://medium.com/media/bae1df9f62b3370a6893aa51db501abd/href</a></iframe><p>Here we <em>hide</em> the actual push, pop and splice methods of <a href="https://medium.com/free-code-camp/prototype-in-js-busted-5547ec68872">Array.prototype</a> by creating these methods on the array itself. Now whenever, any part of code calls any of these <em>mutating</em> methods of<strong> that particular array,</strong> you’d have breakpoint and then again you can see the call stack to trace the problem.</p><p>You can create such debuggers for any type of code. Let’s say you use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a>s in your application and you want to debug a particular <a href="https://medium.com/free-code-camp/prototype-in-js-busted-5547ec68872">instance</a> of Set. Simply write another code snippet like watchSet (as we wrote watchArray above), to watch whatever function you’d like to watch.</p><p><strong>You can add multiple watches or nested watches on objects for the properties that you are interested in. <em>You can even add watchers while you are deep inside breakpoints for cases when the new value itself is an object and you have to watch a property on new value.</em></strong></p><h3>Caveats</h3><p>This way of debugging is not flawless and has few limitations where such tricks don’t work, which are:</p><ul><li>If a property is deleted using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a> operator, this operation can not be detected and hence will go unnoticed.</li><li>If a property in your code is defined using Object.defineProperty / Object.defineProperties, that would cause the watcher to get overwritten and you’d have to watch it again.</li><li>Something I can not think of right now.</li></ul><p>Frameworks like Vue.js, that themselves use getters and setters for change detection and reactivity have been taken care of in the watchProperty snippet by getting the original getter/setter using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor">Object.getOwnPropertyDescriptor</a>, saving them in the closure and calling them with correct this when getter/setters are called.</p><h3>Helper Chrome Extension</h3><p>Now creating these methods every time you want to debug is a problem, for which<strong> I use this awesome </strong><a href="https://chrome.google.com/webstore/detail/user-javascript-and-css/nbhcbdghjpllgmfilhnhkllmkecfmpld?hl=en"><strong>Chrome Extension</strong></a><strong> </strong>which lets you define javascript code you want to run as soon as any website loads. Simply save these snippets for *.* wildcard so you have them at console anytime and anywhere. I use this extension for few more snippets like loading any javascript library on demand as and when needed. I’m a <a href="https://medium.com/@pranavjindal999/stop-using-loops-just-lodash-everything-c60417b43b6c">big fan of <em>lodash</em></a><em> </em>and load it anytime I have to heavily modify data on the fly.</p><p>Using such watchers really speeds-up my debugging. I additionally use framework specific extensions (like <a href="https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk?hl=en">this</a> for angular.js) and new dev-tools features like <a href="https://blittle.github.io/chrome-dev-tools/sources/conditional-breakpoints.html">conditional-breakpoints</a>, <a href="https://developers.google.com/web/updates/2019/01/devtools#logpoints">logpoints</a> and <a href="https://developers.google.com/web/updates/2018/08/devtools#watch">live expressions</a> to make my debugging sessions less frustrating.</p><p>Happy debugging !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c405a6a9103" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-i-debug-javascript-code-i-didnt-write-6c405a6a9103">How I debug Javascript Code I didn’t write</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop using loops, just lodash everything!]]></title>
            <link>https://medium.com/free-code-camp/stop-using-loops-just-lodash-everything-c60417b43b6c?source=rss-c6351a9383e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60417b43b6c</guid>
            <category><![CDATA[lodash]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Pranav Jindal]]></dc:creator>
            <pubDate>Tue, 15 May 2018 20:02:32 GMT</pubDate>
            <atom:updated>2019-01-25T19:07:03.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*akTl-9s_amrjYa9-YjytmQ.png" /></figure><p>What? 🤨</p><p>Loops are the most fundamental programming concepts that anyone-into-coding learns and I’m asking you to not use them?</p><p>Well, yes and no..!!</p><p><a href="https://www.imdb.com/title/tt1276104/"><em>Loopers</em></a> 😏<em> </em>like for or while will always be part of any programming language and nothing will ever replace them, but using them as your mainstream constructs to do daily things is ugly and cumbersome.</p><p>Whenever we have to work on collections, be it arrays or objects, we just use a bunch of loops and conditions to get the work done but while doing that, all the code just gets littered with few useless extra variables that you never intended to make.</p><p>Let’s take a simple example:</p><p>You have an unsorted array employees where each employee has their name and salary (as string) and you need to extract top 10 salaries.</p><p>Let’s take this up normally:</p><pre>let employees = [{name: &#39;Gilfoyle&#39;, salary: &quot;90&quot;}, {name: &#39;Dinesh&#39;, salary: &quot;72&quot;}, and so on........]</pre><pre>let salaries = []</pre><pre>for (let i = 0; i&lt; employees.length; i++){<br> salaries.push(employees[i].salary)<br>}</pre><pre>salaries = salaries.sort((a,b)=&gt; parseInt(b)- parseInt(a))<br>let top10 = salaries.slice(0,9)</pre><p>That was a very simple operation but still took some lines of code.</p><p><a href="https://lodash.com/"><strong><em>Lodash</em></strong></a><em>: Move aside everyone, I’ll make it one-liner!</em></p><pre>let employees = [{name: &#39;Gilfoyle&#39;, salary: &quot;90&quot;}, {name: &#39;Dinesh&#39;, salary: &quot;72&quot;}, and so on........]</pre><pre>let top10 = _(employees).map(&#39;salary&#39;).orderBy(_.parseInt,&#39;desc&#39;).take(10).value()</pre><p>First, please don’t tell me that there is a better way of doing this using loops. There could be, but my point here is, <em>look at those two code blocks again</em>.</p><p>To do a simple operation as above, you ended up writing 4–5 lines of code using loops. If someone reads that code, like you just did, their brain would have to parse those lines, and would require some level concentration to understand.</p><p>The second one doesn’t even looks like code but <em>just description of what you intend to do. </em>You extracted <em>(mapped)</em> salary of employees, ordered them in descending order, took 10 of the residue and done 😎!</p><blockquote>If you already know the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">ES5/ES6 array functions</a>, you could argue that why add up a whole library when language already provides them. Well, to an extent those features work but lodash is a library dedicated to reduce the mundane tasks developers keep doing and has a whole lot to provide which is taken up further.</blockquote><p><a href="https://lodash.com/">Lodash</a> is like <a href="https://en.wikipedia.org/wiki/Batman%27s_utility_belt">Batman’s utility belt</a> for a JavaScript developer that provides almost everything you need while writing code.</p><blockquote><a href="http://underscorejs.org/">Underscore</a> fans, your library is also very cool, but lodash has surpassed it and has become a super-set of underscore. In fact, lodash is the <a href="https://www.npmjs.com/browse/depended">most depended upon package on npm</a>. Comparing libraries is not the intent of this article, use the one which suits your requirements.</blockquote><p>If we break down what we usually do using loops, it would turn out that there are a limited set of operations that we do over collections to solve most problems, and they would be:</p><ol><li>Extract/transform (<em>map</em>) values from a collection</li><li>Filter values based on some criteria</li><li>Group values based on some criteria</li><li>Aggregate (<em>reduce</em>) collection to a single value</li><li>…and other general operations like sorting, removing, inserting, etc.</li></ol><p>Achieving these is very much possible using loops but not pretty and so lodash provides few functions to clean up that mess, but before getting to those functions, let&#39;s first clear up few terminologies:</p><ul><li>predicate: A function that takes a value and returns a boolean based on input.</li><li>iteratee: A function that takes one or more values as input and returns a value based on that input.</li><li>comparator: A function that takes two values as input and returns a boolean based on both inputs.</li></ul><p>You don’t have to write these functions every time and there are shorthand notations to these which makes lodash very succinct and we will take them as we go.</p><blockquote>I’d barely be scratching the surface of what lodash is capable of and covering all that is not possible in a single article. The intent is to make new developers aware that using loops and basic programming constructs everywhere and everyday is not ideal. Using libraries like lodash makes your code concise and a breeze to read making it manageable.</blockquote><p>Taking up our initial breakdown of common operations:</p><ol><li><a href="https://lodash.com/docs/4.17.10#map">map</a>: A function that takes a collection and an iteratee as input and returns an array running the iteratee on each item of collection.</li></ol><p>For example:</p><pre>_.map([4, 8], n =&gt; n*n)</pre><pre>// [16, 64]</pre><pre>let employees = [{name: &#39;Gilfoyle&#39;, salary: &quot;90&quot;}, {name: &#39;Dinesh&#39;, salary: &quot;72&quot;}]</pre><pre>_.map(employees, emp =&gt; emp.salary)</pre><pre>// [&quot;90&quot;, &quot;72&quot;]</pre><p>A <a href="https://lodash.com/docs/4.17.10#property">shorthand</a> for iteratee in second example can be as simple as a string naming the property to extract.</p><pre>_.map(employees, &#39;salary&#39;)</pre><p>2. <a href="https://lodash.com/docs/4.17.10#filter">filter</a>: A function that takes a collection and a predicate as input and returns a filtered array running the predicate on each item of collection for which predicate returned true.</p><pre>var pipers = [<br>{ piper: &#39;Richard Hendricks&#39;, genius: true, billionaire: false },<br>{ piper: &#39;Bag Head&#39;, genius: false, billionaire: false },<br>{ piper: &#39;Russ Hanneman&#39;, genius: false, billionaire: true }<br>]<br>_.filter(pipers, piper =&gt; piper.billionaire)<br>//[{ piper: &#39;Russ Hanneman&#39;, genius: false, billionaire: true }]</pre><p>Shorthand for predicate in second example can be as simple as a string naming the property or a partial object or a property-value pair.</p><pre>_.filter(pipers, &#39;billionaire&#39;)<br>//[{ piper: &#39;Russ Hanneman&#39;, genius: false, billionaire: true }]</pre><pre>_.filter(users, {genius: true, billionaire: false})<br>//[{ piper: &#39;Richard Hendricks&#39;, genius: true, billionaire: false }]</pre><pre>_.filter(users, [&#39;billionaire&#39;, false])<br>//[{ piper: &#39;Richard Hendricks&#39;, genius: true, billionaire: false },<br>{ piper: &#39;Bag Head&#39;, genius: false, billionaire: false }]</pre><p>3. <a href="https://lodash.com/docs/4.17.10#groupBy">groupBy</a> : A function that creates an object composed of keys generated from the results of running each element of collection thru iteratee.</p><pre>_.groupBy([6.1, 4.2, 6.3], Math.floor);<br>{ 4: [4.2], 6: [6.1, 6.3] }</pre><p>A <a href="https://lodash.com/docs/4.17.10#property">shorthand</a> for iteratee can again be as simple as a string naming a property.</p><pre>var pipers = [<br>{ piper: &#39;Richard Hendricks&#39;, genius: true, billionaire: false },<br>{ piper: &#39;Bag Head&#39;, genius: false, billionaire: false },<br>{ piper: &#39;Russ Hanneman&#39;, genius: false, billionaire: true }<br>]</pre><pre>_.groupBy(pipers, &#39;genius&#39;)<br>/*<br>{<br>   true: [<br>      {<br>         &quot;piper&quot;: &quot;Richard Hendricks&quot;,<br>         &quot;genius&quot;: true,<br>         &quot;billionaire&quot;: false<br>      }<br>   ],<br>   false: [<br>      {<br>         &quot;piper&quot;: &quot;Bag Head&quot;,<br>         &quot;genius&quot;: false,<br>         &quot;billionaire&quot;: false<br>      },<br>      {<br>         &quot;piper&quot;: &quot;Russ Hanneman&quot;,<br>         &quot;genius&quot;: false,<br>         &quot;billionaire&quot;: true<br>      }<br>   ]<br>}<br>*/</pre><p>4. <a href="https://lodash.com/docs/4.17.10#reduce">reduce</a>: A function that r<em>educes </em>collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous.</p><p>Reduce is better used when you don’t want to make extra variables and just want to extract a value off a collection. It is <a href="https://codeburst.io/learn-understand-javascripts-reduce-function-b2b0406efbdc">better explained here</a>.</p><p>Lodash has various other general operations like <a href="https://lodash.com/docs/4.17.10#sortBy">sorting</a>/<a href="https://lodash.com/docs/4.17.10#orderBy">ordering</a> arrays, <a href="https://lodash.com/docs/4.17.10#remove">removing</a> items from arrays, <a href="https://lodash.com/docs/4.17.10#intersection">intersecting</a> arrays, finding <a href="https://lodash.com/docs/4.17.10#difference">difference</a> between arrays and so on, which are very handy in common day to day programming and once you know them (which is just a matter of days), <em>you’ll feel, using loops is so-stone-age.</em></p><p>One of the premier features of Lodash that I used in the first example is <a href="https://lodash.com/docs/4.17.10#chain"><em>chaining</em></a><em> </em>⛓️ which lets you chain your operations without making you save intermediate results in variables and then passing on to next functions. Chaining makes your code very brief, descriptive and compact without any mess.</p><p>For example, if you look at the following code, it becomes as easy as reading a statement to guess what type the data would be and what the code actually does:</p><pre><em>let</em> statuses = _(data).map(&#39;status&#39;).uniq().sortBy().value()</pre><p>data must be a collection of objects, you extracted all status, removed duplicates leaving unique set of status, sorted them and voilà!</p><p>There are two ways of chaining in lodash which have been explained very well <a href="https://blog.mariusschulz.com/2015/05/14/implicit-function-chains-in-lodash">here</a>.</p><blockquote>Also, Lodash auto optimizes your chain of functions to make it as performant as possible using <a href="http://filimanjaro.com/blog/2014/introducing-lazy-evaluation/">lazy evaluation</a>.</blockquote><p>I can keep on defining these awesome functions and features but nothing is better than <a href="https://lodash.com/docs/4.17.10">Lodash’s documentation</a>, so hop-on and dive into the world of no-loops.</p><p>Thank you for reading, have a great day!! ✌️</p><p>👉<em>Attention beginners! Do not directly jump over to such libraries without mastering loops and basic programming constructs. Whenever you need to solve a new algorithmic problem, it’s best to fallback to loops to make an optimized solution.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60417b43b6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/stop-using-loops-just-lodash-everything-c60417b43b6c">Stop using loops, just lodash everything!</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototype in JavaScript: it’s quirky, but here’s how it works]]></title>
            <link>https://medium.com/free-code-camp/prototype-in-js-busted-5547ec68872?source=rss-c6351a9383e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5547ec68872</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Pranav Jindal]]></dc:creator>
            <pubDate>Wed, 31 May 2017 11:11:28 GMT</pubDate>
            <atom:updated>2018-02-20T04:24:19.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prjnL1V1OgyVtYrhssOUSQ.jpeg" /></figure><p>The following four lines are enough to confuse most JavaScript developers:</p><pre>Object instanceof Function<br>//true</pre><pre>Object instanceof Object<br>//true</pre><pre>Function instanceof Object<br>//true</pre><pre>Function instanceof Function<br>//true</pre><p>Prototype in JavaScript is one of the most mind-boggling concepts, but you can’t avoid it. No matter how much you ignore it, you will encounter the prototype puzzle during your JavaScript life.</p><p>So let’s face it head-on.</p><p>Starting with basics, there are following data types in JavaScript:</p><ol><li>undefined</li><li>null</li><li>number</li><li>string</li><li>boolean</li><li>object</li></ol><p>First five are primitive data types. These store a value of their type such as a boolean, and can be true or false<em>.</em></p><p>The last “object” is a reference type which we can describe as a collection of key-value pairs (but it is much more).</p><p>In JavaScript, new objects are made using <strong>Object constructor</strong> <strong>function </strong>(or object literal {}) which provides generic methods like toString() and valueOf().</p><p>Functions in JavaScript are special objects which can be “<strong>called”</strong><em>. </em>We make them and by using the <strong>Function constructor function</strong> (or function literal). The fact that these <strong>constructors</strong> are objects as well as function has always confused me, much in the same way the chicken-egg riddle confuses everyone.</p><p>Before starting with Prototypes, I want to clarify that there are two prototypes in JavaScript:</p><ol><li><strong>prototype</strong>: This is a special object which is assigned as property of any function you make in JavaScript. Let me be clear here, it is already present for any function you make, but not mandatory for internal functions provided by JavaScript (and function returned by bind). This prototype is the same object that is pointed to by the<em> </em>[[Prototype]](see below) of the a newly created object from that function (using new keyword).</li><li><strong>[[Prototype]]:</strong> This is a somehow-hidden property on every object which is accessed by the running context if some property which is being read on the object is not available. This property simply is a reference to the prototype<em> </em>of the function from which the object was made. It can be accessed in script using special <strong>getter-setter</strong> (topic for another day) called __proto__<em>.</em> There are other new ways to access this prototype, but for sake of brevity, I will be referring to <strong>[[Prototype]] </strong>using<strong> </strong><strong>__proto__.</strong></li></ol><pre>var obj = {}<br>var obj1 = new Object()</pre><p>The above two statements are equal statements when used to make a new object, but a lot happens when we execute any of these statements.</p><p>When I make a new object, it is empty. Actually it is not empty because it is an instance of the<em> </em>Object<em> </em>constructor, and it inherently gets a reference of prototype<em> </em>of Object,<em> </em>which is pointed to by the __proto__<em> </em>of the newly created object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MQi57rWt3nR_r6hmaqu_Cw.png" /></figure><p>If we look at the prototype of Object constructor function, it looks the same as the __proto__ of obj. In fact, they are two pointers referring to the same object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CVPs1e72dkaGQq8VCJFbzg.png" /></figure><pre>obj.__proto__ === Object.prototype<br>//true</pre><p>Every prototype<em> </em>of a function<em> </em>has an inherent property called constructor which is a pointer to the function itself. In the case of Object function<em>,</em> the prototype has constructor<em> </em>which points back to Object.</p><pre>Object.prototype.constructor === Object<br>//true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*amL4pobc_otUzW0OU4yuKw.png" /></figure><p>In the picture above, the left side is the expanded view of the Objectconstructor. You must be wondering what are all these other functions over it. Well, functions are <strong>objects</strong><em>, </em>so they can have properties over them as other objects can.</p><p>If you look closely, the Object<em> (on left) </em>itself has a __proto__<em> </em>which means that Object<em> </em>must have been made from some other constructor which has a prototype. As Object<em> </em>is a function object, it must have been made using Function<em> </em>constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MJUXc7X6T_3v_5M6IyDiVg.png" /></figure><p>__proto__<em> </em>of Object<em> </em>looks same as prototype of Function<em>.</em>When I check the equality of both, they turn out to be the same objects.</p><pre>Object.__proto__ === Function.prototype<br>//true</pre><p>If you look closely, you will see the Function<em> </em>itself has a __proto__<em> </em>which means that Function<em> </em>constructor function<em> </em>must have been made from some constructor function which has a prototype. As Function<em> </em>itself is a <strong>function</strong>, it must have been made using Function<em> </em>constructor, that is, itself. I know that sounds weird but when you check it, it turns out to be true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GETeMbEKqEh8UYWO5Lb2xg.png" /></figure><p>The __proto__<em> </em>of Function and prototype<em> </em>of Function<em> </em>are<em> </em>in fact two pointers referring to the same object.</p><pre>Function.prototype === Function.__proto__<br>\\true</pre><p>As mentioned earlier, the constructor of any prototype<em> </em>should point to the function that owns that prototype.<em> </em>The constructor<em> </em>of prototype<em> </em>of Function<em> </em>points back to Function itself.</p><pre>Function.prototype.constructor === Function<br>\\true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7VuOb5g6tmV8v3YXzKepOg.png" /></figure><p>Again, the <strong>prototype<em> </em></strong>of <strong>Function</strong><em> </em>has a __proto__<em> </em>.Well, that’s no surprise… prototype is an object, it can have one. But notice also that it points to the prototype<em> </em>of Object<em>.</em></p><pre>Function.prototype.__proto__ == Object.prototype<br>\\true</pre><p>So we can have a master map here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*sPvDEVuyKFOuL4LOskec2w.png" /></figure><pre><strong>instanceof Operator<br></strong>a instanceof b</pre><p>The<em> </em>instanceof<em> </em>operator looks for the object b<em> </em>pointed to by<em> </em>any of the constructor(s)<em> of </em>chained __proto__<em> </em>on a<em>. </em>Read that again! If it finds any such reference it returns true<em> </em>else false<em>.</em></p><p>Now we come back to our first four instanceof<em> </em>statements. I have written corresponding statements that make instanceof<em> </em>return true<em> </em>for the following:</p><pre>Object instanceof Function<br>Object.__proto__.constructor === Function</pre><pre>Object instanceof Object<br>Object.__proto__.__proto__.constructor === Object</pre><pre>Function instanceof Function<br>Function.__proto__.constructor === Function</pre><pre>Function instanceof Object<br>Function.__proto__.__proto__.constructor === Object</pre><p>Phew!! Even spaghetti is less tangled, but I hope things are clearer now.</p><p>Here I have something that I did not pointed out earlier that prototype of Object<em> </em>doesn’t have a __proto__<em>.</em></p><p>Actually it has a __proto__<em> </em>but that is equal to <strong>null</strong>. The chain had to end somewhere and it ends here.</p><pre>Object.prototype.__proto__<br>\\null</pre><p>Our Object<em>, </em>Function<em>, </em>Object.prototypeand<em> </em>Function.prototype<em> </em>also have properties which are functions, such as Object.assign<em>, </em>Object.prototype.hasOwnPropertyand<em> </em>Function.prototype.call<em>. </em>These are internal functions which do not have prototype and are also instances of Function and have a __proto__<em> </em>which is a pointer to Function.prototype<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NsFhlxWIycecYqqm4Whtmw.png" /></figure><pre>Object.create.__proto__ === Function.prototype<br>\\true</pre><p>You can explore other constructor functions like Arrayand<em> </em>Date, or take their objects and look for the prototype<em> </em>and<em> </em>__proto__. I’m sure you will be able to make out how everything is connected.</p><h4>Extra queries:</h4><p>There’s one more question that bugged me for a while: Why is it that prototype of Object is <strong>object</strong> and prototype of Function is <strong>function object</strong>?</p><p><a href="https://stackoverflow.com/a/32929083/1934798"><strong>Here</strong></a><strong> </strong>is a good explanation for it if you were thinking the same.</p><p>Another question that might be a mystery for you until now is: How do primitive data types get functions like toString()<em>, </em>substr() and toFixed()?<em> </em>This is well explained <a href="https://javascript.info/native-prototypes#primitives"><strong>here</strong></a><strong>.</strong></p><p>Using prototype, we can make inheritance work with our custom objects in JavaScript. But that is a topic for another day.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5547ec68872" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/prototype-in-js-busted-5547ec68872">Prototype in JavaScript: it’s quirky, but here’s how it works</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>