<?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 Charles Hughes on Medium]]></title>
        <description><![CDATA[Stories by Charles Hughes on Medium]]></description>
        <link>https://medium.com/@buddha_js?source=rss-c0495a5f6ce7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6RA38Wcfhrf_aHO6WB1OAw.jpeg</url>
            <title>Stories by Charles Hughes on Medium</title>
            <link>https://medium.com/@buddha_js?source=rss-c0495a5f6ce7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:36:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@buddha_js/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[Iterative Programming]]></title>
            <link>https://medium.com/@buddha_js/iterative-programming-d9b7d3d2adac?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b7d3d2adac</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Sat, 29 Mar 2014 00:23:55 GMT</pubDate>
            <atom:updated>2014-03-29T00:23:55.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>and Committing to Small Commits</h4><p>An approach to building software that I have grown to like is something I like to call iterative programming. In most of my most successful software projects, I ended up following this pattern in one way or another. The basic idea is that when you start out with a project, your only goal is to produce the minimum viable product possible. Just get something together and working that does the very basics of what you are thinking of. Don’t get caught up in “nice to haves” or optimization too much. Just try to get SOMETHING working. The purpose of this first build cycle is to simply get familiarized with the problem space you are working in for this product. You will get an idea of what the general structure might be for the final product, what kinds of things are likely to trip you up, and how feasible the idea actually is.</p><p>At the end of this first phase, you will probably have something that is pretty ugly and not that impressive. This is fine. We don’t have anything amazing yet, but we are better off than when we started. Now is the time to start iterating.</p><p>Iterating involves procedurally refactoring your original code and adding features to it one by one. Each iteration should involve relatively small changes that slightly improve the product without breaking it. After you have performed an iteration, commit. Doing this allows you to have a detailed history of the changes you make to your codebase. This will help you immensely when debugging down the line. Another big part of this philosophy is making sure each one of your commits are focused on a single change to the source. If you make multiple different changes for one commit, it will be more difficult to track down the commit where you changed something that you found out is broken.</p><p>Big changes are sometimes necessary. Sometimes, to accomplish a bigger change, it is possible to break the task up into small subtasks that don’t break the product. This is preferable to making huge changes all at once. This way you can be more confident that bugs aren’t being introduced into the system and that you can find bugs more easily when they do come up.</p><p>There are times when a large change needs to be made that simply can not be broken down into smaller subtasks that keep the product in working order. For these cases, you kind of just have to bite the bullet and do it. Do your due diligence to only make changes that bring you toward your goal for that specific goal though.</p><p>After many, many iterations, you should start seeing a pretty viable product that has some pretty cool features and is probably pretty solid!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b7d3d2adac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closure Scopes]]></title>
            <link>https://medium.com/@buddha_js/closure-scopes-53c8773cb505?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/53c8773cb505</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Fri, 28 Mar 2014 04:38:34 GMT</pubDate>
            <atom:updated>2014-03-28T18:14:08.739Z</atom:updated>
            <content:encoded><![CDATA[<h4>Closing isn’t over if something has been closed over</h4><p>This is part five of a five part series. For more context see the previous four posts: <a href="https://medium.com/p/7a0cf3ca68ed">Understanding Function Objects In JavaScript</a>, <a href="https://medium.com/p/3113f4e6af54">What is “this”?</a>, <a href="https://medium.com/p/8930faa4d173">Bind, call, and apply. Oh my!</a>, and <a href="https://medium.com/p/dbf2d2e7be41">Scopes in JavaScript</a></p><p>Our final subject in our whirlwind blog series is about closure scopes. If you read my previous post that explained scopes in general, you might remember that I mentioned that, most of the time, function scopes are garbage collected after a function closes out. Closure scopes are the exception to this rule. So under what conditions can this happen? Here is a small example:</p><pre>var parentFun = function(){<br>  var x = 0;<br>  var innerFun = function(){ <br>    return x++; <br>  }; <br>  return innerFun;<br>};<br>var func = parentFun();<br>func(); // returns 0<br>func(); // returns 1</pre><p>As complicated as it seems, this is the simplest example of closure scopes I could think of. So what is going on here? Well, first we have a function called parentFun that contains within it a variable definition x, a function definition innerFun, and a return statement returning the function innerFun. If we look at the definition of innerFun, it simply returns the value of the variable x that is defined in the parent function scope. The special thing here is that if we use the function returned by parent, the value of x is retained despite it being defined in a function that has returned! Here we returned a function that simply refers to a variable defined in parentFun, not the variable itself. Yet we still seem to have retained the variable originally defined in a function scope that has closed out. This is the magic of closure scopes.</p><p>The rule is that if a function definition refers to a variable defined outside of its own scope, that environment variable is “closed over” and a reference to that value in memory is kept for that function object as long as it exists in the system.</p><p>And that is about it! Closure scopes are actually pretty simple once you understand the other concepts that they are built on top of well. I think that the reason a lot of people have trouble with closure scopes is that they don’t have a precise understanding of scopes in general. It is really easy to gain a general intuition about scopes without truly understanding what they do or how they work.</p><p>Thanks for reading the series if you did! I had a lot of fun writing it, and I hope you enjoyed reading it! ☺</p><p>This is part five of a five part series (<a href="https://medium.com/p/7a0cf3ca68ed">1</a>, <a href="https://medium.com/p/3113f4e6af54">2</a>, 3, <a href="https://medium.com/p/dbf2d2e7be41">4</a>, <a href="https://medium.com/p/53c8773cb505">5</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53c8773cb505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scopes in JavaScript]]></title>
            <link>https://medium.com/@buddha_js/scopes-in-javascript-dbf2d2e7be41?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbf2d2e7be41</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Fri, 28 Mar 2014 03:53:20 GMT</pubDate>
            <atom:updated>2014-03-31T19:09:27.272Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part four of a five part series. For more context see the previous three posts: <a href="https://medium.com/p/7a0cf3ca68ed">Understanding Function Objects In JavaScript</a>, <a href="https://medium.com/p/3113f4e6af54">What is “this”?</a>, and <a href="https://medium.com/p/8930faa4d173">Bind, call, and apply. Oh my!</a></p><p>Before I blow your mind with closure scopes, I need to explain what scopes are in general in case you don’t understand them. A scope in JavaScript can be thought of as simply an object in memory that is used as a key value store that is used whenever a variable name is referenced in your program. What I’m going to do is build a scoping system that mimicks JavaScript’s scoping system in JavaScript. This will start with defining an object constructor we could call makeScope:</p><pre>var makeScope = function(){<br>  var instance = {};<br>  var storage = {};<br>  instance.define = function(varName, value){<br>    storage[varName] = value;<br>  };<br>  instance.lookup = function(varName){<br>    return storage[varName];<br>  };<br>  return instance;<br>};</pre><p>It’s okay if you don’t understand exactly what I am doing here. I’m using closure scopes and functional instantiation, which I do not expect you to know yet. Just trust that the above code works and read on.</p><p>The above code is an example of a datastructure that might be used to implement scoping in a programming language that doesn’t have scope hierarchies for some reason. I’m leaving out scope hierarchies for the moment to keep things simple. I’m now going to walk you through how this datastructure would be used in a Javascript program instead of JavaScript’s actual scoping system.</p><p>Each method in the scope object defined above has an analog usage in JavaScript programming. First there is the function define. Define takes a variable name and the value it will be assigned to and adds them to our storage object. So “var x = 1;” is equivalent to the statement “scope.define(‘x’, 1);”. The second function is lookup. Lookup takes a variable name and attempts to find the value corresponding to that name in our storage object. So “return x;” is equivalent to “return scope.lookup(‘x’);”. Now lets write some regular JavaScript code and then show what it would look like if we used only our new custom scoping system:</p><pre>var n = 11;<br>var test = function(){<br>  var x = n;<br>  if( x % 2 ){<br>    return x;<br>  }<br>};<br>test();</pre><p>is equivalent to:</p><pre>var globalScope = makeScope();<br>globalScope.define(‘n’, 11);<br>globalScope.define(‘test’, function(){<br>  var localScope = makeScope();<br>  localScope.define(‘x’, localScope.lookup(‘n’));<br>  if( localScope.lookup(‘x’) % 2 ){<br>    return localScope.lookup(‘x’);<br>  }<br>};<br>globalScope.lookup(‘test’)();</pre><p>The second code block is what your every day code might look like if JavaScript didn’t implement scopes as part of their language standard. I’m basically explicitly doing what is implicitly done in the first code block. So you will notice that I have added two entirely new lines to the code: “var globalScope = makeScope();” and “var localScope = makeScope();”. These two lines need to be added so that we have a scope object to use at each scope level that would be created by JavaScript implicitly otherwise. The other substitutions were explained previously.</p><p>So the problem with this scoping system so far is that there is no scope hierarchy mechanism. This means that we could not reach anything in the globalScope from the localScope I defined in the test function. So that means that when we try to lookup ‘n’ on the localScope object, we will get undefined rather than 10. This is pretty sad. Lets add this functionality:</p><pre>var makeScope = function(parent){<br>  var instance = {};<br>  var storage = {};<br>  instance.define = function(varName, value){<br>    storage[varName] = value;<br>  };<br>  instance.lookup = function(varName){<br>    if(!storage[varName] &amp;&amp; parent){<br>      return parent.lookup(varName);<br>    }else{<br>      return storage[varName];<br>    }<br>  };<br>  return instance;<br>};</pre><p>What I have done above is added a parent scope mechanism to our scope datastructure. This will allow our localScope object to reference variables defined in the globalScope object. Check it out:</p><pre>var globalScope = makeScope();<br>globalScope.define(‘n’, 11);<br>globalScope.define(‘test’, function(){<br>  var localScope = makeScope(globalScope);<br>  localScope.define(‘x’, localScope.lookup(‘n’));<br>  if( localScope.lookup(‘x’) % 2 ){<br>    return localScope.lookup(‘x’);<br>  }<br>});<br>globalScope.lookup(‘test’)();</pre><p>So when we execute the line “localScope.define(‘x’, localScope.lookup(‘n’));” in the function “test”, the lookup function will see that there is no value ‘n’ in localScope. After discovering that, the lookup function executes the lookup function on its parent scope (in this case globalScope). If globalScope didn’t have any ‘n’ key value pair, then it would call lookup on its parent as well if it had one (I guess globalScope is a little like Batman now that I think about it).</p><p>Now that we have added scope hierarchies to our system, the above code should work! If you compare the above code to the original little blurb we have near the top of this post, you can plainly see why these kinds of things are simply implied. But I think that it helps a lot to write it out explicitly so you can know almost exactly what is going on under the hood.</p><p>Now that you understand (hopefully) how scope lookups work, there is one more piece of the puzzle to consider: garbage collection. When you reach a return statement in a function or simply the closing bracket of a function, the scope object that was created for that object invocation is no longer needed. So that scope object will likely have nothing that references it after the function closes out and it will be collected by JavaScript’s garbage collector. The interesting fact is that this isn’t always the case in JavaScript. There are conditions under which a function’s scope can still be referenced by other parts of the system long after the original function that generated it has closed out. You will learn all about this wizardry in the next post: “Closure Scopes: Closing is never over if something has been closed over”</p><p>This is part 4 of a 5 part series (<a href="https://medium.com/p/7a0cf3ca68ed">1</a>, <a href="https://medium.com/p/3113f4e6af54">2</a>, <a href="https://medium.com/p/8930faa4d173">3</a>, <a href="https://medium.com/p/dbf2d2e7be41">4</a>, <a href="https://medium.com/p/53c8773cb505">5</a>). The next post will be <a href="https://medium.com/p/53c8773cb505">Closure scopes</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbf2d2e7be41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bind, call, and apply. Oh my!]]></title>
            <link>https://medium.com/@buddha_js/bind-call-and-apply-oh-my-8930faa4d173?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8930faa4d173</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Mon, 17 Mar 2014 02:15:00 GMT</pubDate>
            <atom:updated>2014-03-28T04:42:32.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>or “why isn’t my setTimeout working?”</h4><p>This is part three of a five part series. For more context see the previous two posts: <a href="https://medium.com/p/7a0cf3ca68ed">Understanding Function Objects In JavaScript</a>, and <a href="https://medium.com/p/3113f4e6af54">What is “this”?</a></p><p>So now that we have explained a little about what the “this” keyword is all about and what problems we can run into when “this” and function objects are allowed in the same language, lets explore some ways that we can pass function objects around while still maintaining their original “this” reference.</p><p>In Javascript, if we have a function that refers to the keyword “this”, we need to make sure that “this” will be what we expect it to be when we invoke the function. There are three properties on every function object in Javascript that exist to help mitigate this problem. These properties are the functions apply, call, and bind.</p><p>First I will attempt to explain the function apply and what it does. Before I get into any details, I think it is best to start out with some example code. I will re-use some code I used in the previous post and build on that. So here is the code from “What IS “this”?”:</p><pre>var obj = {<br> x: 1,<br> fun: function(){ alert(this.x); }<br>};<br>var new_fun = obj.fun;<br>new_fun(); // runtime error!</pre><p>So we have an object obj with the properties x, and fun. x is assigned to the value 1. fun is assigned to a function object that uses the this keyword to refer to its “sibling property” x. We then define a variable called “new_fun”. This variable is assigned to the same function object that obj.fun refers to. So if we try to invoke new_fun as it is, we will likely get a runtime error because the variable this will not be set to obj anymore. We can fix this problem by using either apply, call, or bind. Here is an example of using apply to make executing new_fun without runtime errors possible:</p><pre>new_fun.apply(obj);</pre><p>Function.prototype.apply is probably the most commonly used function of the three. Its function signature is as follows: apply(thisArg, [argsArray]). To re-iterate, apply is a function that is assigned as a property of every function object in javascript. This function, when invoked, will assign the keyword “this” to whatever is passed in as the first parameter. In our example above, we passed in obj as the first parameter. This assigns “this” to obj <em>for this invocation </em>of new_fun. An interesting thing we can do with apply is assign this to any arbitrary object we want. As long as the object we use has the properties that the function expects, it will work! Here’s an example:</p><pre>var obj2 = { x:2 };<br>new_fun.apply(obj2);</pre><p>We have just modified entirely what the “this” keyword refers to when new_fun is executing! After executing the above, we will be alerted 2 instead of 1. How exciting!</p><p>You may have noticed that I neglected to utilize or explain the second parameter given in apply’s function signature. So what is [argsArray] all about? It is a way for us to pass in any needed parameters to the function we are invoking with apply. Lets set up a little example:</p><pre>var plus = function(b){ return this+b; };<br>plus.apply(1, [2]); // returns 3!</pre><p>Here I defined a function plus that adds “this” and the parameter b together and returns the result. I then invoked plus with the apply function while setting thisArg to the value 1 and argsArray to the one element array [2]. This brings up two important points:</p><ol><li>With apply (and call and bind), we can assign “this” to be whatever we want! It can be a primitive value, an object, or even a function! It’s just another variable in the invoked function’s environment!</li><li>The second argument given to apply MUST be an array. That’s just how it works.</li></ol><p>The second point needs some further elaboration. Function.prototype.apply takes an array as its second input and applies each element of that array as a parameter of the function being invoked(this is also known as a splat). This is mostly useful for when you want to call apply and simply pass the arguments object along to the next function. To clarify, here is another example of using apply’s splatting:</p><pre>var sum = function(a, b, c){<br> return a + b + c;<br>}<br>sum.apply(null, [1,2,3]); // returns 6</pre><p>Note how I simply supplied null for the first argument this time. That is because the function sum as defined does not use the keyword “this”. I really didn’t need to use apply here, I just wanted to exemplify splatting.</p><p>Now that we understand how apply works, call and bind will come pretty easy. Call is just like apply, but it does not perform the splatting that apply does. Call can take any number of arguments and will supply them to the function you are calling it for. Here is a quick example using the sum function above:</p><pre>sum.call(null, 1, 2, 3);</pre><p>Call is usually used when we aren’t simply passing along the arguments object on the function we are invoking.</p><p>Finally, lets take a quick gander at what makes bind special:</p><pre>var obj = {<br> x: 1,<br> fun: function(){ alert(this.x); }<br>};<br>var new_fun = obj.fun;<br>var obj2 = { x:2 };<br>var bound_new_fun = new_fun.bind(obj2);<br>bound_new_fun(); //alerts “2”</pre><p>As you can see, bind takes a function object and produces a new function object that has its “this” variable bound to the given variable (in this case obj2). This allows us to later call this returned function and have it refer to obj2 as “this” when it is invoked. This can be really handy for calling an object method with a setTimeout or setInterval.</p><p>This is part three of a five part series (<a href="https://medium.com/p/7a0cf3ca68ed">1</a>, <a href="https://medium.com/p/3113f4e6af54">2</a>, <a href="https://medium.com/p/8930faa4d173">3</a>, <a href="https://medium.com/p/dbf2d2e7be41">4</a>, <a href="https://medium.com/p/53c8773cb505">5</a>). The next post will be <a href="https://medium.com/p/dbf2d2e7be41">Scopes in JavaScript</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8930faa4d173" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is “this”?]]></title>
            <link>https://medium.com/@buddha_js/what-is-this-3113f4e6af54?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3113f4e6af54</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Mon, 17 Mar 2014 02:14:22 GMT</pubDate>
            <atom:updated>2014-03-28T16:35:31.945Z</atom:updated>
            <content:encoded><![CDATA[<h4>There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton</h4><p>This is part two of a five part series. For extra context see <a href="https://medium.com/p/7a0cf3ca68ed">Understanding Function Objects in JavaScript</a>.</p><p>The keyword “this” is an aspect of Javascript programming that confuses a lot of people. I think this is largely due to the fact that “this” was a horrible name choice. I very much prefer Ruby’s label of “self” for this concept. The basics of what “this” is are fairly simple. Lets start right away with a small example:</p><pre>var obj = {<br> x: 1,<br> fun: function(){ console.log(this.x); }<br>};<br>obj.fun(); // logs &#39;1&#39; to the console</pre><p>Here I have defined a Javascript object that has two properties: x, which is assigned to the value 1, and fun which is assigned to a simple function that uses the “this” keyword. When I call the function fun that is a property of the object obj, it will log the value that is assigned to x. So “this” is the object that the variable obj refers to when I use the function fun like this: obj.fun(). My favorite rule of thumb for the keyword “this” is that <em>“this” is the thing that is to the left of the dot </em>of the function invocation (in most cases…).</p><p>“This” is a fairly simple concept in programming languages where function objects aren’t part of the language standard. This is because with function objects, what “this” is when referenced in a function can be different depending on the situation. In languages where function objects don’t exist, “this” always refers to the same(ish) thing for a given function. So if Javascript did not support the concept of function objects, “this” in the function “fun” above would always refer to the object “obj”. This is because it would not be possible to use the function fun without referring to obj. But because Javascript does support the concept of function objects, it is possible for us to use the function fun in any context we want. What do I mean by that? Well, here is an example:</p><pre>var new_fun = obj.fun;<br>new_fun(); // throws a runtime error (probably)</pre><p>In the above snippet, I have declared a new variable “new_fun” that I then assign to the function object “fun” that is a property of “obj”. Now what happens when I try to invoke new_fun in the second line? You might think that nothing special will happen and that we will just log 1 like before. But that likely isn’t what will happen. A runtime error is likely to occur when we try to invoke new_fun like this. This is because new_fun refers to “fun” alone. new_fun as it is currently defined does not have any reference to the definition of the object obj. It simply has the function object “fun” that is also assigned as a property of obj. It is very similar to “var number = obj.x;”. “number” is a variable that now holds a reference to the value 1 and only the value 1. It has no information about the object from which the value 1 originally came.</p><p>So what is the deal? Why would we ever want to do this? I have one word for you, my friend: callbacks. In javascript programming, and especially in asynchronous programming (YAY NodeJS!), we often want to perform some operation after the results of another operation are available. In the case that we want to call a function on a given object (like obj.fun()), we will want to be able to have the this keyword in that function still refer to obj once it is called. Now with this little motivating factor, we are going to dive into the wonderful world of call, apply, and bind.</p><p>This is part two of a five part series (<a href="https://medium.com/p/7a0cf3ca68ed">1</a>, <a href="https://medium.com/p/3113f4e6af54">2</a>, <a href="https://medium.com/p/8930faa4d173">3</a>, <a href="https://medium.com/p/dbf2d2e7be41">4</a>, <a href="https://medium.com/p/53c8773cb505">5</a>). The next post is <a href="https://medium.com/p/8930faa4d173">Bind, call, and apply. Oh my!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3113f4e6af54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Function Objects in JavaScript]]></title>
            <link>https://medium.com/@buddha_js/understanding-function-objects-in-javascript-7a0cf3ca68ed?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a0cf3ca68ed</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Mon, 17 Mar 2014 02:13:30 GMT</pubDate>
            <atom:updated>2014-04-01T03:55:13.596Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the essential concepts in JavaScript programming is the function object. Function objects are pretty complicated, multi-facetted beasts. To fully grasp function objects in JavaScript, we need to have a solid grasp of a couple different things: the keyword “this”, scopes or environment variables, and closures. All three of these things are concepts that are fairly abstract without many analogous things in our daily lives to compare them to. I feel it is for this reason that they are often misunderstood. I hope to help clear these concepts up for some people with a few blog posts.</p><p>So first of all, in its most basic form, what is a function object? Without any of the fancy whistles and bells that I’ll be talking about later, a function object is simply an object in memory that represents a function. This function can be executed at will by putting some parentheses after its variable name.</p><pre>var function_object = function(){<br> alert(“I’m a function object! Look at me!”);<br>};<br>function_object();</pre><p>You might be thinking “Well, that looks just like a function to me. What makes it a function object?” The bare bones example above only illustrates the function part of function objects in Javascript and not the object part. So what makes a function object a function object? One example of the object property of Javascript functions is that you can pass a function as a parameter to other functions:</p><pre>var another_function_object = function(callback){<br> callback.call();<br>};<br>another_function_object(function_object);</pre><p>It might not seem like much right now, but this ability is very powerful and has deep implications for the power you can wield when writing Javascript code.</p><p>So not only can you pass a function as a parameter to another function, but you can return a function from within another function, set a function as a property of an object, store a function in an array… You can basically do anything with a function that you can do with any other object in Javascript. You can even assign additional properties to a function:</p><pre>var fun = function(){<br> return 1;<br>};<br>fun.newProp = “I’m a property!”;<br>fun.newProp; // returns &quot;I&#39;m a property!&quot;</pre><p>I’m not sure why you would be tempted to do that, but you can!</p><p>So now that we have the basics down, lets explore the other facets of function objects in Javascript that make them so fun and interesting. First, we will start off with an introduction to the keyword “this”.</p><p>This is part one of a five part series (<a href="https://medium.com/p/7a0cf3ca68ed">1</a>, <a href="https://medium.com/p/3113f4e6af54">2</a>, <a href="https://medium.com/p/3113f4e6af54">3</a>, <a href="https://medium.com/p/dbf2d2e7be41">4</a>, <a href="https://medium.com/p/53c8773cb505">5</a>). The next post is <a href="https://medium.com/p/3113f4e6af54">What is “this”</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a0cf3ca68ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ups and downs of trampolining]]></title>
            <link>https://medium.com/@buddha_js/the-ups-and-downs-of-trampolining-8eee8afb41df?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eee8afb41df</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Sun, 26 Jan 2014 01:00:55 GMT</pubDate>
            <atom:updated>2014-01-27T07:21:11.496Z</atom:updated>
            <content:encoded><![CDATA[<h4>With CoffeeScript</h4><p>I really enjoy programming solutions that are elegant and short. I also really like to keep the functions I write as <a href="http://en.wikipedia.org/wiki/Pure_function">pure</a> as possible. This often leads me to want to implement recursive solutions to problems. Recursion allows iteration without mutation. It also allows for beautifully succinct tree traversal. The problem with recursive functions, however, is that each recursive step takes up stack space; and stack space is limited. The time complexity of our recursive algorithm may be alright, but our space complexity is totally off kilter if it is linear or worse. Because of this, our recursive algorithms will typically cause a stack overflow given some arbitrary problem size. This is not acceptable.</p><p>Luckily, there are a couple of solutions to this problem! Some compilers for some languages support <a href="http://en.wikipedia.org/wiki/Tail_call">tail call</a> optimization. That is great for them. Unfortunately, I rarely get to program in those languages. Another method that we can utilize in any language that supports first class functions is trampolining.</p><p>Before we start talking about trampolining, I will need to explain the concept of a thunk. Thunks are very simple things. They are simply a function call that has been wrapped in an anonymous function. Thunks are used for delayed execution. Lets see an example of this:</p><p>Say we have some function that takes in some parameters and performs some operations based on that input:</p><pre>add = (a,b) -&gt; a+b</pre><p>We can thunk some given invocation of this function like so:</p><pre>add_thunk = -&gt; add(1,2)</pre><p>Now we have a thunk that will add one and two once invoked at some later time. This is how thunks can be used for delayed execution!</p><pre>#do some other stuff… <br>x = add_thunk()<br># x now holds the value 3</pre><p>This seems perfectly useless doesn’t it? However, this simple mechanism is the solution to our recursion problems. We can use thunks to easily make linearly recursive functions have constant space complexity, thus solving our stack overflow issues.</p><p>So, here is an extremely simple linearly recursive function:</p><pre>countDown = (n) -&gt; <br>  console.log(n)<br>  if n &gt; 0 countDown(n-1)<br>  else &quot;DONE!&quot;</pre><p>This function will just count down from the number it is given to zero and return the string “DONE!” once it is finished. If we give this function some value n &gt; 10000 or so, we will likely get a “maximum call stack size exceeded” error or something like that. With a tiny, simple change we can make this function not cause that error for any arbitrarily large input. We just need to make it return a thunk of its recursive call rather than invoking the recursive call itself.</p><pre>countDown = (n) -&gt;<br> console.log(n) <br> if n &gt; 0 -&gt; countDown(n-1)<br> else “DONE!”</pre><p>Now when we call countDown, it gives us a thunk that will execute the next recursive step in the process:</p><pre>&gt;thunk = countDown(10)<br> 10<br>&gt;thunk = thunk()<br> 9<br>&gt;thunk = thunk()<br> 8</pre><p>The secret sauce here is that we are now performing each recursive step while keeping a constant call stack depth. We keep calling a single function, which gets added to the call stack, that function just returns a thunk of the next function call and then is removed from the call stack! After going up and down like this n times, we will get our “DONE!” string! But we’re still not done yet. We really don’t want to have to keep calling thunk after thunk every time we want to use this function do we? This looks pretty ridiculous:</p><pre>&gt;countDown(10)()()()()()()()()()()<br> =&gt; “DONE!”</pre><p>So lets define a function that does this for us:</p><pre>trampoline = (fun, args...) -&gt;<br>  result = fun(args...)<br>  while typeof result is &#39;function&#39;<br>    result = result()<br>  result</pre><p>This function will just keep on calling thunks that our recursive function returns until it gets something other than a thunk indicating that we are done. So now we can just pass our function into trampoline and let it go!</p><pre>trampoline(countDown, 1000000)<br>#wait a while…<br> =&gt; “DONE!”</pre><p>If we tried to call our non-thunking countDown function with n = 1000000, we would most likely get a stack overflow error. Our trampolining, thunking implementation handles it just fine!</p><p>So, for this implementation of trampoline, recursive functions are only “trampolinable” when they return thunks of their next recursive step. This does turn out to be a prohibitive constraint in some cases.</p><p>The sad thing about trampolining is that it doesn’t make our lives very easy when we are writing non-linear recursive functions. It think it is totally possible to implement a non-linear recursive function that is “trampolinable.” It just seems to make things really complicated for some problems (like non-trivial tree traversal).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eee8afb41df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods: more than DRY]]></title>
            <link>https://medium.com/@buddha_js/methods-more-than-dry-f94efae5618d?source=rss-c0495a5f6ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94efae5618d</guid>
            <dc:creator><![CDATA[Charles Hughes]]></dc:creator>
            <pubDate>Wed, 15 Jan 2014 17:12:02 GMT</pubDate>
            <atom:updated>2014-01-15T18:48:05.902Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Method Names As Documentation</h4><p>Beginner programmers often think, and are often told, that the only use for a method definition is to eliminate repetition in a program’s implementation. Keeping your code DRY is important, and defining methods is a great way to do that, but that is not the only use for declaring new methods.</p><p>Another use for method declarations is documentation and readability. A good rule of thumb for declaring a method for these purposes is when you are tempted to add a comment to a chunk of code to explain what it is doing. Instead of writing a comment, you could declare a new method with a descriptive name and call it in that spot. You should do this even if you only plan on using this method once in your whole implementation. It makes your code more readable, short, declarative, and testable.</p><p>Here’s an example of two different implementations of <a href="http://en.wikipedia.org/wiki/Newton%27s_method">Newton’s method</a> for approximating the square root of a given number in JavaScript:</p><pre>function sqrt_iter(guess,x) {<br> if (abs(square(guess) — x) &lt; 0.001) <br>   return guess;<br> else <br> return sqrt_iter(guess + x/guess) / 2);<br>}<br>function sqrt(x) {<br> return sqrt_iter(1.0,x);<br>}</pre><p>This first implementation is very terse and somewhat difficult to read. If we were to take this code and perform the technique I had suggested above, this code might look something like this:</p><pre>function sqrt_iter(guess,x) {<br> if (good_enough(guess,x)) <br>   return guess;<br> else <br>   return sqrt_iter(improve(guess,x), x);<br>}<br>function improve(guess,x) {<br> return average(guess,x / guess);<br>}<br>function average(x,y) {<br> return (x + y) / 2;<br>}<br>function good_enough(guess,x) {<br> return abs(square(guess) — x) &lt; 0.001;<br>}<br>function sqrt(x) {<br> return sqrt_iter(1.0,x);<br>}</pre><p>This implementation is noticably longer. That aside, I think that it could be argued that this implementation is much more nicely separated out into the different concepts it uses. The sqrt_iter function, in particular, is much more readable in this implementation than the previous. I don’t have to do much thinking to look at that function definition and understand what it is doing.</p><p>The “better” implementation of sqrt above was adapted from the first chapter of SICP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94efae5618d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>