<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Kevin Ennis]]></title><description><![CDATA[<p>Software engineer, documentary aficionado, golden retriever enthusiast.</p>

<a href="/about">About me</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/projects">Projects</a>]]></description><link>http://kevvv.in/</link><generator>Ghost 0.6</generator><lastBuildDate>Fri, 12 Dec 2025 15:57:52 GMT</lastBuildDate><atom:link href="http://kevvv.in/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Getting Started With A New Build Tool]]></title><description><![CDATA[<p><br><br>  </p>

<video preload="auto" autoplay="autoplay" muted="muted" loop="loop" webkit-playsinline="" style="width: 100%">  
  <source src="http://kevvv.in//i.imgur.com/y6OjRO3.mp4" type="video/mp4">
</video>]]></description><link>http://kevvv.in/getting-started-with-a-new-build-tool/</link><guid isPermaLink="false">426b429e-5a11-43c6-abba-a3a5e17791fc</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Tue, 15 Nov 2016 19:50:12 GMT</pubDate><content:encoded><![CDATA[<p><br><br>  </p>

<video preload="auto" autoplay="autoplay" muted="muted" loop="loop" webkit-playsinline="" style="width: 100%">  
  <source src="http://kevvv.in//i.imgur.com/y6OjRO3.mp4" type="video/mp4">
</video>]]></content:encoded></item><item><title><![CDATA[Prototypal Inheritance]]></title><description><![CDATA[<p>Last year I wrote a post called "How to impress me in an interview", and in it, I mentioned that I run across a lot of candidates (the vast majority, actually) who don't really understand how prototypes work.</p>

<p>In a way, that's kind of an amazing testament to how flexible</p>]]></description><link>http://kevvv.in/prototypal-inheritance/</link><guid isPermaLink="false">9bf35c07-482e-4708-b304-719cc7514e20</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Sat, 21 May 2016 01:23:39 GMT</pubDate><content:encoded><![CDATA[<p>Last year I wrote a post called "How to impress me in an interview", and in it, I mentioned that I run across a lot of candidates (the vast majority, actually) who don't really understand how prototypes work.</p>

<p>In a way, that's kind of an amazing testament to how flexible JavaScript is, and how user-friendly many of today's popular libraries are. I can't think of many other object-oriented languages where an engineer can be reasonably productive without being at least vaguely aware of classes.</p>

<p>But here's the thing: if you write JavaScript even semi-regularly, you really <em>should</em> understand how prototypal inheritance works. And that's why I'm writing this post.</p>

<h6 id="disclaimer">Disclaimer</h6>

<p>There will be some things in this article that I over-simplify a little bit.</p>

<p>My goal here is to help someone who's never used prototypal inheritance to become comfortable with it. In order to do that, I'll cut a few small corners here and there if I think it helps eliminate a bit of confusion.</p>

<h6 id="objectsinheritfromobjects">Objects Inherit from Objects</h6>

<p>If you've ever read <strong>anything</strong> about inheritance in JS, then you've almost certainly heard that objects inherit from other objects.</p>

<p>This is true, and <em>once you already understand it</em>, it's a good way to think about things. But my experience has been that this explanation alone isn't really sufficient.</p>

<p>So I'm going to break from tradition here and not actually try to explain how inheritance works right up front. Instead, we'll start with some simpler stuff that will hopefully provide a bit of context later on.</p>

<h6 id="functionprototypes">Function prototypes</h6>

<p>Here's a fun fact: In JavaScript, all functions are also objects, which means that they can have properties. And as it so happens, they all have a property called <code>prototype</code>, which is also an object.</p>

<pre><code>function foo() {

}

typeof foo.prototype // 'object'  
</code></pre>

<p>That's pretty simple, right? Any time you create a function, it will <em>automatically</em> have a property called <code>prototype</code>, which will be initialized to an empty object.</p>

<h6 id="constructors">Constructors</h6>

<p>In JavaScript, there's really no difference between a "regular" function and a constructor function. They're actually all the same. But as a convention, functions that are <em>meant to be used</em> as constructors are generally capitalized.</p>

<p>By the way, if you don't know what I mean when I say "constructor", that's totally okay. We'll get there.</p>

<p>So let's say that we want to make a constructor function called <code>Dog</code>, because explaining inheritance using animals is a time-honored tradition and I'm kind of a nostalgic dude.</p>

<pre><code>function Dog() {

}
</code></pre>

<p>If I want to make an instance of <code>Dog</code>, I use the <code>new</code> keyword. That's really what I mean when I talk about constructors – I'm using the function to <em>construct</em> a new object. Any time you see the <code>new</code> keyword, it means that the following function is being used as a constructor.</p>

<pre><code>var fido = new Dog();  
</code></pre>

<p>So now we have <code>fido</code>, who's a <code>Dog</code>. But he doesn't really do anything. </p>

<p>He's kind of like my dog, actually.</p>

<h6 id="methods">Methods</h6>

<p>It's time to make our <code>Dog</code> a little more dog-like. Bear with me here, because I'm going to explain this in just a minute.</p>

<pre><code>function Dog() {

}

Dog.prototype.bark = function() {  
  console.log('woof!');
};
</code></pre>

<p>You should remember from earlier that all functions automatically get initialized with a <code>prototype</code> object. In the example above, we tacked a function onto it called <code>bark</code>.</p>

<p>Now let's make ourselves a new <code>fido</code>.</p>

<pre><code>function Dog() {

}

Dog.prototype.bark = function() {  
  console.log('woof!');
};

var fido = new Dog();

fido.bark(); // 'woof!'  
</code></pre>

<p>I'm going to explain this in more detail a little later on. But the important thing to take away right now is that by placing <code>bark</code> on <code>Dog.prototype</code>, we made it available to all instances of <code>Dog</code>.</p>

<p>Don't worry yet about <em>how</em> this works. Just keep in mind that it works.</p>

<h6 id="differentialinheritance">Differential Inheritance</h6>

<p>JavaScript uses an inheritance model called "differential inheritance". What that means is that methods aren't copied from parent to child. Instead, children have an "invisible link" back to their parent object.</p>

<p>For example, <code>fido</code> doesn't actually have its own method called <code>bark()</code> (in other words, <code>fido.hasOwnProperty('bark') === false</code>).</p>

<p>What actually happens when I write <code>fido.bark()</code> is this:</p>

<ol>
<li>The JS engine looks for a property called <code>bark</code> on our <code>fido</code> object.  </li>
<li>It doesn't find one, so it looks "up the prototype chain" to <code>fido</code>'s parent, which is <code>Dog.prototype</code>.  </li>
<li>It finds <code>Dog.prototype.bark</code>, and calls it with <code>this</code> bound to <code>fido</code>.</li>
</ol>

<p>That part is really important, so I'm going to repeat it:</p>

<p>There's really no such property as <code>fido.bark</code>. It doesn't exist. Instead, <code>fido</code> has <em>access</em> to the <code>bark()</code> method on <code>Dog.prototype</code> because it's an instance of <code>Dog</code>. This is the "invisible link" I mentioned. More commonly, it's referred to as the "prototype chain".</p>

<h6 id="objectcreate">Object.create()</h6>

<p>Okay. We talked a little bit about differential inheritance and the prototype chain. Now it's time to put that into action.</p>

<p>Since ES5, JavaScript has had a cool little function called <code>Object.create()</code>.</p>

<p>Here's how it works.</p>

<pre><code>var parent = {  
  foo: function() {
    console.log('bar');
  }
};

var child = Object.create( parent );

child.hasOwnProperty('foo'); // false  
child.foo(); // 'bar'  
</code></pre>

<p>So what is it doing?</p>

<p>Essentially, it creates a new, empty object that has <code>parent</code> in its prototype chain. That means that even though <code>child</code> doesn't have its own <code>foo()</code> method, it has access to the <code>foo()</code> method from <code>parent</code>.</p>

<h6 id="tryit">Try It</h6>

<p>We've covered a lot of ground so far, and we still have a bit more to go. To make sure everything we learned so far sinks in, I'd encourage you to open up your dev tools and try a quick little example.</p>

<p>Create a constructor function called <code>Car</code>. Add a <code>drive()</code> method to its prototype that just logs to the console. Now create an instance of <code>Car</code> and call <code>drive()</code>.</p>

<p>I really mean it. You should take 30 seconds and go do it. I'll wait here. And no cheating...</p>

<p>Good, you're back. Hopefully you wrote something that looks like this.</p>

<pre><code>function Car() {

}

Car.prototype.drive = function() {  
  console.log('vroom');
};

var benz = new Car();

benz.drive(); // vroom  
</code></pre>

<p>If not, consider re-reading some of the earlier sections. It's important that you're somewhat comfortable with that stuff before you move on.</p>

<h6 id="puttingitalltogether">Putting It All Together</h6>

<p>It's time to look at a (slightly) more real-world example that takes everything in this post and puts it all together.</p>

<p>Let's start by creating a <code>Rectangle</code> constructor.</p>

<pre><code>function Rectangle( width, height ) {  
  this.width = width;
  this.height = height;
}
</code></pre>

<p>At this point, we'll take a tiny detour to talk about <code>this</code>.</p>

<p>When a function is used as a constructor, <code>this</code> refers to the <em>new object that you're creating</em>. So in our <code>Rectangle</code> constructor, we're taking <code>width</code> and <code>height</code> as arguments, and assigning those values to the <code>width</code> and <code>height</code> properties of our new <code>Rectangle</code> instance.</p>

<pre><code>var rect = new Rectangle( 3, 4 );

rect.width;  // 3  
rect.height; // 4  
</code></pre>

<p>Now it's time to give our <code>Rectangle</code> a method. Let's call it <code>area</code>.</p>

<pre><code>Rectangle.prototype.area = function() {  
  return this.width * this.height;
};
</code></pre>

<p>There's that <code>this</code> keyword again. Just like in the constructor, <code>this</code> inside of a method refers to the instance.</p>

<pre><code>var rect = new Rectangle( 3, 4 );

rect.area(); // 12  
</code></pre>

<h6 id="subclassing">Subclassing</h6>

<p>What if we want to make a new class of object that inherits from <code>Rectangle</code>?</p>

<p>Let's say we need a class called <code>Square</code>. Hopefully you remember from elementary school that a square is just a specific type of rectangle.</p>

<p>We'll start by creating its constructor.</p>

<pre><code>function Square( length ) {  
  this.width = this.height = length;
}
</code></pre>

<p>So, that's all well and good, but how do we make <code>Square</code> inherit from <code>Rectangle</code>? It's all about setting up the prototype chain.</p>

<p>If you remember from earlier, we can use <code>Object.create()</code> to create an empty object that inherits from another object. In the case of <code>Square</code>, that means all we need to do is this:</p>

<pre><code>Square.prototype = Object.create( Rectangle.prototype );  
</code></pre>

<p>All instances of <code>Square</code> will automatically have <code>Square.prototype</code> in their prototype chain, and because <code>Square.prototype</code> has <code>Rectangle.prototype</code> in <em>its</em> prototype chain, every <code>Square</code> will have access to the methods of <code>Rectangle</code>.</p>

<p>In other words, we can do this:</p>

<pre><code>var square = new Square( 4 );

square.area(); // 16  
</code></pre>

<p>We can also add new methods that are specific to <code>Square</code>. Remember, <code>Square.prototype</code> is just an empty object right now (albeit with a link back to <code>Rectangle.prototype</code>).</p>

<pre><code>Square.prototype.diagonal = function() {  
  return Math.sqrt( this.area() * 2 );
};
</code></pre>

<h6 id="timetravel">Time travel</h6>

<p>One of the really cool (and potentially dangerous) things about inheritance in JavaScript is that you can modify or extend the capabilities of a class <em>after</em> you've defined it.</p>

<p>Because JavaScript will look up the prototype when trying to access properties on an object, to you can alter your classes at runtime.</p>

<p>Here's an example (for illustrative purposes only. Don't ever do this):</p>

<pre><code>var arr = [ 1, 2, 3, 4, 5 ];

Array.prototype.shuffle = function() {  
  return this.sort(function() {
    return Math.round( Math.random() * 2 ) - 1;
  });
};

arr.shuffle(); // [ 3, 1, 4, 5, 2 ]  
</code></pre>

<p>The important thing to notice in this example is that <code>arr</code> was created <em>before</em> <code>Array.prototype.shuffle</code> existed. But because property lookups are done at runtime, our array got access to the new method anyway. It's like we went back in time and gave <code>Array</code> a (stupid) new method.</p>

<p>To get a sense of how powerful (and potentially dangerous) this is, go open the JS console on a page like Facebook, paste in the following code, and watch the log as you click around:</p>

<pre><code>Array.prototype.push = function() {  
  throw new Error('lolnope');
};
</code></pre>

<hr>

<p>If you live in the Boston area, love JavaScript, and want to work on some really exciting problems at <a href="https://starry.com">Starry</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I'm hiring.</p>]]></content:encoded></item><item><title><![CDATA[You’re Thinking About Frameworks the Wrong Way]]></title><description><![CDATA[<p>I interviewed at a company late last year that was having a lot of trouble on the front end.</p>

<p>Their apps were unmaintainable. Code quality was poor. Build processes were slow and messy. Nothing was really standardized.</p>

<p>They knew they had a problem, and were looking for a senior engineer</p>]]></description><link>http://kevvv.in/youre-thinking-about-frameworks-the-wrong-way/</link><guid isPermaLink="false">a4500251-0197-4dd6-8c48-ea5aa6e818a2</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Thu, 30 Jul 2015 12:58:08 GMT</pubDate><content:encoded><![CDATA[<p>I interviewed at a company late last year that was having a lot of trouble on the front end.</p>

<p>Their apps were unmaintainable. Code quality was poor. Build processes were slow and messy. Nothing was really standardized.</p>

<p>They knew they had a problem, and were looking for a senior engineer to come on board and help get things pointed in the right direction – but they also had a few ideas of their own on how to fix things:</p>

<blockquote>
  <p>“We’re gonna switch from [Framework X] to [Framework Y]”</p>
</blockquote>

<p>I immediately knew that I wouldn’t be able to help, because as an organization, they fundamentally misunderstood the root cause of their problem.</p>

<h4 id="blamingthetools">Blaming the Tools</h4>

<p>There’s a line of reasoning I see all the time, and it goes something like this:</p>

<p><em>“The app is bad and we built it with [Framework X], so [Framework X] is bad”.</em></p>

<p>This kind of logic seems to be pervasive among front-end developers right now, and I think it’s really, really dangerous. Rather than thinking critically about application design, we instead look to frameworks to solve all of our problems.</p>

<p>I’ve actually seen a company switch from Backbone to Ember. Then from Ember to Angular. In all likelihood, they’ve switched from Angular to React and Flux by now.</p>

<p>Don’t get me wrong, there’s nothing wrong with changing tools. Each have their strengths and weaknesses, and they need to be evaluated on a case-by-case basis against the objectives of your project. But you need to be clear on <em>why</em> you want to switch, and which pain points you’re trying to alleviate.</p>

<p>I’d submit that if your app is still a disaster after the third switch, then <em>maybe</em> the problem isn’t the framework.</p>

<h4 id="makingdecisionsishard">Making Decisions is Hard</h4>

<p>My personal take on all of this is that many developers are either unwilling or unable to make difficult choices about application design. So instead, they look for a framework to make all the choices for them.</p>

<p>But the <em>kind</em> of choices baked in to even the most opinionated frameworks aren’t the ones that will make or break your app.</p>

<p>I have yet to discover any library or framework so opinionated, so complete, so fundamentally correct in its core ideology that it can’t be used to make shitty apps.</p>

<p>In other words, they can’t save us from ourselves.</p>

<h4 id="engineersandtechnicians">Engineers and Technicians</h4>

<p>Okay, back to that interview.</p>

<p>There’s an important piece of information that I left out earlier: this was a rapidly-growing company, and they’d adopted a strategy of hiring very junior devs with [Framework X] experience <em>in droves</em>.</p>

<p>What they’d created was a team of <em>technicians</em>. Employees who knew how to operate the machinery of [Framework X] — but had no context. They lacked a fundamental understanding of the underlying concepts. And as a result, they often weren’t able to make informed decisions when confronted with a problem that their chosen framework offered no clear opinion on.</p>

<p>Anyway, my point here isn’t that junior devs are stupid, or that frameworks are bad.</p>

<p>My point is that by exaggerating the importance of frameworks, we’re ending up with an army of technicians and no engineers. By pretending that Ember or Angular can solve all of our problems, we give the false impression that simply learning the “right” framework is all you need in order to be effective. But it’s not.</p>

<h4 id="whatsthesolution">What’s the Solution?</h4>

<p>I’m not sure that I know, really.</p>

<p>But I think it starts with a much more honest discussion around what these frameworks can and <em>cannot</em> do for us.</p>

<p>More importantly, we need to place a much stronger emphasis on learning fundamental JavaScript concepts and principles of good application design. Unlike memorizing the API of some trendy new framework, that knowledge never becomes obsolete.</p>

<p>— —</p>

<p>Follow me on <a href="http://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis/">Medium</a> for more posts. I’m trying to write once a day for the next 30 days.</p>

<p>And if you’re in the Boston area and want to come work on crazy, top-secret things with me at <a href="http://projectdecibel.com/">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I’m hiring.</p>]]></content:encoded></item><item><title><![CDATA[On Unit Testing]]></title><description><![CDATA[<p>In the past few years, I’ve done kind of a 180° on unit tests.</p>

<p>There are a lot of really easy ways to rationalize <em>not</em> testing your code, and I’m probably guilty of saying each of them at one point or another.</p>

<ul>
<li>“It takes too much time”</li>
<li>“That’</li></ul>]]></description><link>http://kevvv.in/on-unit-testing/</link><guid isPermaLink="false">842e128e-ffff-4865-8812-7371b0b59e76</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Sun, 26 Jul 2015 14:46:26 GMT</pubDate><content:encoded><![CDATA[<p>In the past few years, I’ve done kind of a 180° on unit tests.</p>

<p>There are a lot of really easy ways to rationalize <em>not</em> testing your code, and I’m probably guilty of saying each of them at one point or another.</p>

<ul>
<li>“It takes too much time”</li>
<li>“That’s what QA is for”</li>
<li>“A passing test suite doesn’t guarantee that you don’t have bugs”</li>
<li>“I tested it myself before I committed to master”</li>
<li>“[some feature I’m working on] isn’t really testable”</li>
</ul>

<p>For some engineers, I think the reluctance to embrace unit testing is basically just <a href="https://en.wikipedia.org/wiki/Fear,_uncertainty_and_doubt">FUD</a>. Like so many other things, testing seems scary if you haven’t done it before.</p>

<p>But it’s also really difficult to fully understand the benefits of testing unless you’ve worked on a project that has good tests. So it’s easy to see why — without fully understanding the upside — many developers regard unit testing as an unnecessary step.</p>

<h4 id="ittakestoomuchtime">It takes too much time</h4>

<p>This argument is actually pretty rational if you don’t understand the long-term benefits of testing.</p>

<p>For a lot of the projects I work on, testing a new feature takes longer than actually implementing it. At first glance, that seems like a crazy way to invest my time.</p>

<p>But there’s an important piece of information missing here:</p>

<p><strong>Over the long-term, having good tests will save you a huge amount of time.</strong></p>

<p>The first time I ever refactored a piece of code with good test coverage, I actually felt a little bit <em>guilty</em>. It was almost too easy. Since I knew there was a safety net, I was free to try whatever I wanted. I didn’t have to remember all of the weird edge cases, because if I forgot them, the tests would fail.</p>

<p>Having good test coverage gives you a crazy amount of confidence going into a large refactor. It helps to ensure that you’re not introducing new bugs, which can ultimately save you a whole lot of time in the long run.</p>

<h4 id="thatswhatqaisfor">That’s what QA is for</h4>

<p>Nope.</p>

<p>Nope nope nope nope nope.</p>

<p>QA does not exist so that we can be lazy and inattentive to detail. They’re a final line of defense against bugs. And they work at a much, much higher level of abstraction than engineers do.</p>

<p>Imagine an app with an off-by-one error. Maybe you’re rendering a list of users, but accidentally omitting the last one.</p>

<p>For QA to catch this, they need to know what the list <em>should</em> look like, and then notice that there’s an entry missing. Essentially, they need to be looking for this exact bug.</p>

<p>Then they need to reproduce it. They need to document it and file an issue. In all likelihood, they need to show their screen to some engineer who doesn’t believe that they could <em>possibly</em> have written code that breaks the app.</p>

<p>And all of that time is wasted, because a simple unit test would have caught the bug. Not just this time, but <em>every time</em>. Instantly and automatically.</p>

<h4 id="apassingtestsuitedoesntguaranteethatyoudonthavebugs">A passing test suite doesn’t guarantee that you don’t have bugs</h4>

<p>Wearing a seatbelt doesn’t guarantee you won’t be horribly injured in a car accident. Should we abandon any safety measure that isn’t 100% effective?</p>

<h4 id="itesteditmyselfbeforeicommittedtomaster">I tested it myself before I committed to master</h4>

<p>Of all these terrible excuses, this is the one I’m probably most guilty of having believed in.</p>

<p><em>Of course it works. Why would I push code that doesn’t work?</em></p>

<p>This argument is compelling because there’s a tiny grain of truth to it.</p>

<p>If you’re attentive to detail and thoroughly test your new feature in the browser (or via HTTP or whatever the interface is), that <em>can be</em> functionally equivalent to unit testing.</p>

<p>But it’s hard to be sure that your new code didn’t break some other, unrelated part of the app. And more importantly, nobody else gets the benefit of the manual testing you did. That process happened once, and now it’s essentially lost.</p>

<p>Unit tests, on the other hand, are forever. They don’t just guard against bugs <em>right now</em>, they guard against bugs in the future.</p>

<h4 id="somefeatureimworkingonisntreallytestable">[some feature I’m working on] isn’t really testable</h4>

<p>For the past two years, every single application or library I’ve worked on has had 100% coverage.</p>

<p>If you’ve never used a code coverage tool (I like <a href="https://github.com/gotwarlost/istanbul">Istanbul</a> for JS), it’s essentially a process that instruments your code and then reports back on whether or not each line was executed while your test suite ran. If a line or expression was never run, it means you didn’t test it.</p>

<p>Anyway, in all of that time, I’ve only encountered one or two functions that couldn’t be written in a way that made them testable. Looking back, I’m not actually convinced that I couldn’t deal with those now by using dependency injection.</p>

<p>Sometimes you have to rethink the problem. Occasionally you even need to settle on an interface that’s less than ideal. But at the end of the day, it’s <em>extremely</em> unlikely that you’re working on a new feature that is literally <strong>impossible</strong> to test.</p>

<h4 id="gettingstarted">Getting Started</h4>

<p>If you’ve been convinced that testing is important but don’t know where to start, I’d recommend looking at some open-source projects. Most high-profile OS repos have excellent coverage, and they can give you an idea of how to effectively test your code.</p>

<p>If you’re worried about getting buy-in from the rest of your team, here’s my recommendation:</p>

<p><strong>Start writing tests for your own contributions. Don’t even ask permission. Just do it*.</strong></p>

<p>I’d be willing to bet that the rest of your team will start to see the benefits before long.</p>

<p>*<em>I did this at my last job, and it worked brilliantly. Within about a week, people were actually excited about it.</em></p>

<p>— -</p>

<p>Follow me on <a href="http://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis/">Medium</a> for more posts. I’m trying to write once a day for the next 30 days.</p>

<p>And if you’re in the Boston area and want to come work on crazy, top-secret, fully unit-tested things with me at <a href="http://projectdecibel.com/">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I’m hiring.</p>]]></content:encoded></item><item><title><![CDATA[Recursion in JavaScript]]></title><description><![CDATA[<p>I’m just gonna get this out of the way right up front, because people get really angry otherwise:</p>

<p>Consider this post as a series of learning exercises. These examples are designed to make you think — and, if I’m doing it right, maybe expand your understanding of functional programming</p>]]></description><link>http://kevvv.in/untitledrecursion-in-javascript/</link><guid isPermaLink="false">52cf3619-b179-46ec-bd42-0874c423a501</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Sat, 25 Jul 2015 13:55:30 GMT</pubDate><content:encoded><![CDATA[<p>I’m just gonna get this out of the way right up front, because people get really angry otherwise:</p>

<p>Consider this post as a series of learning exercises. These examples are designed to make you think — and, if I’m doing it right, maybe expand your understanding of functional programming a little bit.</p>

<h4 id="heydawgiheardyoulikerecursionsoiputaheydawgiheardyoulikerecursionsoiputaheydawg">Hey, dawg. I heard you like recursion, so I put a “Hey, dawg. I heard you like recursion, so I put a “Hey, dawg…</h4>

<p>Loosely defined, recursion is the process of taking a big problem and sub-dividing it into multiple, smaller instances of the same problem.</p>

<p>Put into practice, that generally means writing a function that calls itself. Probably the most classic example of this concept is the factorial function.</p>

<p>You may remember from math class that the factorial of a number <code>n</code> is the product of all positive integers less than or equal to <code>n</code>. In other words, the factorial of <code>5</code> is <code>5 x 4 x 3 x 2 x 1</code>. The mathematical notation for this is <code>5!</code>.</p>

<p>Something interesting you might have noticed about that pattern: <code>5!</code> is actually just <code>5 x 4!</code>. And <code>4!</code> is just <code>4 x 3!</code>. So on and so forth until you get down to 1.</p>

<p>Here’s how we’d write that in JavaScript:</p>

<script src="https://gist.github.com/kevincennis/9f6d414403e8b5bd045d.js"></script>

<p>If this seems confusing, I’d encourage you to mentally walk through the code using the example of <code>factorial( 3 )</code>.</p>

<p>Here’s a bit of help, in case you need it:</p>

<ol>
<li><code>factorial( 3 )</code> is <code>3 x factorial( 2 )</code>.  </li>
<li><code>factorial( 2 )</code> is <code>2 x factorial( 1 )</code>.  </li>
<li><code>factorial( 1 )</code> meets our <code>if</code> condition, so it’s just <code>1</code>.</li>
</ol>

<p>So what’s really happening here is that you’re winding up the call stack, getting down to <code>1</code>, and then unwinding the stack. As you unwind the call stack, you multiply each result. <code>1 x 2 x 3</code> is <code>6</code>, and that’s your return value.</p>

<h4 id="reversingastring">Reversing A String</h4>

<p>One of my co-workers recently told me about a whiteboard question that he’d been asked in an interview, and I thought it was kind of a fun problem.</p>

<blockquote>
  <p>Write a function that accepts a string a reverses it. Recursively.</p>
</blockquote>

<p>If you’re the ambitious type, I’d encourage you to take a few minutes and try to solve this one on your own. Keep in mind the core principle of recursion, which is to take a big problem and break it down into smaller instances of itself.</p>

<p>If you got stuck (or you’re the decidedly <em>unambitious</em> type), here’s my solution:</p>

<script src="https://gist.github.com/kevincennis/17a71a57af9fb6f0e796.js"></script>

<p>Again, I’ll give a quick walk-through example in case you got stuck. We’ll use <code>reverse('bar')</code> as a starting point.</p>

<ol>
<li><code>reverse('bar')</code> is <code>reverse('ar') + 'b'</code>  </li>
<li><code>reverse('ar')</code> is <code>reverse('r') + 'a'</code>  </li>
<li><code>reverse('r')</code> meets our <code>if</code> condition, so it’s just <code>'r'</code></li>
</ol>

<p>When the call stack unwinds, we end up with <code>'r' + 'a' + 'b'</code>.</p>

<h4 id="writingarecursivemapfunction">Writing a Recursive Map Function</h4>

<p>For our final example, we’re going to write a <code>map()</code> function. We want to be able to use it like this:</p>

<script src="https://gist.github.com/kevincennis/49a57520ef2bcd8ab1a6.js"></script>

<p>Again, I’d strongly encourage you to take a few minutes and try this one on your own. Here are a few hints and reminders:</p>

<ol>
<li><code>map()</code> should always return a new array.  </li>
<li>Break the problem down into smaller chunks.  </li>
<li>Remember the <code>reverse()</code> example.</li>
</ol>

<p>Oh, good. You’re back. How did it go?</p>

<p>j/k, this is a blog and I can’t hear you. lol.</p>

<p>Anyway, here’s how I did it:</p>

<script src="https://gist.github.com/kevincennis/b5e8a4bf100ec9d47318.js"></script>

<p>So let’s go through this using the example I gave earlier:</p>

<ol>
<li>Call <code>map()</code> using the array <code>[ 'a', 'b', 'c' ]</code>  </li>
<li>Create a new array that holds the result of calling <code>fn('a')</code>  </li>
<li>Return <code>[ 'A' ].concat( map([ 'b', 'c' ]) )</code>  </li>
<li>Repeat steps 1 through 3 with <code>[ 'b', 'c' ]</code>  </li>
<li>Repeat steps 1 through 3 for <code>[ 'c' ]</code>  </li>
<li>Eventually, we call <code>map()</code> with an empty array, which ends the recursion.</li>
</ol>

<p><strong>NOTE:</strong></p>

<p>You should never, ever, ever do this in a real application. You’ll blow out the stack on large arrays, and more importantly, you create a huge amount of garbage by instantiating so many new objects. Use <code>Array#map</code> in production code.</p>

<h4 id="wrapup">Wrap Up</h4>

<p>Hopefully I did a decent job in explaining this stuff. If you’re still struggling a bit to wrap your head around recursion, the best advice I can give is to start with small examples and mentally trace the call stack. Try something like <code>reverse('abc')</code> and walk through it, step-by-step. Eventually it’ll click.</p>

<p>— -</p>

<p>Follow me on <a href="https://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis">Medium</a> for more posts. I’m trying to write once a day for the next 30 days.</p>

<p>And if you’re in the Boston area and want to come work on crazy, top-secret things with me at <a href="http://projectdecibel.com">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I’m hiring.</p>]]></content:encoded></item><item><title><![CDATA[How I Built TinyMusic.js (part 2)]]></title><description><![CDATA[<p>In yesterday’s <a href="http://kevvv.in/how-i-built-tinymusic-js/">post</a>, I wrote about the Note class in <a href="https://github.com/kevincennis/TinyMusic">TinyMusic</a>, and covered some of the basic music theory behind it. Today, I’ll cover the Sequence class and discuss some Web Audio API basics like audio contexts, oscillators, and scheduling.</p>

<p>If you didn’t read part 1, you</p>]]></description><link>http://kevvv.in/how-i-built-tinymusic-js-part-2/</link><guid isPermaLink="false">127be777-b3eb-4d1b-bd7d-e2b9459f9d80</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Thu, 23 Jul 2015 11:02:02 GMT</pubDate><content:encoded><![CDATA[<p>In yesterday’s <a href="http://kevvv.in/how-i-built-tinymusic-js/">post</a>, I wrote about the Note class in <a href="https://github.com/kevincennis/TinyMusic">TinyMusic</a>, and covered some of the basic music theory behind it. Today, I’ll cover the Sequence class and discuss some Web Audio API basics like audio contexts, oscillators, and scheduling.</p>

<p>If you didn’t read part 1, you really should go back and do that, because this post references a lot of stuff from it.</p>

<h6 id="thesequenceclass">The Sequence Class</h6>

<p>In TinyMusic, <code>Note</code> instances are strung together and have their playback controlled by a <code>Sequence</code>. Each Sequence has a tempo, volume control, and some basic EQ.</p>

<p>There are a couple different ways to instantiate a Sequence:</p>

<pre><code>// create a Web Audio API context
var ac = new AudioContext();  
// beats per minute
var tempo = 110;  
var sequence = new Sequence( ac, tempo, [  
  new Note('G3 q'),
  new Note('E4 q'),
  new Note('C4 h')
]);
</code></pre>

<p>For convenience, you can also pass an array of strings, and they’ll automatically get turned into Note instances.</p>

<pre><code>// create a Web Audio API context
var ac = new AudioContext();  
// beats per minute
var tempo = 110;  
var sequence = new Sequence( ac, tempo, [  
  'G3 q',
  'E4 q',
  'C4 h'
]);
</code></pre>

<p>So now we’ve got a Sequence with an AudioContext, a tempo, and a bunch of Notes. What’s next?</p>

<h6 id="playingasequence">Playing A Sequence</h6>

<p>Playing a Sequence consists of a few steps. I’ll explain each one in a bit more detail later on, but I want to start with a higher-level overview.</p>

<p>First, I create a new oscillator.</p>

<p>Next, I loop through each <code>Note</code> in the sequence and schedule changes to the oscillator’s frequency.</p>

<p>Finally, I schedule a <code>stop()</code> on the oscillator and, when applicable, enable looping.</p>

<p>Here’s the <code>play()</code> method in its entirety:</p>

<pre><code>// run through all notes in the sequence and schedule them
Sequence.prototype.play = function( when ) {  
  when = typeof when === ‘number’ ? when : this.ac.currentTime;
  this.createOscillator(); 
  this.osc.start( when );
  this.notes.forEach(function( note, i ) { 
    when = this.scheduleNote( i, when ); 
  }.bind( this )); this.osc.stop( when );
  this.osc.onended = this.loop ? 
    this.play.bind( this, when ) : null; 
  return this;
};
</code></pre>

<p>The when parameter is a Web Audio timestamp, which is essentially a high-precision value (in seconds) that can be used for accurate scheduling.</p>

<p>Everything else will be explained below.</p>

<h6 id="creatinganoscillator">Creating an oscillator</h6>

<p>This part is pretty straight-forward.</p>

<p>There’s a bit of extra code to support custom wave types (a bit beyond the scope of this post, and probably not of much interest to most readers) — but essentially, all we really need to do is this:</p>

<pre><code>this.osc = this.ac.createOscillator();  
this.osc.type = this.waveType || ‘square’;  
</code></pre>

<p>Possible values for waveType are <code>sine</code>, <code>square</code>, <code>triangle</code>, and <code>saw</code>.</p>

<h6 id="schedulingfrequencychanges">Scheduling Frequency Changes</h6>

<p>The entire Sequence is actually played back using a single oscillator.</p>

<p>All I do is loop through each note and schedule changes to the oscillator’s frequency at the appropriate time.</p>

<p>In other words, when you call <code>Sequence#play</code>, I do all of the scheduling immediately, and the Web Audio API kind of takes over from there. All of my work is done up front.</p>

<p>Each note is passed to <code>Sequence#scheduleNote</code> with its index and a timestamp for when it should begin.</p>

<p>Here’s the <code>scheduleNote</code> method:</p>

<pre><code>// schedules this.notes[ index ] to play at the given time
// returns an AudioContext timestamp of when the note will *end*
Sequence.prototype.scheduleNote = function( index, when ) {  
  var duration = 60 / this.tempo * this.notes[ index ].duration,
    cutoff = duration * ( 1 - ( this.staccato || 0 ) );

  this.setFrequency( this.notes[ index ].frequency, when );

  if ( this.smoothing &amp;&amp; this.notes[ index ].frequency ) {
    this.slide( index, when, cutoff );
  }

  this.setFrequency( 0, when + cutoff );
  return when + duration;
};
</code></pre>

<p>I think this might be hard to explain by going line-by-line, so I’m going to give sort of a conceptual overview instead.</p>

<p>When we loop through all of the Notes in the <code>play()</code> method, we have a starting time value called <code>when</code>.</p>

<p>Starting with the first note, we call <code>scheduleNote()</code>, passing <code>when</code> as well as the note’s index within the sequence (for the first Note, this would be <code>0</code>).</p>

<p>From there, <code>scheduleNote</code> tells the oscillator “change to <code>x</code> frequency at <code>y</code> time”, and then it returns a new value for <code>when</code> (the previous value plus the duration of the latest Note).</p>

<p>Then <code>play()</code> moves on to the next note, and calls <code>scheduleNote()</code> using the new <code>when</code> value. Rinse and repeat for each additional Note in the sequence.</p>

<p>The actual oscillator scheduling happens in a method called <code>setFrequency()</code>, which looks like this:</p>

<pre><code>// set frequency at time
Sequence.prototype.setFrequency = function( freq, when ) {  
  this.osc.frequency.setValueAtTime( freq, when );
  return this;
};
</code></pre>

<p>Pretty simple, right? We just use the oscillator’s <code>setValueAtTime</code> method, which does exactly what it looks like.</p>

<h6 id="staccatoandsmoothing">Staccato and Smoothing</h6>

<p>TinyMusic supports two settings called <code>staccato</code> and <code>smoothing</code>.</p>

<p>Staccato refers to “choppiness”, or how long/short each note will be compared to its intended duration. Lots of staccato means the note is harshly truncated, and no staccato means it will play in its entirety.</p>

<p>Smoothing is for portamento, which is sliding from one note to the next. Higher smoothing values result in a slower slide, and no smoothing means that notes don’t slide at all.</p>

<p>These settings aren’t really integral to the basic functioning of TinyMusic, and I think they’re pretty easy to understand from looking at the source, so I’m going to skip over them in this post.</p>

<p>If you have questions about either, just leave a comment and I’ll answer to the best of my ability.</p>

<h6 id="eqandvolume">EQ and Volume</h6>

<p>EQ and volume nodes are created as soon as a Sequence is initialized with a method called <code>createFXNodes()</code>.</p>

<p>There are three nodes for EQ: bass, mid, and treble. Each is a Web Audio <code>BiQuadFilterNode</code>. This allows for some basic 3-band equalization.</p>

<p>Setting EQ values looks like this:</p>

<pre><code>var sequence = new Sequence( ac, tempo, noteArray );  
// 80 Hz
sequence.bass.frequency.value = 80;  
// +4dB
sequence.bass.gain.value = 4;  
</code></pre>

<h6 id="stoppingplayback">Stopping Playback</h6>

<p>Stopping playback is pretty simple, but there are a few important things that need to happen:</p>

<pre><code>if ( this.osc ) {  
    this.osc.onended = null;
    this.osc.stop( 0 );
    this.osc.frequency.cancelScheduledValues( 0 );
    this.osc = null;
  }
  return this;
};
</code></pre>

<p>First, we just do a quick safety check to make sure we actually have an active oscillator.</p>

<p>Next, we <code>null</code> out the oscillator’s <code>onended</code> callback, which effectively cancels looping.</p>

<p>Then, we actually stop the oscillator and cancel any frequency automation that may have been scheduled.</p>

<p>Finally, we <code>null</code> out the oscillator.</p>

<h6 id="wrappingup">Wrapping Up</h6>

<p>There are a few things in TinyMusic that I decided not to cover here.</p>

<p>Some of them are “advanced” features that likely wouldn’t be of interest to most readers, and others are trivial little helper functions that you can pick up by reading the source.</p>

<p>Nevertheless, I hope you learned a little bit about working with music in code — and maybe got a small taste for what it’s like to build apps with the Web Audio API.</p>

<p>Like I said earlier, please don’t hesitate to ask questions in the comments. If I left something out, it was likely an oversight.</p>

<p>— -</p>

<p>Follow me on <a href="http://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis/">Medium</a> for more posts. I’m trying to write once a day for the next 30 days.</p>

<p>And if you’re in the Boston area and want to come work on crazy, top-secret things with me at <a href="http://projectdecibel.com/">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I’m hiring.</p>]]></content:encoded></item><item><title><![CDATA[How I Built TinyMusic.js (part 1)]]></title><description><![CDATA[<p>About a year ago, a few co-workers and I decided that we'd all participate in <a href="http://js13kgames.com/">js13k</a>. If you're not familiar, js13k is a game competition where each entry has to be smaller than 13 KB.</p>

<p>Being a musician, it felt important that my game would have music. After looking around</p>]]></description><link>http://kevvv.in/how-i-built-tinymusic-js/</link><guid isPermaLink="false">ff0993b3-038c-4a3a-936b-ce6ec6294918</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Wed, 22 Jul 2015 12:29:57 GMT</pubDate><content:encoded><![CDATA[<p>About a year ago, a few co-workers and I decided that we'd all participate in <a href="http://js13kgames.com/">js13k</a>. If you're not familiar, js13k is a game competition where each entry has to be smaller than 13 KB.</p>

<p>Being a musician, it felt important that my game would have music. After looking around a bit, I wasn't able to find any libraries that really did what I wanted without totally blowing the 13 KB budget. So I decided to make my own.</p>

<p>This post is the first of two parts. In it, I'll explain the <code>Note</code> class in TinyMusic. We'll dig in to a little bit of light music theory and math.</p>

<p>In part two, I'll cover the <code>Sequence</code> class, and talk about the Web Audio API.</p>

<h6 id="tinymusic">TinyMusic</h6>

<p>Before I start digging in, here's a link to the final product: <a href="https://github.com/kevincennis/TinyMusic">TinyMusic</a>. You can also check out a small demo <a href="http://jsbin.com/pavelunima/1/edit?js,output">here</a>.</p>

<p>Keep in mind that this is a fairly bare-bones library. It was really purpose-built for something like js13k, so the idea was to deliver the minimum useful feature set for basic music synthesis.</p>

<h6 id="notes">Notes</h6>

<p>The first thing I started work on was a <code>Note</code> class.</p>

<pre><code>var note = new Note('A4 q');  
</code></pre>

<p>This was the API that I wanted. Basically, it accepts a string containing a note name and a time value (q = quarter, h = half, etc.), separated by a space.</p>

<p>In order to translate the note name into a frequency, you need two things:</p>

<ol>
<li>A known frequency for a given note.  </li>
<li>A formula for moving between your known frequency and the target note.</li>
</ol>

<h6 id="choosingastartingfrequency">Choosing a starting frequency</h6>

<p>Most musicians probably know that A4 = 440Hz, so that seems like a good choice for our target frequency. But since numbered octaves actually begin at C, we really want to use middle C (C4) as our target.</p>

<p>Knowing that C4 is 9 half-steps below A4, we can get its frequency like this:</p>

<pre><code>var middleC = 440 * Math.pow( Math.pow( 2, 1 / 12 ), -9 );  
</code></pre>

<p>I won't dig too far into the math here, but hopefully you recognize the <code>12</code> (number of semitones in an octave) and the <code>-9</code> (the distance between A4 and C4).</p>

<p>We'll be using the same formula later on to derive all of our other frequencies.</p>

<h6 id="convertingnotenamestofrequencies">Converting note names to frequencies</h6>

<p>Now that we have our target frequency for middle C, we need a way to translate other note names into frequencies.</p>

<p>The first thing I did was create a string of every note and then use that to populate an <code>offsets</code> hash.</p>

<pre><code>var enharmonics = 'B#-C|C#-Db|D|D#-Eb|E-Fb|E#-F|F#-Gb|G|G#-Ab|A|A#-Bb|B-Cb';  
var offsets = {};

enharmonics.split('|').forEach(function( val, i ) {  
  val.split('-').forEach(function( note ) {
    offsets[ note ] = i;
  });
});
</code></pre>

<p>The groupings in that string are kind of important to understand. The basic idea is that in music theory, sometimes there are actually multiple names for the same note. So B# and C are equivalent. Fb and E are equivalent. You get the idea...</p>

<p>Anyway, what we end up with at the end of that process is an object where each key is a note name (A, F#, Db, etc.), and the value is the distance between that note and C (in half-steps).</p>

<p>From there, we just need a little bit of math.</p>

<pre><code>var num = /(\d+)/;  
// the octave number of our known frequency, middle C
var octaveOffset = 4;

Note.getFrequency = function( name ) {  
  var couple = name.split( num ),
    distance = offsets[ couple[ 0 ] ],
    octaveDiff = ( couple[ 1 ] || octaveOffset ) - octaveOffset,
    freq = middleC * Math.pow( Math.pow( 2, 1 / 12 ), distance );
  return freq * Math.pow( 2, octaveDiff );
};

// usage:
Note.getFrequency('F3'); // 174.61  
</code></pre>

<p>So we're doing a few things here. The first line just creates an array that looks like <code>[ 'F', '3' ]</code>.</p>

<p>From there, we get the note's distance from C by looking it up in the <code>offsets</code> object. In this case, it's <code>5</code>.</p>

<p><code>octaveDiff</code> ends up being <code>-1</code>, which means that our target frequency is in the octave below our known frequency.</p>

<p>Next, we calculate a frequency <em>as if our target note was in the same octave as middle C</em>. This is the same basic formula you saw earlier.</p>

<p>Finally, we shift our frequency to the correct octave.</p>

<h6 id="durations">Durations</h6>

<p>In addition to <code>frequency</code>, each <code>Note</code> also needs a duration.</p>

<p>In this case, <code>duration</code> isn't actually measured in seconds or milliseconds. It's really just going to be a ratio of the note's time value to one beat length.</p>

<p>In other words, for a quarter note, <code>duration</code> would be <code>1</code> (because it's exactly one beat long). For a half note, it would be <code>2</code>. An eighth note is <code>0.5</code>, etc.</p>

<h6 id="dottednotes">Dotted notes</h6>

<p>If you read music, you're probably familiar with "dotted" notes.</p>

<p>If not, it basically means that when a note is dotted, you add 50% to its duration. So a dotted eighth note is really like an eighth note <em>plus</em> a sixteenth note.</p>

<p>It was pretty important to support this in TinyMusic, so this is how I did it:</p>

<pre><code>var note = new Note('A4 es');  
</code></pre>

<p>Here, the <code>e</code> stands for "eighth" and the <code>s</code> for "sixteenth". When I parse that string, I simply add the two durations together.</p>

<h6 id="numericvalues">Numeric values</h6>

<p>There are so many possible values for note duration that I couldn't realistically support all of them with short-hand strings (e.g. "q" = quarter, "e" = eighth, etc).</p>

<p>So the <code>Note</code> constructor also accepts numeric values, like this.</p>

<pre><code>var note = new Note('A4 0.75');  
</code></pre>

<h6 id="puttingitalltogether">Putting it all together</h6>

<p>This is the actual function I ended up with.</p>

<pre><code>var numeric = /^[0-9.]+$/;

Note.getDuration = function( symbol ) {  
  return numeric.test( symbol ) ? parseFloat( symbol ) :
    symbol.toLowerCase().split('').reduce(function( prev, curr ) {
      return prev + ( curr === 'w' ? 4 : curr === 'h' ? 2 :
        curr === 'q' ? 1 : curr === 'e' ? 0.5 :
        curr === 's' ? 0.25 : 0 );
    }, 0 );
};
</code></pre>

<p>I know, the nested ternary thing is gross. But in my defense, I wrote this a while ago <em>and</em> I was trying to save bytes. So whatever.</p>

<p>Anyway, here's how this thing works:</p>

<ol>
<li>If we got a string that looks like a number, just call <code>parseFloat</code> and return the number.  </li>
<li>Otherwise, loop through each character in the string and try to get a time value for it – then add them up.</li>
</ol>

<p>The second step is accomplished with <code>Array#reduce</code>. This is what gives us the ability to support strings like <code>'es'</code>. We just get the value for <code>e</code> and add it to the value for <code>s</code>.</p>

<h6 id="wrappingup">Wrapping up</h6>

<p>Now that we've got our <code>Note</code> class, we need a way to group them together and play them. I accomplish this with a class called <code>Sequence</code>, which I'll be covering in part 2 tomorrow.</p>

<hr>

<p>Follow me on <a href="http://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis/">Medium</a> for more posts. I’m trying to write once a day for the next 30 days.</p>

<p>And if you’re in the Boston area and want to come work on crazy, top-secret things with me at <a href="http://projectdecibel.com">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I’m hiring.</p>]]></content:encoded></item><item><title><![CDATA[Why Your Team Should Be Using Pull Requests]]></title><description><![CDATA[<p>I have a pretty serious fear of public speaking. </p>

<p>I start yawning a lot. My heart rate becomes elevated. I'm pretty sure my face turns red. It's gotten a lot better with age – but still, it's not great.</p>

<p>Anyway.</p>

<p>About two years ago, while I was working at Aereo, I</p>]]></description><link>http://kevvv.in/pull-requests-are-pretty-much-the-greatest/</link><guid isPermaLink="false">5bb2a751-92e5-4a43-a4c9-43235013f127</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Tue, 21 Jul 2015 11:43:18 GMT</pubDate><content:encoded><![CDATA[<p>I have a pretty serious fear of public speaking. </p>

<p>I start yawning a lot. My heart rate becomes elevated. I'm pretty sure my face turns red. It's gotten a lot better with age – but still, it's not great.</p>

<p>Anyway.</p>

<p>About two years ago, while I was working at Aereo, I had the enlightened idea that we should start doing a Lunch &amp; Learn once a week. I sent out an email to see if anyone was interested, and the response was overwhelmingly positive.</p>

<p>I'm sure you can see where this is going.</p>

<p>Since I was the one who made the suggestion, it was decided that I should present first. </p>

<p>Now, this was going to be a relatively small group of my peers. Maybe 20 people or so, most of whom I had know for about 2 or 3 years. To call this "public speaking" would be a stretch, but still, I was kind of nervous about it.</p>

<h6 id="alittlebitofcontext">A little bit of context</h6>

<p>I had recently participated in AngelHack Boston with some people I "met" on Twitter, and it was my first real exposure to using pull requests on a project. The other guys on my team were all at the same company, and they used PRs for everything at work – so we adopted them on the hackathon team as well.</p>

<p>The process really struck a chord with me, and I was curious how it might work for my team at Aereo. So I decided to pretend like I had some sort of authority on the matter, and I chose pull requests as my Lunch &amp; Learn topic.</p>

<h6 id="nopenopenopenopenopenope">Nope. Nope nope nope nope nope.</h6>

<p>The day of my little presentation arrived, and I remember sneaking into the kitchen to grab a beer from the fridge about 30 minutes before we were supposed to get started to calm my nerves. It didn't really work.</p>

<p>Eventually, everyone packed into the conference room, pizza in hand. Waiting.</p>

<p>I took a deep breath, tried not to make eye contact with anyone, and got started. At the time, I has almost zero <em>actual</em> experience with pull requests. So everything I said over the next 40 minutes was, shall we say, "speculative".</p>

<h6 id="aintsobad">#aintsobad</h6>

<p>About 5 minutes into my talk, I started feeling more comfortable. People seemed genuinely interested. A couple of them laughed at my bad jokes. Questions were asked and answered. The conference room was filled with the smell of slightly above-average pizza.</p>

<p>I was gaining confidence.</p>

<blockquote>
  <p>Pull Requests are a way to start a discussion about new code</p>
</blockquote>

<p>That was my thesis. I repeated it several times, with a level of conviction that I think is unique to people who are completely and utterly full of shit.</p>

<p>BUT HERE'S THE THING.</p>

<p>It's now two years later, and I think I was actually right.</p>

<h6 id="whyiwastedyourtimewiththatdumbstory">Why I wasted your time with that dumb story</h6>

<p>I'm about to list a few of the reasons why I think your team should use pull requests. These are the exact same things that I wrote in my slide deck two years ago. When I had pretty much never used pull requests before.</p>

<p>My point is: most of these reasons are actually kind of obvious if you take a minute to think about them. They just make sense. You can imagine a scenario where your team begins using pull requests, and intuitively, you know these things are likely to happen.</p>

<p>But still, here you are. Reading this article. <em>Not</em> using pull requests.</p>

<p>So I'll leave you with the same points I made in my bullshit presentation two years ago. Except now, I know they're true.</p>

<p><strong>Discussion</strong></p>

<p>At their core, I think pull requests are just a way to start a discussion about code. Or at least that's how I'd encourage you to think about them.</p>

<p>But why is talking about code a good thing?</p>

<p>ALLOW ME TO TELL YOU...</p>

<p><strong>Learning</strong></p>

<p>Pull requests give the engineers on your team an opportunity to receive constructive feedback – which is a really, really efficient way to learn. I noticed pretty dramatic changes in the overall quality of code being submitted within about a week from when we started using PRs at Aereo. And things just kept getting better and better.</p>

<p><strong>Ownership</strong></p>

<p>At Aereo, we had a rule that any member of the team could merge a PR <em>except</em> for the person who submitted it. This meant that <strong>everyone</strong> was responsible for reviewing new code, not just leads.</p>

<p>This greatly increased the sense of collective ownership over the codebase. It set an expectation that all new code needed to meet a certain standard, and my experience was that people actually took that pretty seriously. In a way, the codebase almost became a thing to be <em>defended</em>. It was something we were all proud of, and we wanted to preserve the level of quality we'd been working toward.</p>

<p><strong>Shared Knowledge</strong></p>

<p>I think this one is really important.</p>

<p>As engineers, we have a tendency sometimes to carve out little niches for ourselves. We put our headphones on, tune everything out, and we work on "our part" of the code.</p>

<p>And a lot of the time, we end up with an app that's basically 3 or 4 different apps all mashed together. Nobody knows how the "other parts" work.</p>

<p>When you embrace pull requests, you force people to review code that they may not have otherwise been exposed to. As a result, you end up with a lot of overlapping knowledge.</p>

<h6 id="wrapup">Wrap-up</h6>

<p>If you're interested in using pull requests on your team, here are some basic "rules" to try out. Keep what you like, and drop the stuff you don't. </p>

<ol>
<li>All new code must be submitted via pull request.  </li>
<li>Every PR must contain tests and documentation (when applicable).  </li>
<li>A pull request can be merged by any member of the team except for the person who submitted it.  </li>
<li>Each pull request must include a meaningful description.  </li>
<li>Large PRs or PRs with breaking changes should be approved by <em>multiple</em> team members or a lead. We use checkboxes in the description for this.</li>
</ol>

<p>The important thing is to <strong>just try it</strong>. Call a quick meeting with the whole team, explain what you want to do, and do it.</p>

<p>I guarantee you'll be super glad that you did. </p>

<hr>

<p>Follow me on <a href="http://twitter.com/kevincennis">Twitter</a> or <a href="https://medium.com/@kevincennis">Medium</a> for more posts. I'm trying to write once a day for the next 30 days.</p>

<p>And if you're in the Boston area and want to come submit pull requests and work on crazy, top-secret things with me at <a href="http://projectdecibel.com">Project Decibel</a>, shoot me an <a href="http://kevvv.in/pull-requests-are-pretty-much-the-greatest/kennis84@gmail.com">email</a>. I'm hiring.</p>]]></content:encoded></item><item><title><![CDATA[[object Object] Things You Didn’t Know About valueOf]]></title><description><![CDATA[<p>Okay, fine. That title is horrible. But we’re all competing with BuzzFeed for readers now, and I needed something catchy, so here we are.</p>

<p>Right, then. </p>

<p>So, what is <code>Object#valueOf</code> and why should you care?</p>

<p>More or less, it's a method that JavaScript calls automatically any time it</p>]]></description><link>http://kevvv.in/object-object-things-you-didnt-know-about-valueof/</link><guid isPermaLink="false">906bec03-7d86-4e98-8c5a-3a17e41ec2fb</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Mon, 20 Jul 2015 10:59:51 GMT</pubDate><content:encoded><![CDATA[<p>Okay, fine. That title is horrible. But we’re all competing with BuzzFeed for readers now, and I needed something catchy, so here we are.</p>

<p>Right, then. </p>

<p>So, what is <code>Object#valueOf</code> and why should you care?</p>

<p>More or less, it's a method that JavaScript calls automatically any time it sees an object in a situation where a primitive value is expected.</p>

<p>Let's look at a quick example.</p>

<pre><code>var obj = {};

console.log( 7 + obj ); // "7[object Object]"  
</code></pre>

<p>Plenty has been written about the insanity of implicit type conversion in JavaScript, so I'm really not interested in going down that road. Hopefully, your takeaway from the example is that we used the addition operator with a number on one side and an object on the other, and we got back a value that doesn't really make a ton of sense.</p>

<p>You can hardly blame JavaScript here, though. It has no way to know <em>how</em> to convert our object into a number.</p>

<p>But as luck would have it, we can actually define that behavior.</p>

<pre><code>var obj = {  
  valueOf: function() {
    return 42;
  }
};

console.log( 7 + obj ); // 49  
</code></pre>

<p>See? I wasn't lying earlier. The EcmaScript specification dictates that whenever an object is encountered in a situation where a primitive is expected, that object's <code>valueOf</code> method will be called*.</p>

<p>* <em>Actually, sometimes <strong>toString()</strong> will be called instead – but I'm not gonna get into it here. You can assume that any time a <strong>Number</strong> is expected, <strong>valueOf</strong> will be called. If you're super interested in this stuff, look up the <strong>ToPrimitive</strong> abstract operation in the ES spec.</em></p>

<h6 id="whocares">Who cares?</h6>

<p>Look, I’m not gonna lie to you here (I feel like we’re becoming friends, and I have a pathological need to be trusted). Knowing about <code>valueOf</code> is not going to materially change the way you write code on a day-to-day basis. This post is really about surfacing an interesting little JS feature that a lot of people don’t know about. But that being said, there <em>are</em> some practical applications.</p>

<p>Let's write a little <code>Integer</code> class. I won't go into much detail here, since I will assume that you, esteemed reader, are already intimately familiar with the concept of integers.</p>

<p>You can actually just skip this part if you want...</p>

<pre><code>function Int( val ) {  
  if ( !( this instanceof Int ) ) {
    return new Int( val );
  }
  if ( isNaN( val ) ) {
    throw new TypeError(‘Int value must be a number’);
  }
  if ( val % 1 !== 0 ) {
    throw new TypeError(‘Int value must be an integer’);
  }
  if ( val instanceof Int ) {
    return Int( val._value );
  }
  this._value = Math.floor( val );
}

Int.prototype.add = function( n ) {  
  return Int( this._value + Int( n )._value );
};

Int.prototype.subtract = function( n ) {  
  return Int( this._value — Int( n )._value );
};

Int.prototype.multiply = function( n ) {  
  return Int( this._value * Int( n )._value );
};

Int.prototype.divide = function( n ) {  
  try {
    return Int( this._value / Int( n )._value );
  } catch ( e ) {
    throw new Error(‘Division resulted in non-integer quotient’);
  }
};
</code></pre>

<p>Okay. Now we've got an <code>Int</code> class.</p>

<p>It does some type checking. It makes sure you don't pass it a float. And it has some basic arithmetic methods.</p>

<p>Here are a couple quick examples, just to give you a better idea of what this thing looks like:</p>

<pre><code>Int( 6 ).multiply( 2 );        // { _value: 12 }  
Int( 4 ).divide( 2 ).add( 3 ); // { _value: 5 }  
</code></pre>

<p>Simple enough. But what if I need to do something like this?</p>

<pre><code>var a = Int( 6 );  
var b = Int( 11 );

Math.min( a, b ); // NaN  
</code></pre>

<p>It basically blows up. I mean, it doesn't throw an exception, but it gives me <code>NaN</code>, which is <em>almost</em> as useless.</p>

<p>I trust at this point that you see where we're headed.</p>

<pre><code>Int.prototype.valueOf = function() {  
  return this._value;
};
</code></pre>

<p>Easy as that. Now, we'll try that same example – but this time, our <code>Int</code> class has a <code>valueOf</code> method on its prototype.</p>

<pre><code>var a = Int( 6 );  
var b = Int( 11 );

Math.min( a, b ); // 6  
</code></pre>

<p>Not bad, right? We can also use instances of <code>Int</code> in other places where a primitive value is expected:</p>

<pre><code>Math.pow( Int( 9 ), 0.5 ); // 3  
</code></pre>

<p><em>The More You Know™</em></p>

<hr>

<p>If you liked this post, follow me on <a href="https://medium.com/@kevincennis">Medium</a> or <a href="http://twitter.com/kevincennis">Twitter</a> for more. I'm challenging myself to write every day for the next month. </p>

<p>And if you live in the Boston area and want to work on crazy, top-secret things with me at <a href="http://projectdecibel.com">Project Decibel</a>, shoot me an <a href="mailto:kennis84@gmail.com">email</a>. I'm hiring.</p>]]></content:encoded></item><item><title><![CDATA[Currying in JavaScript]]></title><description><![CDATA[<p>I've been thinking a lot lately about functional programming, and I thought it might be kind of fun to walk through the process of writing a <code>curry</code> function.</p>

<p>For the uninitiated, currying refers to the process of taking a function with <code>n</code> arguments and transforming it into <code>n</code> functions that</p>]]></description><link>http://kevvv.in/currying-in-javascript/</link><guid isPermaLink="false">feb223f7-5a3b-48ca-add4-bd08be180876</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Sun, 19 Jul 2015 12:39:12 GMT</pubDate><content:encoded><![CDATA[<p>I've been thinking a lot lately about functional programming, and I thought it might be kind of fun to walk through the process of writing a <code>curry</code> function.</p>

<p>For the uninitiated, currying refers to the process of taking a function with <code>n</code> arguments and transforming it into <code>n</code> functions that each take a single argument. It essentially creates a chain of partially applied functions that eventually resolves with a value.</p>

<p>Here's a basic example of how you'd use it:</p>

<pre><code>function volume( l, w, h ) {  
  return l * w * h;
}

var curried = curry( volume );

curried( 1 )( 2 )( 3 ); // 6  
</code></pre>

<h6 id="disclaimer">Disclaimer</h6>

<p>This post assumes basic familiarity with closures and higher-order functions, as well as stuff like <code>Function#apply()</code>. If you're not comfortable with those concepts, you might want to brush up before reading further.</p>

<h6 id="writingourcurryfunction">Writing our curry function</h6>

<p>The first thing you'll notice is that <code>curry</code> expects a function as its argument, so we'll start there.</p>

<pre><code>function curry( fn ) {

}
</code></pre>

<p>Next, we need to know how many arguments our function expects (called its "arity"). Otherwise, we won't know when to stop returning new functions and give back a value instead.</p>

<p>We can tell how many arguments a function expects by accessing its <code>length</code> property.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;
}
</code></pre>

<p>From there, things get a little bit trickier. </p>

<p>Essentially, every time a curried function is called, we add any new arguments to an array that's saved in a closure. If the number of arguments in that array is equal to the number of arguments that our original function expects, then we call it. Otherwise, we return a new function.</p>

<p>To do that, we need (1) a closure that can retain that list of arguments and (2) a function that can check the total number of arguments and either return another partially applied function <em>or</em> the return value of the original function with all of the arguments applied.</p>

<p>I usually do this with an immediately invoked function called <code>resolver</code>.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {

  }());
}
</code></pre>

<p>Now, the first thing we need to do in <code>resolver</code> is make a copy of any arguments it received. We'll do that by creating a variable called <code>memory</code> that uses <code>Array#slice</code> to make a copy of the <code>arguments</code> object.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {
    var memory = Array.prototype.slice.call( arguments );
  }());
}
</code></pre>

<p>Next, <code>resolver</code> needs to return a function. This is what the outside world sees when it calls a curried function.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {
    var memory = Array.prototype.slice.call( arguments );
    return function() {

    };
  }());
}
</code></pre>

<p>Since this internal function is the one that ends up actually being called, it needs to accept arguments. But it also needs to <em>add</em> those to any arguments that might be stored in <code>memory</code>. So first, we'll make a copy of <code>memory</code> by calling <code>slice()</code> on it.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {
    var memory = Array.prototype.slice.call( arguments );
    return function() {
      var local = memory.slice();
    };
  }());
}
</code></pre>

<p>Now, lets add our new arguments by using <code>Array#push</code>.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {
    var memory = Array.prototype.slice.call( arguments );
    return function() {
      var local = memory.slice();
      Array.prototype.push.apply( local, arguments );
    };
  }());
}
</code></pre>

<p>Good. Now we have a new array containing all the arguments we've received so far in this chain of partially applied functions.</p>

<p>The last thing to do is to compare the length of arguments we've received with the arity of our curried function. If the lengths match, we'll call the original function. If not, we'll use <code>resolver</code> to return yet another function that has all of our current arguments stored in memory.</p>

<pre><code>function curry( fn ) {  
  var arity = fn.length;

  return (function resolver() {
    var memory = Array.prototype.slice.call( arguments );
    return function() {
      var local = memory.slice(), next;
      Array.prototype.push.apply( local, arguments );
      next = local.length &gt;= arity ? fn : resolver;
      return next.apply( null, local );
    };
  }());
}
</code></pre>

<p>This can be a little bit difficult to wrap your head around, so let's take it step by step in an example.</p>

<pre><code>function volume( l, w, h ) {  
  return l * w * h;
}

var curried = curry( volume );  
</code></pre>

<p>Okay, so <code>curried</code> is the result of passing <code>volume</code> into our <code>curry</code> function.</p>

<p>If you look back, what's happening here is:</p>

<ol>
<li>We store the arity of <code>volume</code>, which is <code>3</code>.  </li>
<li>We immediately invoke <code>resolver</code> with no arguments, which means that for now, its <code>memory</code> array is empty.  </li>
<li><code>resolver</code> returns an anonymous function.</li>
</ol>

<p>Still with me? Now let's call our <code>curried</code> function and pass in a length.</p>

<pre><code>function volume( l, w, h ) {  
  return l * w * h;
}

var curried = curry( volume );  
var length = curried( 2 );  
</code></pre>

<p>Again, here are the steps:</p>

<ol>
<li>What we actually called here was the anonymous function being returned by <code>resolver</code>.  </li>
<li>We made a copy of <code>memory</code> (which was empty) and called it <code>local</code>.  </li>
<li>We added our argument (<code>2</code>) to the <code>local</code> array.  </li>
<li>Since the length of <code>local</code> is less than the arity of <code>volume</code>, we call <code>resolver</code> again with the list of arguments we have so far. That creates a new closure with a new <code>memory</code> array, which contains our first argument of <code>2</code>.  </li>
<li>Finally, <code>resolver</code> returns a new function that has access to an outer closure with our new <code>memory</code> array.</li>
</ol>

<p>So what we get back is that inner anonymous function again. But this time, it has access to a <code>memory</code> array that isn't empty. It has our first argument (a <code>2</code>) inside of it.</p>

<p>If we call our <code>length</code> function, the process repeats.</p>

<pre><code>function volume( l, w, h ) {  
  return l * w * h;
}

var curried = curry( volume );  
var length = curried( 2 );  
var lengthAndWidth = length( 3 );  
</code></pre>

<ol>
<li>Again, what we actually called was the anonymous function being returned by <code>resolver</code>.  </li>
<li>This time, <code>resolver</code> had been primed with some previous arguments. So we make a copy of that array <code>[ 2 ]</code>.  </li>
<li>We add our new argument, <code>3</code>, to the <code>local</code> array.  </li>
<li>Since the length of <code>local</code> is still less than the arity of <code>volume</code>, we call <code>resolver</code> again with the list of arguments we have so far – and that returns a new function.</li>
</ol>

<p>Now it's time to call our <code>lengthAndWidth</code> function and get back a value.</p>

<pre><code>function volume( l, w, h ) {  
  return l * w * h;
}

var curried = curry( volume );  
var length = curried( 2 );  
var lengthAndWidth = length( 3 );

console.log( lengthAndWidth( 4 ) ); // 24  
</code></pre>

<p>This time, the steps are a little bit different at the end:</p>

<ol>
<li>Once again, what we actually called was the anonymous function being returned by <code>resolver</code>.  </li>
<li>This time, <code>resolver</code> had been primed with two previous arguments. So we make a copy of that array <code>[ 2, 3 ]</code>.  </li>
<li>We add our new argument, <code>4</code>, to the <code>local</code> array.  </li>
<li>Now the length of <code>local</code> is <code>3</code>, which is the arity of <code>volume</code>. So instead of returning a new function, we return the result of calling <code>volume</code> with all of the arguments we've been saving up, and that gives us a value of <code>24</code>.</li>
</ol>

<h6 id="wrappingup">Wrapping up</h6>

<p>Admittedly, I have yet to find a super compelling use-case for currying in my day-to-day work. But I still think that going through the process of writing functions like this is a great way to improve your understanding of functional programming, and it helps reinforce concepts like closures and first-class functions.</p>

<p>By the way, if you like nerdy JavaScript things and live in the Boston area, I'm hiring at <a href="http://projectdecibel.com">Project Decibel</a>. Shoot me an <a href="mailto:kennis84@gmail.com">email</a>.</p>]]></content:encoded></item><item><title><![CDATA[How to impress me in an interview]]></title><description><![CDATA[<p>In the past few years, I've interviewed dozens of candidates for JavaScript-heavy roles. Over that time, I've identified a few key areas that seem to be pretty good indicators of overall proficiency – and I focus on these pretty much exclusively in my technical interviews.</p>

<p>First and foremost, this post is</p>]]></description><link>http://kevvv.in/how-to-impress-me-in-an-interview/</link><guid isPermaLink="false">4c3cb7b3-9270-45d4-a52d-5d82a1aa8980</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Sat, 18 Jul 2015 13:47:04 GMT</pubDate><content:encoded><![CDATA[<p>In the past few years, I've interviewed dozens of candidates for JavaScript-heavy roles. Over that time, I've identified a few key areas that seem to be pretty good indicators of overall proficiency – and I focus on these pretty much exclusively in my technical interviews.</p>

<p>First and foremost, this post is about what to expect if you're interviewing with me. But it's also about how to conduct a technical interview of JS candidates, and which areas offer the best signal-to-noise ratios.</p>

<h6 id="thisisnotatest">This is Not a Test</h6>

<p>The most important thing that I try to stress in any technical interview is that I'm not administering a test. What I'm really interested in is using questions as a tool for facilitating a conversation about code.</p>

<p>So if I ask you to write a <code>memoize()</code> function, what I really want is to give us a starting point to talk about higher-order functions and closures. I don't really care if you can write that function off the top of your head. Instead, what I'm really looking for is whether or not you can arrive at a solution with a little bit of guidance, and if you understand the underlying concepts.</p>

<p>If you get stuck along the way, ask for some help. And if you flat out don't know an answer, that's okay too. I'll do my best to explain it, and we'll work on another example together.</p>

<p>One of the most impressive things you can do in an interview is learn something new and then apply it. It lets me see how you think about problems and assimilate new information.</p>

<p>Anyway, the point is: not knowing things is totally okay.</p>

<h6 id="whiteboards">Whiteboards</h6>

<p>There seems to be a lot of anxiety these days about whiteboarding during interviews. Every couple weeks, I see an article on Hacker News about what a terrible, outmoded practice this is. </p>

<p>And for the most part, I agree.</p>

<p>That said, if you interview with me, you should expect to walk in to a room with a whiteboard on the wall. And you should expect that we'll use it.</p>

<p>Whiteboards are great for quick examples. If I ask you what an IIFE is, or how to write a ternary expression, I expect you to be able to jot that down on a whiteboard. Or maybe I'll write a function on the board and ask you what its return value is given a certain set of arguments.</p>

<p>What I won't <em>ever</em> do – and what I think is the primary cause of apprehension about whiteboarding – is ask you to write some big, 20-line function on a whiteboard. It's unnatural, it's slow, and frankly, it's pretty hard for me to read your code that way anyway.</p>

<h6 id="frameworkslibraries">Frameworks &amp; Libraries</h6>

<p>Don't care.</p>

<p>As JavaScript engineers, we use third-party code all day, every day. On the front-end, there's jQuery, Underscore, Backbone, Ember, Angular, React, Moment, D3, Bluebird, THREE, and a million others. With Node, there are currently something like 166,000 packages on npm.</p>

<p>We're all learning new APIs constantly, and it's totally unreasonable to expect that you happen to know the same ones that I do. I will almost never ask specific questions about libraries or frameworks.</p>

<p>If you've got a strong understanding of fundamental JS concepts, you'll learn the libraries we're using pretty quickly. </p>

<p>I'm just not that worried about it.</p>

<h6 id="closuresandfirstclassfunctions">Closures and First-Class Functions</h6>

<p>Super important. I expect everyone I interview to be very comfortable with these concepts.</p>

<p>Here's a typical example that I might present to a candidate:</p>

<pre><code>// write a function called `partial` that makes 
// the following snippet work

function add( a, b ) {  
  return a + b;
}

var add5 = partial( add, 5 );

add5( 4 ); // 9  
</code></pre>

<p>If that elicits a deer-in-the-headlights look, I might steer the discussion like this:</p>

<p>"Okay, so it looks like <code>partial</code> accepts two arguments. One is a function, and the other is a number."</p>

<p>That'll usually get us at least to this point:</p>

<pre><code>function partial( fn, num ) {

}
</code></pre>

<p>"Great. And <code>partial</code> must return a function, because we're assigning its return value to <code>add5</code> and then calling <code>add5()</code>".</p>

<pre><code>partial( fn, num ) {  
  return function() {

  };
}
</code></pre>

<p>"Cool. That's the basic idea. So, if <code>add5</code> is the function that <code>partial</code> returns and it expects a number as an argument, where does that go?"</p>

<p>Usually, this is the point where a light bulb turns on.</p>

<pre><code>partial( fn, a ) {  
  return function( b ) {
    return fn( a, b );
  };
}
</code></pre>

<p>Again, the point here is not necessarily that you can do this without any help (although that's great, and it's what I'd expect from a more senior candidate). What I'm really hoping is that you can get there with a little bit of direction.</p>

<h6 id="prototypalinheritance">Prototypal Inheritance</h6>

<p>This is definitely an area that tends to separate junior devs from more senior ones, although in my mind, it's something <em>everyone</em> applying for a JS role should know.</p>

<p>Here's a problem that I might give to a candidate:</p>

<pre><code>// make a class called `Square` that inherits from 
// `Rectangle` and satisfies the following snippet

function Rectangle( width, height ) {  
  this.width = width;
  this.height = height;
}

Rectangle.prototype.area = function() {  
  return this.width * this.height;
};

// your code here

var square = new Square( 4 );

square.area(); // 16  
Square.prototype.area === Rectangle.prototype.area; // true  
</code></pre>

<p>If this looks foreign to you, I would strongly recommend brushing up on prototypal inheritance. It's really not very hard once you get the hang of it, and it's an extremely powerful and important feature of JavaScript.</p>

<p>Oh, and here's the answer:</p>

<pre><code>function Square( length ) {  
  Rectangle.call( this, length, length );
}

Square.prototype = Object.create( Rectangle.prototype );  
</code></pre>

<h6 id="whatsthis">What's <code>this</code>?</h6>

<p>There's probably no other feature in JS with a worse simplicity-to-confusion ratio than the <code>this</code> keyword. You can basically learn everything about it in an hour, but so many JS developers never do.</p>

<p>You should know how <code>Function#call()</code> and <code>Function#apply()</code> work. They are absolutely essential to writing JS at a high level, and they're super easy to wrap your head around.</p>

<p>This is low-hanging fruit.</p>

<h6 id="async">Async</h6>

<p>Another big one, especially if you're applying for a job where you'll be using Node.</p>

<p>Here's a question I might ask:</p>

<pre><code>// write a function called `shout` that accepts
// a string and a callback function, and uses
// `exclaim` and `yell` to transform its input

function exclaim( value, fn ) {  
  setTimeout(function() {
    fn( value + '!' );
  }, 100 );
}

function yell( value, fn ) {  
  setTimeout(function() {
    fn( value.toUpperCase() );
  }, 100 );
}

shout( 'hello', function( shouted ) {  
  console.log( shouted ); // 'HELLO!'
});
</code></pre>

<p>Again, this is really something that I expect every JS candidate to be comfortable with. If you're about to interview for a JS gig and you're not familiar with this stuff, drop what you're doing and spend some time practicing.  It's that important.</p>

<p>Oh, and the solution to that problem:</p>

<pre><code>function shout( value, fn ) {  
  exclaim( value, function( exclaimed ) {
    yell( exclaimed, fn );
  }); 
}
</code></pre>

<h6 id="trickquestions">Trick Questions</h6>

<p>Personally, not a fan.</p>

<p>In the rare occasion that I <em>do</em> ask a trick question, I'll call it out beforehand, and I won't really care if you miss the "trick". What I'm really trying to accomplish in cases like this is to start a conversation.</p>

<p>"Not quite. Remember, variables get hoisted in JavaScript..."</p>

<p>"That's actually a <code>ReferenceError</code>. Can you see why?"</p>

<p>Questions like this can be really useful, but I use them pretty sparingly because nobody likes to feel like they've been set up for failure.</p>

<h6 id="advancedstuff">Advanced Stuff</h6>

<p>Okay, so you were able to breeze through closures, prototypal inheritance, and async functions. Now what?</p>

<p>At this point in an interview, I'm usually pretty confident that a candidate has an intermediate to advanced understanding of the language, and my goals for the interview start to shift a little.</p>

<p>What I really want to know now is <em>how much</em> you know. I'm trying to get a sense of the shape and depth of your JavaScript knowledge.</p>

<p>This is where we start to move away from core concepts and I might start asking about specific language features or more advanced functional programming.</p>

<p>I might ask you to use <code>Object.defineProperty</code> or to write a <code>curry</code> function. Maybe we'll talk about promises or recursion.</p>

<p>These are things that you don't really <em>have</em> to know, per se, but since you've got the basic stuff down, I need to ask these types of questions to get a better sense of how advanced you are.</p>

<p>Think of this as extra credit. It's an opportunity to impress me. Anything we talk about at this point is essentially just bonus material.</p>

<h6 id="memorization">Memorization</h6>

<p>This is sort of a tricky area, and I'm a little bit conflicted.</p>

<p>I expect a senior level JS person to know the argument signatures for <code>Array#splice()</code> or <code>Function#bind()</code>.</p>

<p>At the same time, I have never worked in an office without an Internet connection – and looking something up on MDN takes about 20 seconds.</p>

<p>I never explicitly quiz candidates on stuff like this, because it just doesn't strike me as being particularly important. That said, if I realize during the course of our interview that you don't know how to use a common method like <code>Array#push()</code>, that's a pretty good indicator that you haven't been writing JS for very long.</p>

<p>In short: Learn the most commonly used stuff, but don't feel like you need to memorize the entire EcmaScript spec.</p>

<h6 id="askquestions">Ask Questions</h6>

<p>If you only take one thing away from this post, let it be this:</p>

<p><strong>If you don't know something, or you aren't sure, ask me.</strong></p>

<p>Not knowing something is a problem with a very simple solution. Lacking intellectual curiosity is much harder to fix.</p>

<p>I love hiring candidates who need a bit of mentoring. It's fun for me, and it's great for the team. One of the best ways to crystalize your own understanding of a concept is to explain it to someone else, and fostering a team environment where we're all teachers <em>and</em> students is the best way I know to continually raise the bar for everyone.</p>

<p>We all have plenty more to learn, myself included. My goal has always been to hire people who embrace that fact, and who are genuinely excited about learning new things and becoming stronger engineers.</p>

<h6 id="imhiring">I'm Hiring</h6>

<p>Is this hypothetical interview sounding pretty fun to you? Are you in the Boston area?</p>

<p>Shoot me an <a href="http://kevvv.in/how-to-impress-me-in-an-interview/kennis84@gmail.com">email</a>, and come work on <strong>crazy</strong>, top-secret things at <a href="http://projectdecibel.com">Project Decibel</a>.</p>]]></content:encoded></item><item><title><![CDATA[New Blog]]></title><description><![CDATA[<p>Using Ghost now because I'm basic.</p>]]></description><link>http://kevvv.in/new-blog/</link><guid isPermaLink="false">4441cb81-9006-4c1c-87b1-625b6c42d33c</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Wed, 10 Jun 2015 01:51:15 GMT</pubDate><content:encoded><![CDATA[<p>Using Ghost now because I'm basic.</p>]]></content:encoded></item><item><title><![CDATA[V8 Profiling]]></title><description><![CDATA[<p>I've been kind of obsessed with V8 (and the d8 shell) lately, so I wrote up a thing for friends and co-workers <br>
about what I've learned so far. </p>

<p>I tried to copy the markdown from the Gist I wrote, but it looked like <a href="http://giphy.com/gifs/pwXqpzXwIs9jy">garbage</a> with my site's stylesheet, so here's</p>]]></description><link>http://kevvv.in/v8-profiling/</link><guid isPermaLink="false">52fbf35a-189e-4a4d-8eb9-0de02cfaca46</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Thu, 14 Aug 2014 16:00:00 GMT</pubDate><content:encoded><![CDATA[<p>I've been kind of obsessed with V8 (and the d8 shell) lately, so I wrote up a thing for friends and co-workers <br>
about what I've learned so far. </p>

<p>I tried to copy the markdown from the Gist I wrote, but it looked like <a href="http://giphy.com/gifs/pwXqpzXwIs9jy">garbage</a> with my site's stylesheet, so here's a <a href="https://gist.github.com/kevincennis/0cd2138c78a07412ef21">link</a> instead.</p>

<p>Enjoy.</p>]]></content:encoded></item><item><title><![CDATA[Fun With ES6]]></title><description><![CDATA[<p>With more and more progress being made on ES6, and a steady stream of new feature implementations <br>
showing up in Firefox and Chrome, I thought it might be fun to take some real-world code and <br>
refactor it to take advantage of forthcoming language additions.</p>

<p>These examples are by no means</p>]]></description><link>http://kevvv.in/fun-with-es6/</link><guid isPermaLink="false">6eea7e09-8f22-406f-b018-3703e37b269e</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Thu, 15 Aug 2013 16:00:00 GMT</pubDate><content:encoded><![CDATA[<p>With more and more progress being made on ES6, and a steady stream of new feature implementations <br>
showing up in Firefox and Chrome, I thought it might be fun to take some real-world code and <br>
refactor it to take advantage of forthcoming language additions.</p>

<p>These examples are by no means an exhaustive overview of what's new in ES6, and since <br>
the spec isn't complete, a lot of these are subject to change. Nonetheless, it's still <br>
kind of fun to get an idea of what the future of JavaScript looks like.</p>

<p><em>Disclaimer: I'm not saying that the following examples are necessarily The Right Way™ to 
refactor in ES6. They're really just meant to be a vehicle for demonstrating some cool new stuff.</em></p>

<h3 id="_range">_.range</h3>

<p>The first example comes from Underscore's <code>_.range</code> method. Here's the original:</p>

<pre><code>_.range = function(start, stop, step) {
  if (arguments.length &lt;= 1) {
    stop = start || 0;
    start = 0;
  }
  step = arguments[2] || 1;

  var len = Math.max(Math.ceil((stop - start) / step), 0);
  var idx = 0;
  var range = new Array(len);

  while(idx &lt; len) {
    range[idx++] = start;
    start += step;
  }

  return range;
};
</code></pre>

<p>The thing I love about this example is that the problem is so straight-forward. It's hard to imagine <br>
anyone taking a drastically different approach here. Sure, some people might not initialize that <br>
<code>range</code> array with a length, and would instead rely on pushing values. But ultimately, the basic
mechanism is going to be the same.</p>

<p>What does stand out though, at least to me, is all that boilerplate in the first few lines of the function <br>
body. This is a pretty common sight in JavaScript for polymorphic methods. There's really never been <br>
a particularly elegant way to deal with a variable number of arguments.</p>

<p>Fortunately, this is one area where ES6 really comes through. Here's the same method, refactored <br>
to take advantage of some of ECMAScript's forthcoming features:</p>

<pre><code>_.range = function(start = 0, stop = start, step = 1) {
    var len = Math.max(Math.ceil((stop - start) / step), 0),
        range = new Array(len);
    for (let idx = 0; idx &lt; len; ++idx) {
      [range[idx], start] = [start, start += step];
    }
    return range;
};
</code></pre>

<p>The first thing you'll notice is that we've got default parameters. Because I can define <br>
defaults, I was able to remove 5 lines of code right off the bat. Not only that, but I think <br>
this syntax is also significantly more explicit, especially once you get used to it.</p>

<p>Second change is the use of the <code>let</code> statement in the loop. <code>let</code> is similar to <code>var</code>, except it has <br>
block scope rather than function scope. In this case, there's honestly not much of a difference, but it <br>
seemed worth demonstrating - especially since <code>let</code> is <em>already implemented</em> in Firefox, Chrome, and IE11. <br>
In this case, the main advantage is basically cosmetic. Since <code>idx</code> is only important to me inside that loop, <br>
I can scope it accordingly to reflect that.</p>

<p>The third change is the destructiring assignment inside the loop. I'm not going to dive into that, because <br>
my explanation wouldn't be nearly as good as what you'll get by reading <a href="http://fitzgeraldnick.com/weblog/50/">This post</a> <br>
by Nick Fitzgerald. And you should definitely read that. Immediately. </p>

<p>Really. Go ahead, I'll wait.</p>

<h3 id="backbonemodel">Backbone.Model</h3>

<p>Oh good, you're back.</p>

<p>Next example comes from Backbone's <code>Backbone.Model</code>:</p>

<pre><code>var Model = Backbone.Model = function(attributes, options) {
    var defaults;
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId('c');
    this.attributes = {};
    _.extend(this, _.pick(options, modelOptions));
    if (options.parse) attrs = this.parse(attrs, options) || {};
    if (defaults = _.result(this, 'defaults')) {
        attrs = _.defaults({}, attrs, defaults);
    }
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
};
</code></pre>

<p>This is a simple example, but also a pretty important one. Defining "classes" in JavaScript <br>
has always been a little bit awkward. First, you write a function (and probably capitalize the first <br>
letter to indicate that it's a constructor, though this is just a convention). Then, completely <em>outside</em> <br>
of that function definition, you start adding methods to its <code>prototype</code> object. It just looks sort of messy, <br>
and fails to really convey what your intention is.</p>

<p>This is where ES6 classes come in:</p>

<pre><code>var Model = Backbone.Model = class Model {
    constructor (attrs = {}, options = {}) {
        this.cid = _.unique('c');
        this.attributes = {};
        _.extend(this, _.pick(options, modelOptions));
        if (options.parse) attrs = this.parse(attrs, options) || {};
        if (defaults = _.result(this, 'defaults')) {
            attrs = _.defaults({}, attrs, defaults);
        }
        this.set(attrs, options);
        this.changed = {};
        this.initialize.apply(this, arguments);
    }
};
</code></pre>

<p>Not too much has really changed here, except for the fact that we're substituting that anonymous <br>
constructor function with a <code>class</code> definition. Then we just move the original function body inside <br>
of the <code>constructor</code> definition and pretty much call it a day, aside from swapping out some boilerplate <br>
for default params.</p>

<p>The beauty here is that (a) this is a lot more explicit, and (b) we can also put our methods <br>
<em>inside the class definition</em>, like this:</p>

<pre><code>var Model = Backbone.Model = class Model {
    constructor (attrs = {}, options = {}) {
        ...
    }
    sync() {
        return Backbone.sync.apply(this, arguments);
    }
    get(attr) {
        return this.attributes[attr];
    }
};
</code></pre>

<p>So now we're being a lot clearer about the intent of the code. The constructor and method definitions <br>
are all living in the same place. It's easier to read and understand what's going on.</p>

<h3 id="backbonecollectiontojson">Backbone.Collection#toJSON</h3>

<p>This final example is a really small one, but it lets me demonstrate one of my favorite ES6 features.</p>

<p>Here's the original code for <code>Backbone.Collection#toJSON</code>:</p>

<pre><code>toJSON: function(options) {
    return this.map(function(model){ return model.toJSON(options); });
}
</code></pre>

<p>That inner line, where we pass an anonymous one-line function to <code>map</code> is something that happens <br>
<em>all the time</em> in JavaScript.</p>

<p>Soon, we'll have an easier way:</p>

<pre><code>toJSON2: function(options) {
    return this.map(model =&gt; model.toJSON(options));
}
</code></pre>

<p>If you've ever used CoffeeScript, this should look pretty familiar. If not, that's called a fat-arrow function.</p>

<p>Basically, it's shorthand syntax for an anonymous function that returns a value. It doesn't need a <code>function</code> keyword, <br>
the parens are optional when there's a single parameter, the value of <code>this</code> is bound to the containing scope, <br>
and automatically return the value of the expression following the fat arrow.</p>

<h3 id="wrappingup">Wrapping up</h3>

<p>The point here wasn't really to give a comprehensive or in-depth overview of everything in ES6. It's really <br>
just to highlight a few interesting changes in the context of how they might be used in the real world. I highly <br>
recommend reading the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals">proposals</a> and trying this <br>
stuff out for yourself.</p>

<p>If that sounds fun, check out Google's <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a>, which lets <br>
you write ES6 and compile it into valid ES5. They even have an <a href="http://traceur-compiler.googlecode.com/git/demo/repl.html">online version</a> <br>
that's great for quick experiments, or if (like me) you're just too lazy to download the code.</p>]]></content:encoded></item><item><title><![CDATA[Displaying Hidden Elements]]></title><description><![CDATA[<p>Here's a fun fact:</p>

<p>Did you know you can set <code>display:block;</code> on things like <code>&lt;title/&gt;</code> elements? Kind of cool, right? If you're <em>super</em> concerned about crazy small request sizes, you could probably save a couple bytes by displaying your <code>&lt;title&gt;</code> instead of an <code>&lt;h1&</code></p>]]></description><link>http://kevvv.in/displaying-hidden-elements/</link><guid isPermaLink="false">54e4a47e-3a70-4ac2-bcc4-41255fde0661</guid><dc:creator><![CDATA[Kevin Ennis]]></dc:creator><pubDate>Mon, 12 Aug 2013 16:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Here's a fun fact:</p>

<p>Did you know you can set <code>display:block;</code> on things like <code>&lt;title/&gt;</code> elements? Kind of cool, right? If you're <em>super</em> concerned about crazy small request sizes, you could probably save a couple bytes by displaying your <code>&lt;title&gt;</code> instead of an <code>&lt;h1&gt;</code>. Overkill, for sure -- but still sort of interesting.</p>

<p>But another, slightly cooler trick is adding a <code>display:block; white-space: pre;</code> rule for select <code>&lt;script&gt;</code> elements.</p>

<p>This is kind of awesome for times when you want to include a code sample in your page, but you also <em>want that code to actually execute</em>. Sure, you don't get syntax highlighting -- but you <em>do</em> get a couple extra nerd points. And you reduce the weight of your page a bit by not duplicating that code.</p>

<p><em>The More You Know™</em></p>]]></content:encoded></item></channel></rss>