<?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 Erwin Carrasquilla on Medium]]></title>
        <description><![CDATA[Stories by Erwin Carrasquilla on Medium]]></description>
        <link>https://medium.com/@erwincarrasquilla?source=rss-4c9a38d5e702------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*utQU53QtyiK69Z2n.</url>
            <title>Stories by Erwin Carrasquilla on Medium</title>
            <link>https://medium.com/@erwincarrasquilla?source=rss-4c9a38d5e702------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:42:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erwincarrasquilla/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[Making a google chrome extension]]></title>
            <link>https://medium.com/@erwincarrasquilla/making-a-google-chrome-extension-b712f5795041?source=rss-4c9a38d5e702------2</link>
            <guid isPermaLink="false">https://medium.com/p/b712f5795041</guid>
            <category><![CDATA[nicolas-cage]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[kittens]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Erwin Carrasquilla]]></dc:creator>
            <pubDate>Tue, 04 Sep 2018 22:08:28 GMT</pubDate>
            <atom:updated>2018-09-04T22:08:28.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*4P7dB68J23c4Hhfa.jpg" /></figure><p>Chrome extensions are some of the most useful applications on the web. They are small and serve minimal purposes to help make web browsing, developing, and overall web life easier. There are chrome extensions that take screenshots, chrome extensions that help you organize your tabs, and other extensions that help with React, Angular, Vue JS, and other stuff that you may be able to use to make your life easier. But how do these extensions work? Well let’s find out by making a simple extension. <strong>This tutorial assumes that you have a basic understanding of JavaScript, HTML, and CSS.</strong></p><h3>Table of Contents:</h3><ul><li><a href="https://medium.com/p/b712f5795041#bb99">What we are making.</a></li><li><a href="https://medium.com/p/b712f5795041#85ac">What is an extension</a></li><li><a href="https://medium.com/p/b712f5795041#f232">Where to start?!</a></li><li><a href="https://medium.com/p/b712f5795041#93f0">Some Manifest option</a>s</li><li><a href="https://medium.com/p/b712f5795041#4350">Defining Permissions</a></li><li><a href="https://medium.com/p/b712f5795041#bb41">Tell your extension what to do</a>!</li><li><a href="https://medium.com/p/b712f5795041#0e96">Running scripts based on events</a></li></ul><p><strong>For this tutorial we are going to create:</strong></p><p>A chrome extension that replaces images that are hovered over with images of <a href="http://placekitten.com/">cats</a>/<a href="http://placecorgi.com/">dogs</a>/<a href="http://placecage.com/">Nicolas Cage</a>. The choice is yours! Some things we want to keep in mind are that we want to change the picture when our mouse hovers over the image in the web page. When we move the mouse off the image it should return the image to it’s original order.</p><h3><strong>What is an extension</strong></h3><p>Extensions are small software applications used to enhance the chrome experience. These extensions can have event based logic, add options to the menu that appears after a right click, block ads, and be used to modify or enhance the chrome experience. They serve a single purpose and can have multiple pieces to them but all these pieces benefit a common purpose. Imagine having an extension that grabs a selected word and displays the definition of the selected word immediately under it. Or maybe an extension that allows for multi-cursor selection. Maybe you have one that gathers how many words per minute you type in chrome. Another good one is an extension that connects to Facebook and displays your messages and notification where ever you are in chrome. The possibilities can be endless, the only reason is because extensions listen in on what you are doing on a web page.</p><p>Extensions are made up of many different pieces. There can be <strong>background scripts</strong> that listen to events and execute some logic based on the conditions that are met, <strong>content scripts</strong> are used to read and modify the DOM visited and executes some Javascript , an <strong>options page</strong> that determines — well you know — the options ,<strong> UI elements</strong> that can aid in creating popup interfaces , and various<strong> logic files</strong> that help with getting the core functionality implemented. Chrome extensions use JavaScript, HMTL, and CSS to create what we see and use in the browser.</p><h3>Where to start?!</h3><p>To start creating your first chrome extension masterpiece, you need a manifest.json. Hmm, I’ve heard of package.json…what the heck is the manifest.json?!</p><p>The<strong> manifest.json</strong> is similar to the well known package.json in JavaScript. It is required for each extension and defines some important information that said extension requires. Both the package.json and the manifest.json define the <strong>name</strong> of the project you are working on, the <strong>version</strong>, <strong>description</strong>, and other pieces of what makes your extension work. The <strong>manifest_version</strong> is special to a chrome extension, at least it’s the first time I have seen it so far. Currently the <a href="https://developer.chrome.com/extensions/manifest/manifest_version">docs</a> specify that the manifest version is 2.</p><pre>// manifest.json</pre><pre>{ <br> “name”: “Replace with kitty”,<br> “version”: “1.0”,<br> “description”: “Build an Extension that replaces your images with kittens”,<br>  “manifest_version”: 2<br> }</pre><p>The above code would be the minimum required to be able to add this as a chrome extension to your browser. This code does absolutely nothing and is pretty self explanatory but we can still make it an extension that is useable within our local chrome browser. All we have to do is switch our chrome extensions to developer mode and add the extension to the browser. To add this project as an extension all you have to do is go to the <a href="/service/chrome://extensions">chrome extensions page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HR1MNOFmO6VLhvWOJIBlw.png" /><figcaption>This is the chrome://extensions page</figcaption></figure><p>Then from here we have to enable developer mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ejz_D5flaWADxzUzhgPnQ.png" /><figcaption>Red arrow is pointing to switch for developer mode</figcaption></figure><p>Press on load unpacked and locate the extensions root file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYlWs6AI2gdniPiLtep2Mg.png" /><figcaption>Red arrow is pointing to LOAD UNPACKED</figcaption></figure><p>The manifest can also take other options such as background scripts, permissions, and page_action. We will be using these for our tutorial but there are many different options that you can add to the manifest. Background scripts defining the scripts that get executed when and event being listened for is heard. The background script also goes idle allowing for it to not be loaded into memory at all times. Permissions just allow us to use the chrome API’s and gain access to certain functionality inside of the extension. Page action is not what you might think, this is just the button that represents the extension to the right of the url bar. All the icons to the right here are all page_actions available for this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmIXcrv15dO3_Gnd9CNPfQ.png" /><figcaption>The icons to the right are page_actions.</figcaption></figure><p>We did not put in an icon or image to represent our extensions so google will default to it’s grey scale “G” logo which you can see all the way to the right. I personally do not want to add an icon to this tutorial app. If you would like to add an icon to your google chrome extension <a href="https://developer.chrome.com/apps/manifest/icons#icons">here</a> is how you do it, it’s pretty simple.</p><h3>Defining permissions</h3><p>I believe that figuring out what permissions you need to start off with and defining them in the manifest first is an important step. So let’s start off with giving our extension a name and defining the activeTab and declarativeContent permissions.</p><pre>// manifest.json<br>{<br>  &quot;name&quot;: &quot;Getting Started Example&quot;,<br>  &quot;version&quot;: &quot;1.0&quot;,<br>  &quot;description&quot;: &quot;Build an Extension!&quot;,<br>  &quot;manifest_version&quot;: 2,<br> // This page_action option uses the activeTab permission<br>  &quot;page_action&quot;: {<br>      &quot;default_title&quot;: &quot;My first extension&quot;<br>  },<br>  &quot;permissions&quot;: [<br>    &quot;activeTab&quot;,<br>    &quot;declarativeContent&quot; // you can add whatever you want/need<br>  ]<br>}<br></pre><p>The other approach , <em>adding permission as you need them,</em> can be used I typically do my research first to get an MVP and then tweak as necessary. For our extension we are going to need to have access to the <a href="https://developer.chrome.com/extensions/activeTab">active tab</a> permission in order to gain temporary access to the currently active tab when the function is invoked. This will also allow us to make use of methods such as <strong>tabs.executeScript</strong> or <strong>tabs.insertCss</strong>. We could also grab the tabs information such as the <strong>url</strong>, <strong>title</strong>, and <strong>favicon</strong> as long as we are on that tab. The active tab permission can be used in conjunction with the <a href="https://developer.chrome.com/extensions/declarativeContent">declarative content</a> permission. When we add the declarative content permission we then have the ability to show the <a href="https://developer.chrome.com/extensions/pageAction">page action</a> depending on the URL of the web page and the CSS selectors that it’s styling contains. For this to happen there is no need to inject a content script into the page. Using both of these permissions allow us to interact with the web page after we click our page action. (The button by the url bar). If you would like to delve deeper into the rabbit hole <a href="https://developer.chrome.com/extensions/declare_permissions">here</a> are the other permissions that you could apply to your extensions.</p><h3>Tell your extension what to do!</h3><p>This is where the background script will come in handy. The background script monitors events such as navigating to a new page, adding/removing a bookmark, switching tabs. It is loaded when it is needed and silenced when it is not needed. Our first step is to add it to the manifest.</p><pre>// manifest.json<br>{<br>  &quot;name&quot;: &quot;Getting Started Example&quot;,<br>  &quot;version&quot;: &quot;1.0&quot;,<br>  &quot;description&quot;: &quot;Build an Extension!&quot;,<br>  &quot;manifest_version&quot;: 2,<br> // This page_action option uses the activeTab permission<br>  &quot;page_action&quot;: {<br>      &quot;default_title&quot;: &quot;My first extension&quot;<br>  },<br>  &quot;permissions&quot;: [<br>    &quot;activeTab&quot;,<br>    &quot;declarativeContent&quot; // you can add whatever you want/need<br>  ], <br> “background”: {<br>   “scripts”: [<br>     // will scan file and listen for any pertinent events<br>     “scripts.js”<br>   ],<br>   “persistent”: false<br> }<br>}</pre><p>Adding it to the manifest tells the chrome extension:</p><blockquote>“Hey, listen. Let’s use this script right here to listen to what the customer wants. If they ask you to cover the images with these pictures of kittens then I want you running after them. If they pick up a family photo book I want you slapping the picture on top of anything they look at!”</blockquote><p>The extension then reads the background script and listens for the event listeners listed within. What does this script.js look like? Well inside of the background scripts we can set up all of our action listeners. For this app we are going to need to set some rules to display our page action and some functionality to listen the the user clicks on the page action.</p><pre><br>// scripts.js</pre><pre>// Remove the current rules <br>chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {<br> // Replace the current rules<br>   chrome.declarativeContent.onPageChanged.addRules([<br>   {<br>     conditions: [/*curious? read more! */], <br>     actions: [/* Go ahead, I know you want to*/]<br>   }<br>  ])<br>})</pre><p>We have the rule update functionality set up for now, as you can see we delete the current rules in bulk and then write over them on each page change because added rules are saved across restarts. Removing an individual rule is computationally expensive and can cause the data structures being created under the hood to duplicate. Wait! We are missing our rules, but exactly how do we set up our rules? I noticed that there always seemed to be two properties defined for each <a href="https://developer.chrome.com/extensions/declarativeContent">object</a> inside the rule array parameter. The first property being “conditions”, this requires something called <a href="https://developer.chrome.com/extensions/declarativeContent#type-PageStateMatcher"><em>PageStateMatcher</em></a>. This is the only supported condition based off the chrome.declarative api documentation. This condition allows us to set which web pages our extension is available in and which actions it is allowed to take based on the url, query, schemes, ports, css, and even if the page is bookmarked.</p><p>The second property that I have noticed is “actions” and this property usually has only one thing inside it. So far I have only seen “<em>new chrome.declarative.ShowPageAction()</em>” being used but there are also two other actions you can be utilized <a href="https://developer.chrome.com/extensions/declarativeContent#type-SetIcon">SetIcon</a>, and <a href="https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript">RequestContentScript</a>. This event object then displays the page action by the url bar. Let’s see what I mean in code:</p><pre><br>// scripts.js<br>// Remove the current rules <br>chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {<br>  // Replace the current rules<br>   chrome.declarativeContent.onPageChanged.addRules([<br>   {<br>     conditions: [<br>     /*<br>     Create a new event Object with PageStateMatcher that<br>     matches page urls that follolw http and https schemes<br>     */<br>     new chrome.declarativeContent.PageStateMatcher({<br>       pageUrl: {<br>         // hostEquals: <br>         schemes: [ ‘http’, ‘https’]<br>       }<br>     })<br>     ], <br>     actions: [<br>      /*<br>       displays the page action<br>       */<br>       new chrome.declarativeContent.ShowPageAction()<br>     ]<br>   }])<br>})</pre><p>The declarativeContent API is now checking each rule and if a condition is met the corresponding actions would be executed. In this case our page action will be displayed. This isn’t enough… our page doesn’t do anything! Let’s set up a on click event listener for the page action. We want it to run code that we have inside of main.js that reads the document and changes the src to each image tag to one of an image of a kitten. To do this we would have to add a new event listener on the page action.</p><pre>// code above this line</pre><pre>// listen for when someone clicks the page action<br>chrome.pageAction.onClicked.addListener( function () {<br> // query the current tab on the current window<br>  chrome.tabs.query( { active: true, currentWindow: true }, function ( tabs ) {<br>   // exceute the main.js script on this tab<br>   chrome.tabs.executeScripts(<br>     tabs[0].id, <br>     { file: ‘main.js’ }<br>   );<br>  });<br>});</pre><p>Luckily our declarativeContent API created a way for us to be able to do this. It allows for us to show our page action without the need to add it to the host permissions and without having to inject a content script that makes that functionality available. All we would have to do is add the code above to the current scripts.js code. It is it’s own separate thing so make sure to put it on a new line! Now when we click on the page action we run the code in main.js, which we still have to implement. Let’s go do that.</p><h3>Running scripts based on events</h3><p>We want the functionality inside of our main.js file to grab every image tag on our current page and make sure that the src attribute gets replaced when the move hovers into the area the image covers on the screen. We also want the extension to restore the original image when the mouse is not hovering over the image. We also want to be able to keep track of the original source so we can put it back when we move our mouse out the the images boundaries. I immediately think of event listeners when I think of the mouse, clicking, or hovering. So let’s go ahead and start this off.</p><pre><br>// main.js</pre><pre>// we have access to the current tabs document variable because<br>// of activeTab and declarativeContent permissions.</pre><pre>let allImages = document.getElementsByTagName(‘img’);</pre><pre>// we should now have an array of all the elements with the img tag. // this array will act as a queue</pre><pre>let oldImages = [];</pre><pre>// iterate through each img</pre><pre>for ( let i = 0; i) {<br>  // attach an event listener for the mouse onto each image.</pre><pre> allImages[i].addEventListener( ‘mouseover’, function () {</pre><pre> // grab the height and width of this current image </pre><pre>  let imageWidth = this.width;<br>  let imageHeight = this.height;<br> <br>  // push the current source into the oldImages queue</pre><pre>  oldImages.push(this.getAttribute(‘src’));</pre><pre>  // set the new src for the image using placekitten.com</pre><pre>  this.setAttribute(‘src’, ‘http://placekitten.com/ ‘+ imageHeight + ‘/’ + imageWidth );<br> });<br>  // add another listener for when the mouse leaves</pre><pre>  allImages[i].addEventListener(‘mouseleave’, function () {<br>  // get the old src up in queue and replace the current src <br>  this.setAttribute(‘src’, oldimages.shift());<br>  });<br>};<br></pre><p>Now if you go to your chrome browser and search on google for images of dogs then activate your chrome extension, when you hover over images of dogs they turn to cats and back to their original picture when you go to another image. I decided to pivot last minute because I found <a href="http://www.placecage.com/">this</a>. I could not resist. This should complete the tutorial on “How to make a chrome extension”. I hope I helped demystify how to get started making a chrome extension and can’t wait to possibly use something you make in the future!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxBlsrie9c7-W7EDvYtADg.png" /><figcaption>Where’s Cage?</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b712f5795041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Prototype Chain and Binding this]]></title>
            <link>https://medium.com/@erwincarrasquilla/function-prototype-chain-and-binding-this-44d3f15bfda2?source=rss-4c9a38d5e702------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d3f15bfda2</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[learning-every-day]]></category>
            <category><![CDATA[hack-reactor]]></category>
            <dc:creator><![CDATA[Erwin Carrasquilla]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 19:39:45 GMT</pubDate>
            <atom:updated>2018-04-14T05:21:46.882Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning computer programming has taught me that there are many solutions to the same problem. One of those problems being how to invoke functions and assign the this parameter while doing so. JavaScript fortunately has a Function prototype chain that includes three methods that can help us accomplish just that. The apply, call, and bind methods in the Function prototype chain can help us tell JavaScript what ‘this’ is. They do have some minor differences during run time and in their syntax.</p><p>There are two similarities between all these methods. The first being that when invoked we want to place the method after a function reference by using dot notation. The second being that the first parameter in these method invocations is always going to be what we want this to be and the rest are parameters that are going to be passed into the function we are invoking. Let us imagine that we have a function that multiplies two numbers, like so:</p><pre>var multiply = function(a,b) { <br>  return a * b;<br>};</pre><p>This function has two parameters a and b which then get multiplied and returned. Let’s use these methods to invoke multiply.</p><h3>Function.prototype.apply()</h3><p>The apply method would be invoked like this:</p><pre>var applyMethod = multiply.apply( this, [7, 3] ); </pre><pre>//21</pre><p>The apply method was placed behind the reference to multiply using dot notation. Then the keyword this ( which currently is pointing to the global object ) is placed as the first parameter in the invocation. So far so good, now with the apply method we do something a little different that what we do with the other methods. We place the parameters that are going to be used to invoke the function in an array-like object. The apply method gets invoked immediately after which then runs the function immediately as well.</p><p><strong>Note</strong>: The best way to remember the syntax for the apply method is to think “ If it starts with an <strong>a</strong>, it needs and <strong>array</strong>”.</p><h3>Function.prototype.bind()</h3><p>The bind method is invoked like this:</p><pre>var bindMethod = multiply.bind( this, 5, 3); </pre><pre>//15</pre><p>The syntax for this method is similar to apply but instead of putting the parameters that are going to be passed onto the function in an array-like object. We place them in there comma separated instead. This method does not invoke the function immediately after it is declaration. Instead it just binds this to the object and returns a function reference. In order to invoke the method the bindMethod variable must be invoked.</p><pre>console.log(bindMethod()); </pre><pre>//15</pre><p>Notice that this invocation does not need parameters. This is because when we bound this to the function multiply we already gave it those parameters. Bind also binds those parameters to this certain function declaration so that it can be recalled later.</p><h3>Function.prototype.call()</h3><p>The call method is very similar to the apply method:</p><pre>var callMethod = multiply.call(this, 3, 4); </pre><pre>//12</pre><p>Invoked the same way (after a function reference) with the first parameter being the object we want to bind this to and after that the parameters. The syntax for the call method does not need an array-like object to define what the parameters are, instead we comma separate them. This method also invokes the function with the given parameters immediately upon declaration just like apply does.</p><p>If this still confuses you that’s alright. We can see the differences better using objects as an example. Let us imagine that we have two Person object and a function called personInfo that displays the persons name, age, and hobby as a string. Just for fun lets throw in three global variables that hold name, age, and hobby.</p><pre>var personInfo = function(){<br>  console.log(`Hello! My name is ${this.name}, I am ${this.age} years old and like to ${this.hobby}.`);<br>};</pre><pre>var name = &#39;Window&#39;;<br>var age = &#39;23&#39;; //JavaScript was created in September 1995.<br>var hobby = &#39;code my life away&#39;;</pre><pre>var marco = {<br>&#39;name&#39; : &#39;Marco&#39; ,<br>&#39;age&#39; : &#39;27&#39; ,<br>&#39;hobby&#39;: &#39;go swimming&#39;<br>};</pre><pre>var polo = {<br>&#39;name&#39; : &#39;Polo&#39;,<br>&#39;age&#39; : &#39;29&#39; , <br>&#39;hobby&#39;: &#39;play hide and seek&#39;<br>};</pre><p>We use this a lot inside of our personInfo function but what is this referring to? Let’s try it out!</p><pre>personInfo();<br>&gt; Hello! My name is Window, I am 23 years old and like to code my life away.</pre><p>It seems to be that when the personInfo function is invoked without apply, call, or bind ‘this’ refers to the global scope where the three variables outside of person objects reside.</p><p>Lets try using apply:</p><pre>personInfo.apply(marco, []);<br>&gt; Hello! My name is Marco, I am 27 years old and like to go swimming.</pre><p>We referenced the function we are trying to use, we placed the object we want the keyword ‘this’ to refer to, and (for the purpose of this explanation) we added an empty array because the function we are invoking does not ask for any parameters and because we are using the apply method. <strong>This can be omitted if the array of parameters is not needed. </strong>The apply method bound this to the person object marco. This allows the function personInfo to use the keyword ‘this’ to refer to marco as an object. It changes what ‘this’ points to, only for the invocation time of the function. Once the function dies, ‘this’ no longer points to marco.</p><p>I encourage you to try out the other two methods on your own, create a new function that takes in parameters to try these three methods on . Remember that bind does not immediately invoke the function. Instead declare a variable to hold the function reference that bind will return and run that variable as a function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d3f15bfda2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion]]></title>
            <link>https://medium.com/@erwincarrasquilla/recursion-de471ed0f7b2?source=rss-4c9a38d5e702------2</link>
            <guid isPermaLink="false">https://medium.com/p/de471ed0f7b2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Erwin Carrasquilla]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 14:55:23 GMT</pubDate>
            <atom:updated>2018-04-11T14:55:59.135Z</atom:updated>
            <content:encoded><![CDATA[<p>When studying computer science the subject of recursion comes up often. What is it though? R<a href="https://en.wikipedia.org/wiki/Recursion_(computer_science)">ecursion </a>is a method in which the solution to a bigger problem depends on smaller instances of that problem. It’s not a special algorithm, data structure, or function. It’s a procedure that helps us lower our the amount we type while allowing our function to call itself in order for it to solve the problem.</p><p><em>Well what’s the difference between recursion and iteration? </em>I’m glad you asked! It comes down to elegance and readability. You can implement algorithms that require your to go through repeated steps both iterative and recursive functions. With recursion elegance is so much more present. The code is a lot more readable, what makes it difficult is the concept of ‘base case’. Let’s think about the factorial function for a better understanding of the concept of base case.</p><p>To better understand this here is the definition of a <a href="http://www.dictionary.com/browse/factorial?s=t">factorial</a>:</p><blockquote>Noun</blockquote><blockquote><strong><em>Mathematics</em></strong><em>. </em>the product of a given positive integer multiplied by all lesser-positive integers: The quantity four factorial (4!) = 4 ⋅ 3 ⋅ 2 ⋅ 1 = 24. <em>Symbol: n!,</em>where <em>n </em>is the given integer.</blockquote><p>So if you have a number n! it would equal n! = n ⋅ n-1 ⋅ n-2 ⋅ … ⋅ n-(n-1). It’s interesting that the factorial does not take 0 in as a smaller part of n! and that’s because anything multiplied by 0 is equal to 0. We don’t want that, so let’s consider this our base case. Which makes our function look like this:</p><pre>var factorial = function(n) {<br>  if(n &lt; 0){<br>    <br>    return null;<br>  }<br>if(n === 0){<br>    return 1;<br>  }<br>return n * factorial (n-1);<br>};</pre><p>As the code describes when n is less than 0, we return nothing at all since we are subtracting one each stack call so n can reach 0 we don’t want to accept negative numbers because they will cause an infinite loop. Our base case is then described in the second if function. When our variable n reaches 0 we want to return 1 because 1 * n will still be n. This is a part in our problem where we have broken it down to the smallest possible issue and then are able to easily solve it without having to use a complicated mathematical procedure. Then in our last line of code is a return statement. Which basically is saying “ Hey, Mr(s). Computer! After you checked those two rules I want you to remember the variable n. Then I want you to multiply n by the same function that called you but take 1 away from n. This creates something called a recursion call stack. Which can be best thought of as Russian nesting dolls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*d_Tgb62-ETLVOVyhYpiDjA.png" /><figcaption>Example of an Animal themed Russian nesting doll</figcaption></figure><p>Each time the function gets called with a decremented n variable it nests itself until it returns something useful. Much like opening the nesting dolls (let’s imagine the nesting dolls have the value of n written on them. When it reaches 0 it returns 1 and since we have been subtracting 1 when we begin to close the nesting dolls back up we can then start getting our product. So we get our scrap paper out and start writing 1 * 2 * 3 * 4 * … * n and we solve our factorial. The more dolls we close the closer we get to the original function that has called us and we can finally give the public the answer they were looking for.</p><p>Recursion does take some practice and patience. With a little time it will seem easier to think about the base case and thinking about how to implement your functions recursively will become a friend and not a foe.</p><p><a href="http://www.cs.cornell.edu/info/courses/spring-98/cs211/lecturenotes/07-recursion.pdf">http://www.cs.cornell.edu/info/courses/spring-98/cs211/lecturenotes/07-recursion.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de471ed0f7b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>