<?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[{kev: blog}]]></title><description><![CDATA[Thoughts, stories, and ideas on web development]]></description><link>http://kevhuang.com/</link><generator>Ghost 0.6</generator><lastBuildDate>Wed, 01 Jun 2022 06:23:57 GMT</lastBuildDate><atom:link href="http://kevhuang.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Using React with Babel and Webpack Hot Module Replacement Middleware]]></title><description><![CDATA[How to set up Webpack HMR middleware with Express and React]]></description><link>http://kevhuang.com/using-react-with-webpack-hot-module-replacement-middleware/</link><guid isPermaLink="false">4f60638e-e964-4da6-a5a9-d00fd9b72adc</guid><category><![CDATA[tutorial]]></category><category><![CDATA[es6]]></category><category><![CDATA[react]]></category><category><![CDATA[webpack]]></category><category><![CDATA[babel]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Fri, 05 Feb 2016 08:31:36 GMT</pubDate><media:content url="http://kevhuang.com/content/images/2016/02/webpack-logo.png" medium="image"/><content:encoded><![CDATA[<img src="http://kevhuang.com/content/images/2016/02/webpack-logo.png" alt="Using React with Babel and Webpack Hot Module Replacement Middleware"><p>If you're developing a web application using React and ES6/ES2015, you may have cursed at the computer or impatiently tapped your fingers while waiting for files to compile and then having to manually reload the browser to see the latest changes. I used to use Gulp to help streamline the process of watching source files and rebuilding them with Webpack on any changes. That helped, but it can still take a while, especially if you have a large app.</p>

<p>Then, I started to embrace hot module replacement (<a href="http://webpack.github.io/docs/hot-module-replacement-with-webpack.html">HMR</a>), or hot reloading, using Webpack. In short, this just means whenever your source files are modified and saved, only the changed module is rebuilt instead of every single module in your project. Then, the HMR runtime (your browser) will automatically listen for any patches, apply the patches (if possible), and then automatically reload. This all happens pretty fast and it speeds up development time!</p>

<h3 id="targetaudience">Target audience</h3>

<p>There are several methods to implementing HMR. This tutorial is specifically aimed towards the following:</p>

<ul>
<li>You want to use your own Express 4 server instead of the <a href="http://webpack.github.io/docs/webpack-dev-server.html">webpack-dev-server</a> that you may have came across</li>
<li>Your server-side code is written in ES6, and you are using Babel's require hook: <code>require('babel-register')</code></li>
<li>You want to use <a href="https://github.com/gaearon/react-transform-hmr">react-transform-hmr</a></li>
</ul>

<p>Let's get down to it.</p>

<h3 id="prerequisites">Prerequisites</h3>

<p>I assume you already have Express and React installed and all set up. I'll walk you through what you'll need for Babel and Webpack. Install the following npm packages:</p>

<p><code>npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-react-hmre webpack webpack-dev-middleware webpack-hot-middleware</code></p>

<p>Here we are using <code>babel-preset-react-hmre</code>. This is a convenience package that sets up <code>react-transform-hmr</code> as a preset for Babel.</p>

<h3 id="setup">Setup</h3>

<h4 id="babel">Babel</h4>

<p>Create a <code>.babelrc</code> file in your project's root directory, and put the following in the file:</p>

<pre><code>{
  "presets": ["react", "es2015"]
}
</code></pre>

<p>This allows Babel to transpile your React JSX and ES6 code.</p>

<h4 id="webpack">Webpack</h4>

<p>Create a <code>webpack.dev.config.js</code> file in your project's root directory, with the following:</p>

<pre><code>var webpack = require('webpack')

module.exports = {  
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  entry: ['webpack-hot-middleware/client', './app.js'],
  output: {
    path: __dirname + '/build/js',
    filename: 'bundle.js',
    publicPath: '/public/js'
  },
  devTool: 'cheap-module-source-map',
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['react-hmre']
        }
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};
</code></pre>

<p>You can modify whatever settings you want based on your project or preferences, but just make sure you do the following:</p>

<ol>
<li>Include <code>webpack-hot-middleware/client</code> as an entry point  </li>
<li>Set <code>output.publicPath</code> to the path the client expects to find the bundled js file, e.g., if your html page has <code>&lt;script src="/js/bundle.js"&gt;&lt;/script&gt;</code>, then your <code>publicPath</code> would be <code>/js</code>. This is where the virtual bundle for HMR will be served from.  </li>
<li>For the JS/JSX loader, use <code>babel</code> (you can also use <code>babel-loader</code>) and include the <code>query</code> option for referencing the <code>react-hmre</code> preset  </li>
<li>Include <code>HotModuleReplacementPlugin</code></li>
</ol>

<p>Also notice how we named the file for the dev environment. You wouldn't be using HMR in production, so you should make a separate Webpack config file just for production that doesn't use HMR.</p>

<p>Another thing to point out is that the <code>react-hmre</code> preset is set up in the config file. Normally, you would set up Babel settings in <code>.babelrc</code>. However, again, this tutorial is geared towards using ES6 on the server-side, and if you use Babel to transpile the server-side code, you're probably using their require hook.</p>

<p>Now, you don't want to want to enable hot reload on the server; you just need it on the client side. So if you do <code>require('babel-register')</code>, that will load <code>.babelrc</code>, and you don't want the HMR preset in there to be loaded on the server side.</p>

<h4 id="expressserver">Express server</h4>

<p>In your server, add the following before your other middleware:</p>

<pre><code>if (process.env.NODE_ENV === 'development') {  
  let webpack = require('webpack'),
    webpackConfig = require('./webpack.dev.config.js'),
    compiler = webpack(webpackConfig);

  server.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath
  }));

  server.use(require('webpack-hot-middleware')(compiler));
}
</code></pre>

<p>And that's it! Simply launch your server, bring it up in your browser, make a change to a source file, and see the browser automatically reload to include the changes!</p>]]></content:encoded></item><item><title><![CDATA[Performance Differences for Inserting Into an Array]]></title><description><![CDATA[<p>I was bored and curious and decided to compare the performance among different ways of inserting an element into the middle of an array.</p>

<p>I tried three methods:</p>

<ol>
<li>Using <code>Array.splice()</code>  </li>
<li>Using <code>Array.slice()</code> and <code>Array.concat()</code>  </li>
<li>Using the ES6 rest operator</li>
</ol>

<p>The winner was using the combination of <code>Array.</code></p>]]></description><link>http://kevhuang.com/performance-differences-for-inserting-into-an-array/</link><guid isPermaLink="false">8832b8bb-a7a8-4a6f-8039-b13323c02fcc</guid><category><![CDATA[javascript]]></category><category><![CDATA[es6]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Sun, 24 Jan 2016 05:52:00 GMT</pubDate><content:encoded><![CDATA[<p>I was bored and curious and decided to compare the performance among different ways of inserting an element into the middle of an array.</p>

<p>I tried three methods:</p>

<ol>
<li>Using <code>Array.splice()</code>  </li>
<li>Using <code>Array.slice()</code> and <code>Array.concat()</code>  </li>
<li>Using the ES6 rest operator</li>
</ol>

<p>The winner was using the combination of <code>Array.slice()</code> and <code>Array.concat()</code>—at least in Chrome 47 and Firefox 43. 2nd place goes to using the ES6 rest operator. Check out the <a href="http://jsperf.com/insert-mid-array">jsPerf</a>.</p>

<p>There are also more performant ways to insert to the beginning and end of an array that aren't commonly used. In short, for adding to the beginning of an array, you may typically use <code>existingArray.unshift(newItem)</code>, but <code>[newItem].concat(existingArray)</code> is <em>way</em> faster.</p>

<p>And for adding to the end of an array, you may typically use <code>existingArray.push(newItem)</code>, but <code>existingArray[existingArray.length] = newItem</code> is faster.</p>

<p>Check out the jsPerf results for inserting to the <a href="http://jsperf.com/unshift-item-inside-an-array">beginning</a> and to the <a href="http://jsperf.com/push-item-inside-an-array">end</a> that were created by others.</p>]]></content:encoded></item><item><title><![CDATA[ES6 Promises: Best Practices]]></title><description><![CDATA[<p>After using more and more promises lately, I've gathered a handful of good and bad design patterns for promises. I'm going to list out some examples of how promises are typically used and demonstrate anti-patterns and how to clean them up. Like everyone, I've been guilty to some of these</p>]]></description><link>http://kevhuang.com/es6-promises-best-practices/</link><guid isPermaLink="false">5d6d2cae-b084-4439-a1a9-d46f22886f3b</guid><category><![CDATA[javascript]]></category><category><![CDATA[tutorial]]></category><category><![CDATA[es6]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Tue, 28 Jul 2015 03:22:00 GMT</pubDate><media:content url="http://kevhuang.com/content/images/2015/07/pinky-promise.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://kevhuang.com/content/images/2015/07/pinky-promise.jpg" alt="ES6 Promises: Best Practices"><p>After using more and more promises lately, I've gathered a handful of good and bad design patterns for promises. I'm going to list out some examples of how promises are typically used and demonstrate anti-patterns and how to clean them up. Like everyone, I've been guilty to some of these anti-patterns, but it's all good. We're here to learn. I promise I'll try not to use any puns. Ah crap.</p>

<h3 id="callbackstyle">Callback Style</h3>

<p>You may be tempted to attach both fulfillment and rejection handlers in a <code>.then()</code> call. For example:</p>

<pre><code>somethingAsync().then(function(result) {  
  // Do something on success/fulfillment
}, function(err) {
  // Do something on error/rejection
});
</code></pre>

<p>The problem with that approach is that what if an error is thrown within your success handler? Your error handler won't catch that, as the error handler will only handle errors thrown from the <code>somethingAsync()</code> call.</p>

<p>Promises have the ability to handle errors or rejections anywhere in the promise chain/composition. As a result, you should use <code>.catch()</code> to handle any errors in the chain. This comes in handy when you have a chain of <code>then</code>'s. Example:</p>

<pre><code>somethingAsync()  
  .then(function(result) {
    // Do something on success/fulfillment of somethingAsync()
  })
  .then(function(result) {
    // Do something on success/fulfillment of the previous then()
  })
  .catch(function(err) {
    // Do something on any error/rejection in the chain
  });
</code></pre>

<h3 id="chainingpromises">Chaining Promises</h3>

<p>As we saw in the previous example, promises can be chained. The chain can consist of synchronous or asynchronous operations. Example:</p>

<pre><code>somethingAsync1()  
  .then(function(result) {
    // Handle fulfillment result from somethingAsync1()
    somethingAsync2(result);
  })
  .then(function(result) {
    // Handle fulfillment result from somethingAsync2()
    somethingSync1(result);
  })
  .catch(function(err) {
    // Do something on any error/rejection in the chain
  });
</code></pre>

<p>In that example, you may think the order of operations is the following: somethingAsync1() -> somethingAsync2() -> somethingSync1(). However, you don't know how long <code>somethingAsync2()</code> will take, and before it resolves, <code>somethingSync1()</code> would have already been invoked.</p>

<p>When you are chaining promises, make sure you return a value from your <code>.then()</code> calls. This is especially important when you have one <code>then</code> calling an asynchronous operation. If the next <code>then</code> in the chain needs the results from this asynchronous operation, the subsequent <code>then</code> must wait for the operation to be resolved. You should return one of the following values from your <code>then</code> handlers:</p>

<ul>
<li>a new Promise</li>
<li>a synchronous value or undefined</li>
<li>or, throw an Error or Exception</li>
</ul>

<p>The previous example should be re-written like so, assuming <code>somethingAsync2()</code> returns a Promise:</p>

<pre><code>somethingAsync1()  
  .then(function(result) {
    // Handle fulfillment result from somethingAsync1()
    return somethingAsync2(result);
  })
  .then(function(result) {
    // Handle fulfillment result from somethingAsync2()
    somethingSync1(result);
  })
  .catch(function(err) {
    // Do something on any error/rejection in the chain
  });
</code></pre>

<h3 id="nestedpromises">Nested Promises</h3>

<p>You've probably seen callback hell. Example:</p>

<pre><code>asyncFunction1(function(err, result) {  
  asyncFunction2(function(err, result) {
    asyncFunction3(function(err, result) {
      asyncFunction4(function(err, result) {
       asyncFunction5(function(err, result) {
         // Do something
       });
      });
    });
  });
});
</code></pre>

<p><img src="http://kevhuang.com/content/images/2015/07/xzibit-loves-callbacks.png" alt="ES6 Promises: Best Practices"></p>

<p>That can get ugly and out of hand. One way to fix this is to chain promises like we saw earlier. Doing so would give you a flat structure and would allow you to run tasks in a series. Another way is to use <code>Promise.all()</code>.</p>

<p><code>Promise.all()</code> takes an iterable object like an array and returns a Promise. The array should contain promises. If an element isn't a Promise, it is automatically converted to one with <code>Promise.resolve()</code>. All the promises in the array will be executed in parallel, and after they are all resolved, the <code>then</code> handler for the <code>all</code> Promise will handle the results. If any of the promises reject, the <code>all</code> Promise will immediately be rejected. Note that the following example does not depend on the order of which the promises are resolved.</p>

<pre><code>var a = promise1;  
var b = promise2;  
var c = promise3;

Promise.all([a,b,c])  
  .then(function(results) {
    // results[0] contains the result from promise1, results[1] is for promise2, ...
  })
  .catch(function(err) {
    // Handle rejections from any of the promises
  });
</code></pre>

<h3 id="summary">Summary</h3>

<p>I hope you take these recommendations into consideration when working with promises. Feel free to leave comments on other best practices or tips when working with promises.</p>]]></content:encoded></item><item><title><![CDATA[String Compression and Concatenation Performance]]></title><description><![CDATA[<p>Here is a whiteboarding problem that may come up in interviews.</p>

<p>You are given a string. Implement a function to perform basic string compression using the counts of repeated characters. For example, the string <code>aabcccccaaa</code> would become <code>a2blc5a3</code>. If the "compressed" string would not become smaller than the original string,</p>]]></description><link>http://kevhuang.com/string-compression-and-concatenation-performance/</link><guid isPermaLink="false">c7297d4d-2e26-490f-afa0-d4451053bf45</guid><category><![CDATA[javascript]]></category><category><![CDATA[tutorial]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Sat, 27 Jun 2015 02:19:00 GMT</pubDate><content:encoded><![CDATA[<p>Here is a whiteboarding problem that may come up in interviews.</p>

<p>You are given a string. Implement a function to perform basic string compression using the counts of repeated characters. For example, the string <code>aabcccccaaa</code> would become <code>a2blc5a3</code>. If the "compressed" string would not become smaller than the original string, the function should return the original string. For example, the string <code>aabc</code> would remain <code>aabc</code> because <code>a2b1c1</code> is larger than the original.</p>

<p>This is a pretty simple problem to solve. Here is a basic implementation:</p>

<pre><code>var compressedString = function(str) {  
  if (str.length &lt; 3) return str;

  var compressedStr = '';
  var prevChar = str.charAt(0);
  var count = 1;

  for (var i = 1; i &lt; str.length; i++) {
    if (str[i] !== prevChar) {
      compressedStr += prevChar + count;
      prevChar = str[i];
      count = 1;
    } else {
      count++;
    }
  }
  compressedStr += prevChar + count;

  return compressedStr.length &gt;= str.length ? str : compressedStr;
};
</code></pre>

<p>That was my initial stab at the solution. I was then curious to see how others went about it. While I was doing research, I learned something new. The string concatenation happening within the for-loop using <code>compressedStr += prevChar + count</code> can potentially operate in O(n²) time, depending on the environment; some browsers have optimizations to make string concatenation more performant.</p>

<p>In JavaScript, strings are immutable—they cannot be changed. As a result, doing concatenation using <code>+=</code> will create a copy of the string by iterating through each character one at a time (O(n)), and then appending the new string to the end. So because the string concatenation happens in linear time, and you have to iterate up to n characters with the for-loop, that results to O(n²).</p>

<p>If you have a large string and time is important, then a data structure like a StringBuffer would give you O(n) time. In a nutshell, a StringBuffer is an array that progressively collects each character of a string, and then at the end, it joins all the characters as a string. Thus, the concatenation only happens once at the very end instead of each time a new character is added. That does mean you end up with O(n) space though.</p>

<p>But wait, <code>StringBuffer</code> doesn't exist in JavaScript! Well, we can create a basic version of a <code>StringBuffer</code>. Check it:</p>

<pre><code>var compressedString = function(str) {  
  if (str.length &lt; 3) return str;

  var compressedStrArray = [];
  var index = 0;
  var char = str.charAt(0);
  var count = 1;

  for (var i = 1; i &lt; str.length; i++) {
    if (str[i] !== char) {
      index = setChar(compressedStrArray, index, char, count);
      char = str[i];
      count = 1;
    } else {
      count++;
    }
  }
  setChar(compressedStrArray, index, char, count);
  var compressedStr = compressedStrArray.join('');

  return compressedStr.length &gt;= str.length ? str : compressedStr;
};

var setChar = function(array, index, char, count) {  
  array[index++] = char;
  array[index++] = count;
  return index;
};
</code></pre>

<p>One optimization included is using the helper function, <code>setChar</code>, to append characters to the array representing the StringBuffer. The <code>Array.prototype.push</code> method could have been used to append new characters to the StringBuffer, but referencing an index is faster.</p>

<p>So is it still "safe" to use <code>+=</code> concatenation? Absolutely, but you need to consider the environment where your code is running. Recent browsers will have optimizations for <code>+=</code>. Also, if you are doing a one-time concatenation and not concatenating within a loop, feel free to use <code>+=</code>.</p>]]></content:encoded></item><item><title><![CDATA[Tree Traversal]]></title><description><![CDATA[<h2 id="bfsvsdfs">BFS vs. DFS</h2>

<p>When you need to search or traverse a graph or tree-like structure, there are two common algorithms: breadth-first search and depth-first search.</p>

<p><img src="http://kevhuang.com/content/images/2015/06/tree-traversal.gif" alt="Depth-first vs. breadth-first search"></p>

<p>Which algorithm to use really depends on the structure of the tree and the location of the items you need to find. Here are some</p>]]></description><link>http://kevhuang.com/tree-traversal/</link><guid isPermaLink="false">91f78d06-837c-4ec8-a24d-e1396f233e8d</guid><category><![CDATA[javascript]]></category><category><![CDATA[tutorial]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Tue, 23 Jun 2015 20:31:00 GMT</pubDate><content:encoded><![CDATA[<h2 id="bfsvsdfs">BFS vs. DFS</h2>

<p>When you need to search or traverse a graph or tree-like structure, there are two common algorithms: breadth-first search and depth-first search.</p>

<p><img src="http://kevhuang.com/content/images/2015/06/tree-traversal.gif" alt="Depth-first vs. breadth-first search"></p>

<p>Which algorithm to use really depends on the structure of the tree and the location of the items you need to find. Here are some quick guidelines (not steadfast rules) for determining which algorithm to use:</p>

<p>Breadth-first:</p>

<ul>
<li>The target is not far from the root</li>
<li>You are looking for the shortest path from the root</li>
<li>You have a lot of memory to work with</li>
</ul>

<p>Depth-first:</p>

<ul>
<li>The target is deep in the tree</li>
<li>You don't care for the shortest path from the root</li>
<li>The tree is very wide and you have limited memory</li>
</ul>

<h2 id="samplecode">Sample Code</h2>

<pre><code>var Tree = function(value) {  
  this.value = value;
  this.children = [];
};

// Assume we have helper functions to add and remove children
Tree.prototype.addChild = function(child) {/* Code to add child */};  
Tree.prototype.removeChild = function(child) {/* Code to remove child */};

// Breadth-first search
Tree.prototype.BFS = function(filter) {  
  var queue = [this]; // The queue of nodes to check, starting with the current node

  while (queue.length) {
    var node = queue.shift(); // Remove and examine first element in queue
    if (filter(node.value)) return node; // Found target node
    queue = queue.concat(node.children); // Node is not target, add its children to the queue
  }

  return null; // No result found
};

// Depth-first search
Tree.prototype.DFS = function(filter) {  
  if (filter(this.value)) return this; // Found target node

  for (var i = 0; i &lt; this.children.length; i++) {
    var search = this.children[i].DFS(filter); // Recurse down the tree
    if (search) return search;
  }

  return null; // No result found
};
</code></pre>

<p>Now let's say our tree contains nodes that hold a number, and we want to find the first node with a value divisible by 5. Here is how we can set up that tree and use BFS and DFS to find the target node:</p>

<pre><code>var root = new Tree(1);  
var branch1 = root.addChild(2);  
var branch2 = root.addChild(3);  
var branch3 = branch1.addChild(4);  
var branch4 = branch1.addChild(5);  
var leaf1 = branch2.addChild(6);  
var leaf2 = branch2.addChild(7);  
var leaf3 = branch3.addChild(8);  
var leaf4 = branch3.addChild(9);  
var leaf5 = branch4.addChild(10);

var filter = function(value) {  
  return value % 5 === 0;
};

var node = root.BFS(filter); // Returns the node with value 5  
var node = root.DFS(filter); // Returns the node with value 5  
</code></pre>

<p>When trying to find the first node divisible by 5 using BFS, this is the order of which the nodes are examined: <code>1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5</code>. And when using DFS: <code>1 -&gt; 2 -&gt; 4 -&gt; 8 -&gt; 9 -&gt; 5</code>.</p>]]></content:encoded></item><item><title><![CDATA[Preview of ES6]]></title><description><![CDATA[<p>Who's excited for ES6? Hold on to your socks. Here is a sneak peek of what's to come in ECMAScript 6.</p>

<h4 id="letandconst"><code>let</code> and <code>const</code></h4>

<p><code>let</code> can be used to declare variables just like <code>var</code>, but <code>let</code> has no hoisting, it has lexical scoping within <code>()</code> and <code>{}</code> blocks, and you cannot redeclare</p>]]></description><link>http://kevhuang.com/preview-of-es6/</link><guid isPermaLink="false">606464e3-614f-44f9-a857-ca2a6f863782</guid><category><![CDATA[javascript]]></category><category><![CDATA[es6]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Mon, 25 May 2015 01:49:00 GMT</pubDate><content:encoded><![CDATA[<p>Who's excited for ES6? Hold on to your socks. Here is a sneak peek of what's to come in ECMAScript 6.</p>

<h4 id="letandconst"><code>let</code> and <code>const</code></h4>

<p><code>let</code> can be used to declare variables just like <code>var</code>, but <code>let</code> has no hoisting, it has lexical scoping within <code>()</code> and <code>{}</code> blocks, and you cannot redeclare a variable that was declared with <code>let</code>.</p>

<pre><code>for (let i = 0; i &lt; 3; i++) {  
  console.log(i); // logs 0, 1, and 2
}
console.log(i); // throws an error  
</code></pre>

<p><code>const</code> is like <code>let</code>, but you cannot reassign a value.</p>

<pre><code>const pi = 3.14;  
pi = 3; // throws an error  
</code></pre>

<h4 id="arrowfunctions">Arrow Functions</h4>

<p>This is very much like CoffeeScript, except there is only fat arrow (<code>=&gt;</code>), and no regular arrow (<code>-&gt;</code>).</p>

<pre><code>// ES6 way
let fn = (a, b, c) =&gt; {  
  console.log(a, b, c);
  return true;
};

fn(1, 2, 3); // logs "1 2 3" and returns true

// ES5 way
var fn = function(a, b, c) {  
  console.log(a, b, c);
  return true;
};
</code></pre>

<p>And just like CoffeeScript, the fat arrow will automatically bind the function to the current value of <code>this</code> during declaration.</p>

<pre><code>// ES6 way
let Human = (age) =&gt; {  
  this.age = age || 0;
  setInterval(() =&gt; {
    this.age++; // `this` will properly refer to the Human object
  }, 1000);
};

// ES5 way
var Human = function(age) {  
  var self = this;
  self.age = age || 0;
  setInterval(function() {
    self.age++;
  }, 1000);
};
</code></pre>

<p>Another thing to point out is that if the function body is just one line, there will be an implicit return. The two functions below do the same thing.</p>

<pre><code>let add10 = (x) =&gt; x + 10;

let addTen = (x) =&gt; {  
  return x + 10;
};
</code></pre>

<h4 id="classes">Classes</h4>

<p>Classes are how you can implement inheritance in ES6. Unlike function declarations, class declarations are not hoisted, so a class must be declared before attempting to access it.</p>

<pre><code>class Human {  
  constructor(name, diet) {
    this.name = name;
    this.diet = diet;
  }
  report() {
    return this.name;
  }
}

class Omnivore extends Human {  
  constructor(name) {
    super(name, "omnivore");
  }
  report() {
    return super.report() + ": I eat everything!";
  }
}

class Vegetarian extends Human {  
  constructor(name) {
    super(name, "vegetarian");
  }
  report() {
    return super.report() + ": I don't eat meat";
  }
}

let meatLover = new Omnivore("Mary");  
console.log(meatLover.report()); // logs "Mary: I eat everything!"  
let meatHater = new Vegetarian("Ellen");  
console.log(meatHater.report()); // logs "Ellen: I don't eat meat"  
</code></pre>

<p>Also notice how the <code>report</code> method doesn't need a <code>let</code> or <code>var</code> in front of it. It's automatically recognized as a method.</p>

<h4 id="templatestrings">Template Strings</h4>

<p>Use backticks instead of single or double quotes to embed expressions within strings and create string interpolation.</p>

<pre><code>var a = 1;  
var b = 2;  
console.log(`${a} + ${b} = ${a + b}`); // logs "1 + 2 = 3"  
</code></pre>

<h4 id="spreadoperator">Spread Operator</h4>

<p>If you want an easy way to expand an expression in function calls or array literals, use the spread operator, <code>...</code>.</p>

<pre><code>let nums1 = [1,2,3];  
let nums2 = [4,5,6];  
console.log(...nums1) // logs "1 2 3"  
let nums = [...nums1, ...nums2];  
console.log(nums); // logs "1,2,3,4,5,6"

var print = (a, b, c, d, e) =&gt; {  
  console.log(a, b, c, d, e);
};
var args = [2, 3];  
print(1, ...args, 4, ...[5]); // logs "1 2 3 4 5"  
</code></pre>

<h4 id="restparameters">Rest Parameters</h4>

<p>Prefixing the last named argument of a function with <code>...</code> will allow you to represent an indefinite number of arguments as an array.</p>

<p>There are some differences between rest parameters and the <code>arguments</code> object.</p>

<ul>
<li>Rest parameters are only the ones not given a separate name, while the <code>arguments</code> object contains all arguments passed to the function</li>
<li>The <code>arguments</code> object is not a real array, while rest parameters are Array instances, so you can use native Array methods on it</li>
<li>The <code>arguments</code> object has additional functionality specific to itself (like the <code>callee</code> property)</li>
</ul>

<pre><code>let logNums = (first, second, third, ...others) =&gt; {  
  console.log(first, second, third, others) // logs "1 2 3 4,5,6,7,8"
  console.log(others) // logs "4,5,6,7,8"
  console.log(others.map(function(num) {
    return num * 2;
  })); // logs "8,10,12,14,16"
};
logNums(1,2,3,4,5,6,7,8);  
</code></pre>

<h4 id="defaultparameters">Default Parameters</h4>

<p>Now you can define default values to use for function parameters if no value or <code>undefined</code> is passed. By default, if no value is passed, JavaScript will set the parameter value to <code>undefined</code>, but you can now use your own default value.</p>

<pre><code>let multiply = (x, y = 1) =&gt; x * y;  
console.log(multiply(4)); // logs "4"  
</code></pre>

<h4 id="nottheend">Not the End</h4>

<p>This is just a taste of what's to come in ES6. There are many more features I didn't mention. It's going to be interesting seeing how companies and the community go about adopting ES6. Are your socks still on?</p>]]></content:encoded></item><item><title><![CDATA[Locally Test Pull Requests]]></title><description><![CDATA[<p>In this post, I am going to cover how to easily test pull requests on your local machine. When you work in a team where people are submitting pull requests, you want to make sure their changes are free of bugs and do not break any existing code in the</p>]]></description><link>http://kevhuang.com/locally-test-pull-requests/</link><guid isPermaLink="false">3fda4728-ac07-4c34-a960-a78ca5b908ab</guid><category><![CDATA[tutorial]]></category><category><![CDATA[git]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Sat, 16 May 2015 20:40:00 GMT</pubDate><content:encoded><![CDATA[<p>In this post, I am going to cover how to easily test pull requests on your local machine. When you work in a team where people are submitting pull requests, you want to make sure their changes are free of bugs and do not break any existing code in the <code>master</code> branch before the pull requests are merged. If you've been manually copying and pasting new code from pull requests into your local environment to test, then you really need to read this post. You want to test all code changes, and you don't want to have to copy and paste if there are a lot of files that changed.</p>

<p>This post is written in the context of using a GitHub workflow.</p>

<h3 id="prerequisites">Prerequisites</h3>

<p>I'm also going to assume you have <code>upstream</code> and <code>origin</code> remotes set up in your local repository. <code>upstream</code> should point to the main repo that is shared by the team and <code>origin</code> should point to your personal (forked) repo. If you are not familiar with this concept, check out this <a href="https://help.github.com/articles/fork-a-repo/">tutorial</a>.</p>

<h3 id="letsgetstarted">Let's get started</h3>

<p>Let's say this is the most recent tip of the current <code>master</code> in <code>upstream</code> as well as on your local machine:</p>

<pre><code>*   d4138b6 2015-05-15 | Merge pull request #8 from aapple/feat/resize-method (HEAD, upstream/master, origin/master) [Billy Banana]
|\  
| * 7e31ce9 2015-05-15 | Add resize method [Adam Apple]
|/
*   9a24fe0 2015-05-13 | Merge pull request #7 from bbanana/feat/insert-method [Cathy Cherry]
</code></pre>

<p>And let's say Denise Date is working on a new feature and has submitted a pull request. Denise followed best practice and did her work in a feature branch on her local machine and then pushed to her GitHub forked repo. Her feature branch is called <code>feat/remove-method</code>.</p>

<p>So now, we want to pull down her changes and do a code review and make sure everything is fine with the new changes. From your local machine, you want to do the following:</p>

<ul>
<li>Create a remote for Denise's repo if it doesn't already exist with <code>git remote add denise &lt;REPO URL&gt;</code></li>
<li>Make sure you are on master by using <code>git checkout master</code></li>
<li>Create a branch for testing Denise's new code by using <code>git checkout -b feat/remove-method</code></li>
<li>Pull down Denise's code into the branch with <code>git pull --rebase denise feat/remove-method</code></li>
<li>Test test test</li>
</ul>

<p>For the <code>git pull</code> into the feature branch, you don't technically need the <code>--rebase</code>, but it's good to use to have a cleaner commit history since it will not create a merge commit. Denise's code should now be combined with the existing codebase.</p>

<p>Now from the <code>feat/remove-method</code> branch in your local repo, the commit history will look something like this:</p>

<pre><code>* cafd1a5 2015-05-14 | Add remove method (HEAD, denise/feat/remove-method, feat/remove-method) [Denise Date]
*   d4138b6 2015-05-13 | Merge pull request #8 from aapple/feat/resize-method (HEAD, upstream/master, origin/master, master) [Billy Banana]
|\  
| * 7e31ce9 2015-05-12 | Add resize method [Adam Apple]
|/
*   9a24fe0 2015-05-11 | Merge pull request #7 from bbanana/feat/insert-method [Cathy Cherry]
</code></pre>

<p>After reviewing her code and making sure everything works, when the pull request is merged into <code>upstream/master</code>, you should also make sure your local and fork <code>master</code> branch are synchronized with <code>upstream</code>.</p>]]></content:encoded></item><item><title><![CDATA[Cleaning Up Your Git Commit History]]></title><description><![CDATA[<p>Before you submit a pull request to the upstream repository for changes you made in your Git repository, you should think about cleaning up your commit history. Ideally, when your code is merged with the master branch of the target repository, the commit history of that master branch should be</p>]]></description><link>http://kevhuang.com/cleaning-up-your-git-commit-history/</link><guid isPermaLink="false">ba44cf8e-3d18-47b8-8a67-68be863ffa30</guid><category><![CDATA[tutorial]]></category><category><![CDATA[git]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Fri, 01 May 2015 21:26:00 GMT</pubDate><content:encoded><![CDATA[<p>Before you submit a pull request to the upstream repository for changes you made in your Git repository, you should think about cleaning up your commit history. Ideally, when your code is merged with the master branch of the target repository, the commit history of that master branch should be succinct and easy-to-follow, and it should reflect a clean progression of code changes.</p>

<p>Leave small insignificant commits out of the final commit history. In other words, the master commit history should not contain commit messages like, "Test a new function" or "Begin work on X." These kinds of messages pollute the commit history and makes it difficult to find where a major change started and ended. If there were many small commits that led to a significant change, there should be one commit that encompasses all those small commits.</p>

<p>So how do we go about cleaning up the commit history before merging with master? We can use <code>git rebase -i</code>. You can use this command to do a variety of tasks like reordering commits, deleting commits, updating commit messages, combining commits, and more. This post will focus on combining commits, or squashing them.</p>

<p>Assume we have the following commit history (shown with the latest commit first) and we want to combine the last 3 commits:</p>

<pre><code>408xcad Return result  
48copd7 Calculate square root  
8cj3x7z Check input type  
pl707da Add functionality for calculating the square of a number  
</code></pre>

<p>We will type the following in the shell: <br>
<code>git rebase -i HEAD~3</code></p>

<p>This will bring up your default text editor and will show the following:</p>

<pre><code>pick 8cj3x7z Check input type  
pick 48copd7 Calculate square root  
pick 408xcad Return result

# Rebase pl707da..408xcad onto pl707da
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
</code></pre>

<p>The oldest commit will be at the very top. Since we want to combine these three commits into one, we will update the lines like so in the text editor:</p>

<pre><code>pick 8cj3x7z Check input type  
squash 48copd7 Calculate square root  
squash 408xcad Return result

# Rebase pl707da..408xcad onto pl707da
</code></pre>

<p>Save and close the editor. Git will then automatically launch the editor again, and this time, you can specify the commit message of the combined snapshot. The initial prompt will be something like this:</p>

<pre><code># This is a combination of 3 commits.
# The first commit's message is:
Check input type

# This is the 2nd commit message:

Calculate square root

# This is the 3rd commit message:

Return result  
</code></pre>

<p>Since we are squashing the 2nd and 3rd commits into the 1st commit, we'll update the commit message of the first message like so:</p>

<pre><code># The first commit's message is:
Add functionality for calculating the square root of a number  
</code></pre>

<p>Now save and close the editor. Then check out your commit history using <code>git log</code> and you should see the following:</p>

<pre><code>6c8a3ll Add functionality for calculating the square root of a number  
pl707da Add functionality for calculating the square of a number  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Let's Consider the OPTIONS]]></title><description><![CDATA[<p><img src="http://kevhuang.com/content/images/2016/07/dev-thinking.jpeg" alt=""></p>

<p>Have you ever noticed a HTTP OPTIONS request being sent from your browser to a server, but never knew what it meant? Here's how it looks like in Chrome Developer Tools:</p>

<p><img src="http://kevhuang.com/content/images/2015/04/options-request-network-panel.png" alt="HTTP OPTIONS request in Network panel of Chrome Developer Tools"></p>

<p>This is your browser attempting a cross-site HTTP request. Per <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">MDN</a>:</p>

<blockquote>
  <p>Cross-site HTTP requests are HTTP requests for resources</p></blockquote>]]></description><link>http://kevhuang.com/lets-consider-the-options/</link><guid isPermaLink="false">db4a00e6-b33a-4b52-a5ed-bc9dc9693bff</guid><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Wed, 22 Apr 2015 20:04:00 GMT</pubDate><content:encoded><![CDATA[<p><img src="http://kevhuang.com/content/images/2016/07/dev-thinking.jpeg" alt=""></p>

<p>Have you ever noticed a HTTP OPTIONS request being sent from your browser to a server, but never knew what it meant? Here's how it looks like in Chrome Developer Tools:</p>

<p><img src="http://kevhuang.com/content/images/2015/04/options-request-network-panel.png" alt="HTTP OPTIONS request in Network panel of Chrome Developer Tools"></p>

<p>This is your browser attempting a cross-site HTTP request. Per <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">MDN</a>:</p>

<blockquote>
  <p>Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request.</p>
</blockquote>

<p>It is common for pages to load resources from different hosts. These resources typically include CSS stylesheets, scripts, images, etc. However, if a script is able to load resources from or create resources on another host, that could be problematic in terms of security. As such, browsers implement a same-origin policy whereby a script on one resource/page can access data from another resource/page, as long as the resources have the same origin/host. Having scripts retrieve and send data without having to leave a page is extremely useful. This is where AJAX comes into play. However, the same-origin policy is still an obstacle.</p>

<p>One way to work around the same-origin policy with AJAX is by using a technique called <a href="http://www.w3.org/TR/cors/">CORS</a> (Cross-Origin Resource Sharing). This standard makes it so that browsers have to "preflight" a HTTP request with an OPTIONS request header. The OPTIONS request is sent to the target server, and the server (if configured properly) can respond to the OPTIONS request informing the client whether it is approved to access the resource. Think of it as requiring the client to ask for permission from the server before the client can send across the XMLHttpRequest. But this standard isn't implemented in all browsers. The older versions of browsers do not support it.</p>

<p>Let's walk through an example. We have a messaging client on h<span></span>ttps://chat.com where users can post messages for other users to see. The messages are stored in a database, and served from h<span></span>ttps://messages.chat.com, which is a different host than chat.com (yes, a different subdomain still makes it under a different host). When a user fills out the form to submit a message from chat.com, the browser needs to make a POST request to messages.chat.com using AJAX, and the server will then store that message in the database. The API for posting messages states that the request must be sent to h<span></span>ttps://messages.chat.com/messages.</p>

<p>But because the client and server are on different hosts and the same-origin policy is in place, CORS can be used to successfully communicate with the server. Here are the steps to make this all happen:</p>

<p><img src="http://kevhuang.com/content/images/2015/04/cors-timeline.png" alt="Timeline of a cross-origin POST request"></p>

<p>After the application initiates the POST request, the browser will submit a HTTP OPTIONS request to the server before actually sending the POST request. This is the preflight request, and it will look something like this:</p>

<pre><code>OPTIONS /messages/ HTTP/1.1  
Host: messages.chat.com  
Accept: */*  
Access-Control-Request-Method: POST  
Access-Control-Request-Headers: accept, content-type  
Origin: https://chat.com  
</code></pre>

<p>The Access-Control-Request-Method header informs the server that when the actual request is sent, it will be in the form of a POST. The Access-Control-Request-Headers header lets the server know what other headers will be included in the actual request. Finally, the Origin header indicates the server/host that made the request. In this example, let's say the server is configured to respond to OPTIONS request, and allows any host to make GET, PUT, POST, and DELETE requests. So, the server will respond back with something like this:</p>

<pre><code>HTTP/1.1 200 OK  
Access-Control-Allow-Origin: *  
Access-Control-Allow-Methods: GET,PUT,POST,DELETE  
Access-Control-Allow-Headers: Content-Type, Accept  
</code></pre>

<p>The Access-Control-Allow-Origin header indicates that all hosts are allowed, the Access-Control-Allow-Methods header indicates the HTTP methods that are allowed, and the Access-Control-Allow-Headers header tells the client what other headers can be included in the POST request.</p>

<p>After the preflight OPTIONS request is acknowledged and approved by the server and sent back to the client, the client can then proceed with submitting the actual POST request.</p>

<p>And that's how CORS works. Remember, the server has to be configured to properly respond to OPTIONS requests if it wants to allow other hosts to access resources. More details about the standard, headers, and compatible browsers can be found on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">MDN</a>.</p>]]></content:encoded></item><item><title><![CDATA[Subclasses and Inheritance in JavaScript]]></title><description><![CDATA[This is the correct way to use inheritance to create subclasses in JavaScript.]]></description><link>http://kevhuang.com/subclasses-and-inheritance-in-javascript/</link><guid isPermaLink="false">91f5aa33-e3aa-4eee-a151-15e86f6b6f05</guid><category><![CDATA[javascript]]></category><category><![CDATA[tutorial]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Sun, 05 Apr 2015 09:59:03 GMT</pubDate><content:encoded><![CDATA[<p>A class is a blueprint for something you want to model. You can use a class to create many similar objects. In JavaScript, a class is simply a function (or a constructor) that creates objects where each object created from the constructor function will have the same properties. Additional properties can be added to each object as well. I will be using the following class for the first couple of examples.</p>

<p>In addition, all examples are written using the pseudoclassical instantiation pattern.</p>

<pre><code>var SuperClass = function() {  
  this.prop1 = 50;
};
SuperClass.prototype.superMethod = function() {  
  console.log('This is a super method.');
};
</code></pre>

<p>A subclass is a class that inherits all the properties of another class, and at the same time, the subclass can add or modify  properties. Therefore, a property can be defined in the parent class and shared with the subclass without having to define that property over again in the subclass. Any failed lookups of properties on the subclass will delegate up the prototype chain of parent classes. This is done by setting the subclass's <code>prototype</code> to point to the prototype chain of its parent.</p>

<p>Before we look at the correct way to create subclasses, let's look at the <strong><em>wrong</em></strong> ways first. </p>

<pre><code>var SubClass = function() {  
  this.prop2 = 100;
};
SubClass.prototype = SuperClass.prototype;  
SubClass.prototype.superMethod = function() {  
  console.log('This is a sub method.');
};

var superObj = new SuperClass();  
superObj.superMethod(); // logs 'This is a sub method.'  
var subObj = new SubClass();  
subObj.superMethod(); // logs 'This is a sub method.'  
</code></pre>

<p>In the above example, <code>SubClass</code>'s prototype is being assigned to the same object as <code>SuperClass</code>'s prototype. If a property is then defined on <code>SubClass.prototype</code> with the same name as a property in <code>SuperClass</code>—<code>superMethod</code> in the example—then it will override that property in <code>SuperClass</code>, and it would affect all instances of <code>SuperClass</code>. Again, this is an example of how not to create subclasses.</p>

<p>Another common mistake that is still being used is the following:</p>

<pre><code>var SubClass = function() {  
  this.prop2 = 100;
};
SubClass.prototype = new SuperClass();  
</code></pre>

<p>Sure, this works. Calling <code>new SuperClass()</code> will create a new object that delegates to <code>SuperClass.prototype</code>. However, using this pattern is not best practice, and there will be times where this will not work. For example, what if we slightly change  <code>SuperClass</code> to take in an argument and use it during instantiation?</p>

<pre><code>var SuperClass = function(value) {  
  this.prop1 = value * 2;
};
var SubClass = function() {  
  this.prop2 = 100;
};
SubClass.prototype = new SuperClass();  
var subObj = new SubClass();  
console.log(subObj.prop1); // logs NaN  
</code></pre>

<p>Notice that when calling <code>subObj.prop1</code>, it didn't return a number. This breaks our expectation on having a number for the property and may even break functionality in the application.</p>

<p>Even if <code>SuperClass</code> doesn't make use of any arguments, it is still a bad practice to set the prototype as a new instance of the parent class because doing so would create exactly that, a new instance of the parent class. Why create another object when you're not going to interact with it?</p>

<p>So here is the correct way to create subclasses as of ES5.1 (ECMA-262):</p>

<pre><code>var SuperClass = function(value) {  
  this.prop1 = value * 2;
};
SuperClass.prototype.superMethod = function() {  
  console.log('This is a super method.');
};
var SubClass = function(value) {  
  SuperClass.call(this, value);
  this.prop2 = 100;
};
SubClass.prototype = Object.create(SuperClass.prototype);  
SubClass.prototype.constructor = SubClass;  
SubClass.prototype.superMethod = function() {  
  console.log('This is a super method on sub.');
};
SubClass.prototype.subMethod = function() {  
  console.log('This is a sub method.');
};

var superObj = new SuperClass(25);  
var subObj = new SubClass(30);  
console.log(superObj.prop1); // logs 50  
superObj.superMethod(); // logs 'This is a super method.'  
console.log(subObj.prop1); // logs 60  
console.log(subObj.prop2); // logs 100  
subObj.superMethod(); // logs 'This is a super method on sub.'  
subObj.subMethod(); // logs 'This is a sub method.'  
</code></pre>

<p>Key takeaways about this approach:</p>

<ol>
<li>When instantiating a new instance of <code>SubClass</code>, it is not going to instantiate a new instance of <code>SuperClass</code>  </li>
<li><code>subObj.prop1</code> evaluates correctly because when <code>SubClass</code> creates a new instance, it is invoking the <code>SuperClass</code> function with <code>call()</code> and passing in <code>value</code>  </li>
<li><code>superMethod</code> on <code>SubClass</code> does not override <code>superMethod</code> on <code>SuperClass</code>  </li>
<li>A new instance of <code>SuperClass</code> is not created when setting <code>SubClass.prototype</code> but <code>SuperClass</code>'s prototype chain is still passed to <code>SubClass</code>'s prototype  </li>
<li><code>SubClass.prototype.constructor</code> is set to refer to the <code>SubClass</code> constructor function because otherwise, it would use the same constructor function as <code>SuperClass</code> since that's the constructor in <code>SuperClass.prototype</code> (remember, failed lookups on the subclass will delegate up the prototype chain)</li>
</ol>

<p>That's it. Look out for ES6. It introduces the <code>class</code> keyword for creating classes.</p>]]></content:encoded></item><item><title><![CDATA[Understanding the Keyword "this"]]></title><description><![CDATA[Learn how to identify what "this" refers to at any time in JavaScript.]]></description><link>http://kevhuang.com/understanding-the-keyword-this/</link><guid isPermaLink="false">d48c1968-bb06-4b86-a442-31f49064f042</guid><category><![CDATA[javascript]]></category><category><![CDATA[tutorial]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Mon, 30 Mar 2015 14:47:51 GMT</pubDate><content:encoded><![CDATA[<p>I have always struggled to correctly use the keyword, <code>this</code>, in JavaScript. This is especially the case when functions are invoked from the context of other functions. At a high level, think of <code>this</code> being a variable that simply refers to an object. When <code>this</code> is bound to an object, you can use <code>this</code> to set or look up properties and invoke methods on such object.</p>

<h2 id="bindingpatternsforthis">Binding Patterns for <code>this</code></h2>

<p><code>this</code> can only be bound by one of five patterns, and more importantly, <code>this</code> is bound to an object at <strong>call time</strong>. So how do you determine which pattern was used during call time?</p>

<ol>
<li>Run the code in the debugger and pause at the line that refers to <code>this</code>  </li>
<li>Scan outward looking for the closest enclosing function body  </li>
<li>Once you find the function <code>this</code> appears in, examine the call stack and look one level down to where this function was called  </li>
<li>Identify the syntax of <strong>how</strong> the function was called to determine the run pattern</li>
</ol>

<p>Let's take a look at each pattern.</p>

<table>  
  <thead>
    <tr>
      <th>Run Pattern</th>
      <th>Example</th>
      <th>Binding Target</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Global reference</td>
      <td><code>this</code> (not enclosed in any function)</td>
      <td>Global object (in a browser, it is <code>window</code>)</td>
      <td>Not useful, but JavaScript has to bind it to something to be consistent</td>
    </tr>
    <tr>
      <td>Free function invocation</td>
      <td><code>functionName()</code></td>
      <td>Global object (in a browser, it is <code>window</code>)</td>
      <td>Not useful, but JavaScript had to bind it to something to be consistent with the other patterns</td>
    </tr>
    <tr>
      <td>ABC (.apply, .bind, .call)</td>
      <td><code>fn.call(target)</code> or <code>obj.methodName(target)</code></td>
      <td>The first argument to .apply, .bid, or .call</td>
      <td>To manually pass in a <code>this</code> binding, like passing in arguments when invoking a function or method</td>
    </tr>
    <tr>
      <td>Method invocation</td>
      <td><code>target.methodName()</code></td>
      <td>Object on the left of the call time dot</td>
      <td>Execute the method in the context of an object they're found on</td>
    </tr>
    <tr>
      <td>Construction mode</td>
      <td><code>new functionName()</code></td>
      <td>A new object created for that invocation</td>
      <td>Allow a constructor to operate on the instance it is creating</td>
    </tr>
  </tbody>
</table>

<p><mark>Tip:</mark></p>

<blockquote>
  <p><em>Most of the time</em>, when inside a function, <code>this</code> will be bound to the object that was to the left of the call time dot.</p>
</blockquote>

<h3 id="globalreference">Global Reference</h3>

<pre><code>console.log(this); // logs window from the browser  
</code></pre>

<p>Consider the above code that runs in the global scope. It is not enclosed in a function. Since <code>this</code> is automatically bound while inside a function body, JavaScript wanted to be consistent in having <code>this</code> be bound to something, so when outside a function body, <code>this</code> will be bound to the global context, which in the case of a browser, is <code>window</code>.</p>

<h3 id="freefunctioninvocation">Free Function Invocation</h3>

<pre><code>var fn = function() {  
  console.log(this);
};

fn(); // logs window from the browser  
</code></pre>

<p><code>fn</code> is being invoked in the global context. Like before, <code>this</code> will be bound to the global context because that is the context during run time when <code>fn</code> is invoked.</p>

<h3 id="abcapplybindcall">ABC (.apply, .bind, .call)</h3>

<pre><code>var fn = function() {  
  console.log(this);
};

var obj1 = {};  
var obj2 = {};

fn.apply(obj); // logs obj1

fn2 = fn.bind();  
fn2(); // logs obj2

fn.call(obj); // logs obj1  
</code></pre>

<p>In this scenario, when using the native <code>apply</code>, <code>bind</code>, and <code>call</code> Function methods, you can manually pass in an object, and <code>this</code> will be bound to that object. This allows you to predictively make use of <code>this</code>.</p>

<h3 id="methodinvocation">Method Invocation</h3>

<pre><code>var fn = function() {  
  console.log(this);
};

var obj1 = {mtd: fn};  
var obj2 = {mtd: obj1.mtd};  
obj1.mtd(); // logs obj1  
obj2.mtd(); // logs obj1  
</code></pre>

<p>Since <code>fn</code> is being invoked as a method whatever object is on the left of the call time dot will be bound to <code>this</code>. With <code>obj2.mtd</code>, it refers to <code>obj1</code>'s <code>mtd</code> method, and invoking <code>obj.mtd()</code> would actually invoke <code>fn</code> as a method of <code>obj1</code> since <code>obj1</code> is to the left of the call time dot.</p>

<p>The phrase, call time dot, is important. Consider the following:</p>

<pre><code>var obj1 = {mtd: fn};

obj1.mtd(); // logs obj1  
window.setTimeout(obj1.mtd, 1000); // logs window from the browser

/*
window.setTimeout() can be imagined like this:  
var setTimeout = function(callback, delay) {  
  wait(delay); // some logic to wait a certain amount of time
  callback();
};
*/
</code></pre>

<p>With <code>setTimeout()</code>, it takes in a function and delay (in milliseconds), and it invokes the function <em>after</em> the delay. In this case, since <code>fn</code> (the callback function that is passed as the first argument into <code>setTimeout()</code>) is invoked as a free function invocation, <code>this</code> is bound to the global context, <code>window</code>.</p>

<h3 id="constructionmode">Construction Mode</h3>

<pre><code>var fn = function() {  
  console.log(this);
};

var obj = {mtd: fn};

obj.mtd(); // logs obj  
var obj1 = new fn(); // logs a new object  
var obj2 = new obj.mtd(); // logs a new object  
</code></pre>

<p>A function invoked with the <code>new</code> keyword means the function is considered a constructor function. This expression will create a new object that is an instance of the constructor function, and the function will execute in the context of that newly-created object.</p>

<p>In addition, the <code>new</code> keyword will override the method invocation pattern. In the example, <code>new obj.mtd()</code> would not bind <code>this</code> to <code>obj</code> even though <code>obj</code> is to the left of the call time dot. Instead, <code>this</code> is bound to the newly-created object from the constructor function.</p>

<h2 id="summary">Summary</h2>

<p>I hope this helped gives clarity on how <code>this</code> is bound. Remember, <em>most of the time</em>, when inside a function, <code>this</code> will be bound to the object that was to the left of the call time dot.</p>]]></content:encoded></item><item><title><![CDATA[Blackboxing Library Code in Chrome DevTools]]></title><description><![CDATA[A quick guide on how to bypass library files when debugging in Chrome DevTools.]]></description><link>http://kevhuang.com/blackboxing-library-code-in-chrome-devtools/</link><guid isPermaLink="false">d03cee47-4d6c-4d59-a3dd-fb6c32efef00</guid><category><![CDATA[tips]]></category><category><![CDATA[chrome]]></category><category><![CDATA[devtools]]></category><category><![CDATA[tutorial]]></category><dc:creator><![CDATA[Kevin Huang]]></dc:creator><pubDate>Thu, 26 Mar 2015 14:34:37 GMT</pubDate><content:encoded><![CDATA[<p><img src="http://kevhuang.com/content/images/2016/07/blackbox.jpg" alt=""></p>

<p>One of the many useful features of Chrome Developer Tools (DevTools) is the blackbox preference. Normally when debugging code, if you step through code that references external source files (e.g., jQuery, Underscore.js, etc.), the debugger will step through that library code. Sometimes this may be good if you want to debug the library code, but most of the time, you trust the library code should be stable and you just want to focus on your code.</p>

<p>With the blackbox preference, DevTools can ignore or bypass any source files you choose during debugging. This means the debugger won't go into blackboxed files when stepping through code, and breakpoints in blackboxed files, if any, will also be ignored (i.e., the debugger will not pause at such breakpoints). This will save you time and minimize confusion in times where library code could generate a deep call stack.</p>

<h3 id="howtoblackbox">How to blackbox</h3>

<ol>
<li>In DevTools, navigate to the Sources panel  </li>
<li><p>Right click the source file you want to blacklist in the navigator pane and select Blackbox Script</p>

<p><img src="http://kevhuang.com/content/images/2015/03/blackbox1.png" alt="Using the context menu to blackbox a script" title=""></p></li>
</ol>

<h4 id="manageblackboxedscripts">Manage blackboxed scripts</h4>

<p>If you ever want to add, modify, or remove blackboxes, you can do so by going into the Settings.</p>

<ol>
<li>In DevTools, navigate to the Settings panel  </li>
<li><p>Under the Sources section, click <strong>Manage framework blackboxing</strong></p>

<p><img src="http://kevhuang.com/content/images/2015/03/blackbox2.png" alt="Settings Panel" title=""></p></li>
<li><p>In the pop-up dialog, modify blackbox scripts as you wish</p>

<p><img src="http://kevhuang.com/content/images/2015/03/blackbox3.png" alt="Manage framework blackboxing dialog" title=""></p></li>
</ol>

<p>FYI, the URI pattern can accept the following values:</p>

<ul>
<li>The file name, e.g., <code>jquery.js</code> would match any files with "jquery.js" in its name</li>
<li>A regular expression, e.g., <code>\.min\.js$</code> would match any files ending in "min.js"</li>
<li>A reference to an entire folder, e.g., <code>bower_components</code> would match all files within the "bower_components" folder</li>
</ul>

<p>You can read more information about blackboxing from the <a href="https://developer.chrome.com/devtools/docs/blackboxing">Chrome Documentation</a>.</p>]]></content:encoded></item></channel></rss>