<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ bitwise - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ bitwise - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 10:08:14 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/bitwise/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create Your Very Own Chip-8 Emulator ]]>
                </title>
                <description>
                    <![CDATA[ By Eric Grandt Before diving into this article, I'd like to provide a quick introduction to what emulators are. In the simplest terms, an emulator is software that allows for one system to behave like another system.  A very popular use for emulators... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/creating-your-very-own-chip-8-emulator/</link>
                <guid isPermaLink="false">66d45e3d264384a65d5a950c</guid>
                
                    <category>
                        <![CDATA[ bitwise ]]>
                    </category>
                
                    <category>
                        <![CDATA[ emulator  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 May 2020 23:55:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/chip8thumbnail-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Eric Grandt</p>
<p>Before diving into this article, I'd like to provide a quick introduction to what emulators are. In the simplest terms, an emulator is software that allows for one system to behave like another system. </p>
<p>A very popular use for emulators nowadays is to emulate old video game systems such as the Nintendo 64, Gamecube, and so forth. </p>
<p>For example, with a Nintendo 64 emulator we can run Nintendo 64 games directly on a Windows 10 computer, without needing the actual console. In our case, we are emulating Chip-8 on our host system through the use of the emulator we'll be creating in this article.</p>
<p>One of the simplest ways to learn how to make your own emulators is to start with a Chip-8 emulator. With only 4KB of memory and 36 instructions, you can be up and running with your very own Chip-8 emulator in less than a day. You'll also gain the knowledge necessary to move on to bigger, more in-depth emulators.</p>
<p>This will be a very in-depth and long article in the hopes of making sense of everything. Having a basic understanding of hex, binary, and bitwise operations would be beneficial. </p>
<p>Each section is split by the file we're working in, and split again by the function we're working on to hopefully make it easier to follow. Once we're done with each file, I'll provide a link to the full code, with comments.</p>
<p>For this entire article, we'll be referencing the <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.2">Chip-8 technical reference</a> by Cowgod which explains every detail of Chip-8. </p>
<p>You can use whatever language you want to make the emulator, though this article will be using JavaScript. I feel it's the simplest language to use for first-time emulator creation considering it provides support for rendering, keyboard, and sound right out of the box. </p>
<p>The most important thing is that you understand the process of emulation, so use whatever language you are most comfortable with.</p>
<p>If you do decide to use JavaScript, you'll need to be running a local web server for testing. I use Python for this which allows you to start a web server in the current folder by running <code>python3 -m http.server</code>.</p>
<p>We're going to start by creating the <code>index.html</code> and <code>style.css</code> files, then move on to the renderer, keyboard, speaker, and finally the actual CPU. Our project structure will look like this:</p>
<pre><code>- roms
- scripts
    chip8.js
    cpu.js
    keyboard.js
    renderer.js
    speaker.js
index.html
style.css
</code></pre><h2 id="heading-index-and-styles">Index and Styles</h2>
<p>There's nothing crazy about these two files, they are very basic. The <code>index.html</code> file simply loads in the styles, creates a canvas element, and loads the <code>chip8.js</code> file.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">canvas</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">canvas</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"scripts/chip8.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The <code>style.css</code> file is even simpler, as the only thing being styled is the canvas to make it easier to spot.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">canvas</span> {
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid black;
}
</code></pre>
<p>You won't have to touch these two files again throughout this article, but feel free to style the page in whatever way you'd like.</p>
<h2 id="heading-rendererjs">renderer.js</h2>
<p>Our renderer will handle everything graphics related. It'll initialize our canvas element, toggle pixels within our display, and render those pixels on our canvas.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Renderer</span> </span>{

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Renderer;
</code></pre>
<h3 id="heading-constructorscale">constructor(scale)</h3>
<p>The first order of business is to construct our renderer. This constructor will take in a single argument, <code>scale</code>, which will allow us to scale the display up or down making pixels larger or smaller.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Renderer</span> </span>{
    <span class="hljs-keyword">constructor</span>(scale) {

    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Renderer;
</code></pre>
<p>We need to initialize a few things within this constructor. First, the display size, which for Chip-8 is 64x32 pixels.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">this</span>.cols = <span class="hljs-number">64</span>;
<span class="hljs-built_in">this</span>.rows = <span class="hljs-number">32</span>;
</code></pre>
<p>On a modern system, this is incredibly small and hard to see which is why we want to scale up the display to make it more user-friendly. Staying within our constructor, we want to set the scale, grab the canvas, get the context, and set the width and height of the canvas.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">this</span>.scale = scale;

<span class="hljs-built_in">this</span>.canvas = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'canvas'</span>);
<span class="hljs-built_in">this</span>.ctx = <span class="hljs-built_in">this</span>.canvas.getContext(<span class="hljs-string">'2d'</span>);

<span class="hljs-built_in">this</span>.canvas.width = <span class="hljs-built_in">this</span>.cols * <span class="hljs-built_in">this</span>.scale;
<span class="hljs-built_in">this</span>.canvas.height = <span class="hljs-built_in">this</span>.rows * <span class="hljs-built_in">this</span>.scale;
</code></pre>
<p>As you can see, we are using the <code>scale</code> variable to increase the width and height of our canvas. We'll be using <code>scale</code> again when we start rendering the pixels on the screen.</p>
<p>The last item we need to add to our constructor is an array that'll act as our display. Since a Chip-8 display is 64x32 pixels, the size of our array is simply 64 <em> 32 (cols </em> rows), or 2048. Basically, we're representing every pixel, on (1) or off (0), on a Chip-8 display with this array.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">this</span>.display = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-built_in">this</span>.cols * <span class="hljs-built_in">this</span>.rows);
</code></pre>
<p>This will later be used to render pixels within our canvas in the correct places.</p>
<h3 id="heading-setpixelx-y">setPixel(x, y)</h3>
<p>Whenever our emulator toggles a pixel on or off, the display array will be modified to represent that. </p>
<p>Speaking of toggling pixels on or off, let's create the function that's in charge of that. We'll call the function <code>setPixel</code> and it'll take an <code>x</code> and <code>y</code> position as parameters.</p>
<pre><code class="lang-javascript">setPixel(x, y) {

}
</code></pre>
<p>According to the technical reference, if a pixel is positioned outside of the bounds of the display, it should wrap around to the opposite side, so we need to account for that.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (x &gt; <span class="hljs-built_in">this</span>.cols) {
    x -= <span class="hljs-built_in">this</span>.cols;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (x &lt; <span class="hljs-number">0</span>) {
    x += <span class="hljs-built_in">this</span>.cols;
}

<span class="hljs-keyword">if</span> (y &gt; <span class="hljs-built_in">this</span>.rows) {
    y -= <span class="hljs-built_in">this</span>.rows;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (y &lt; <span class="hljs-number">0</span>) {
    y += <span class="hljs-built_in">this</span>.rows;
}
</code></pre>
<p>With that figured out, we can properly calculate the location of the pixel on the display.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pixelLoc = x + (y * <span class="hljs-built_in">this</span>.cols);
</code></pre>
<p>If you're not familiar with bitwise operations, this next piece of code might be confusing. According to the technical reference, sprites are XORed onto the display:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">this</span>.display[pixelLoc] ^= <span class="hljs-number">1</span>;
</code></pre>
<p>All that this line is doing is toggling the value at <code>pixelLoc</code> (0 to 1 or 1 to 0). A value of 1 means a pixel should be drawn, a value of 0 means a pixel should be erased. From here, we just return a value to signify whether a pixel was erased or not. </p>
<p>This part, in particular, is important later on when we get to the CPU and writing the different instructions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> !<span class="hljs-built_in">this</span>.display[pixelLoc];
</code></pre>
<p>If this returns true, a pixel was erased. If this returns false, nothing was erased. When we get to the instruction that utilizes this function, it'll make more sense.</p>
<h3 id="heading-clear">clear()</h3>
<p>This function completely clears our <code>display</code> array by reinitializing it.</p>
<pre><code class="lang-javascript">clear() {
    <span class="hljs-built_in">this</span>.display = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-built_in">this</span>.cols * <span class="hljs-built_in">this</span>.rows);
}
</code></pre>
<h3 id="heading-render">render()</h3>
<p>The <code>render</code> function is in charge of rendering the pixels in the <code>display</code> array onto the screen. For this project, it will run 60 times per second.</p>
<pre><code class="lang-javascript">render() {
    <span class="hljs-comment">// Clears the display every render cycle. Typical for a render loop.</span>
    <span class="hljs-built_in">this</span>.ctx.clearRect(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-built_in">this</span>.canvas.width, <span class="hljs-built_in">this</span>.canvas.height);

    <span class="hljs-comment">// Loop through our display array</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.cols * <span class="hljs-built_in">this</span>.rows; i++) {
        <span class="hljs-comment">// Grabs the x position of the pixel based off of `i`</span>
        <span class="hljs-keyword">let</span> x = (i % <span class="hljs-built_in">this</span>.cols) * <span class="hljs-built_in">this</span>.scale;

        <span class="hljs-comment">// Grabs the y position of the pixel based off of `i`</span>
        <span class="hljs-keyword">let</span> y = <span class="hljs-built_in">Math</span>.floor(i / <span class="hljs-built_in">this</span>.cols) * <span class="hljs-built_in">this</span>.scale;

        <span class="hljs-comment">// If the value at this.display[i] == 1, then draw a pixel.</span>
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.display[i]) {
            <span class="hljs-comment">// Set the pixel color to black</span>
            <span class="hljs-built_in">this</span>.ctx.fillStyle = <span class="hljs-string">'#000'</span>;

            <span class="hljs-comment">// Place a pixel at position (x, y) with a width and height of scale</span>
            <span class="hljs-built_in">this</span>.ctx.fillRect(x, y, <span class="hljs-built_in">this</span>.scale, <span class="hljs-built_in">this</span>.scale);
        }
    }
}
</code></pre>
<h3 id="heading-testrender">testRender()</h3>
<p>For testing purposes, let's create a function that will draw a couple of pixels on the screen.</p>
<pre><code class="lang-javascript">testRender() {
    <span class="hljs-built_in">this</span>.setPixel(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
    <span class="hljs-built_in">this</span>.setPixel(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>);
}
</code></pre>
<p><a target="_blank" href="https://github.com/Erigitic/chip8-emulator/blob/master/scripts/renderer.js">Full renderer.js Code</a></p>
<h2 id="heading-chip8js">chip8.js</h2>
<p>Now that we have our renderer, we need to initialize it within our <code>chip8.js</code> file.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Renderer <span class="hljs-keyword">from</span> <span class="hljs-string">'./renderer.js'</span>;

<span class="hljs-keyword">const</span> renderer = <span class="hljs-keyword">new</span> Renderer(<span class="hljs-number">10</span>);
</code></pre>
<p>From here we need to create a loop that runs at, according to the technical reference, 60hz or 60 frames per second. Just like our render function, this is not Chip-8 specific and can be modified a bit to work with practically any other project.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> loop;

<span class="hljs-keyword">let</span> fps = <span class="hljs-number">60</span>, fpsInterval, startTime, now, then, elapsed;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    fpsInterval = <span class="hljs-number">1000</span> / fps;
    then = <span class="hljs-built_in">Date</span>.now();
    startTime = then;

    <span class="hljs-comment">// TESTING CODE. REMOVE WHEN DONE TESTING.</span>
    renderer.testRender();
    renderer.render();
    <span class="hljs-comment">// END TESTING CODE</span>

    loop = requestAnimationFrame(step);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">step</span>(<span class="hljs-params"></span>) </span>{
    now = <span class="hljs-built_in">Date</span>.now();
    elapsed = now - then;

    <span class="hljs-keyword">if</span> (elapsed &gt; fpsInterval) {
        <span class="hljs-comment">// Cycle the CPU. We'll come back to this later and fill it out.</span>
    }

    loop = requestAnimationFrame(step);
}

init();
</code></pre>
<p>If you start up the web server and load the page in a web browser you should see two pixels drawn on the screen. If you want, play with the scale and find something that works best for you.</p>
<h2 id="heading-keyboardjs">keyboard.js</h2>
<p><a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.3">Keyboard Reference</a></p>
<p>The technical reference tells us that Chip-8 uses a 16-key hex keypad that is laid out as follows:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td></td><td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td><td>C</td></tr>
<tr>
<td>4</td><td>5</td><td>6</td><td>D</td></tr>
<tr>
<td>7</td><td>8</td><td>9</td><td>E</td></tr>
<tr>
<td>A</td><td>0</td><td>B</td><td>F</td></tr>
</tbody>
</table>
</div><p>In order to make this work on modern systems, we have to map a key on our keyboard to each one of these Chip-8 keys. We'll do that within our constructor, as well as a few other things.</p>
<h3 id="heading-constructor">constructor()</h3>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Keyboard</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.KEYMAP = {
            <span class="hljs-number">49</span>: <span class="hljs-number">0x1</span>, <span class="hljs-comment">// 1</span>
            <span class="hljs-number">50</span>: <span class="hljs-number">0x2</span>, <span class="hljs-comment">// 2</span>
            <span class="hljs-number">51</span>: <span class="hljs-number">0x3</span>, <span class="hljs-comment">// 3</span>
            <span class="hljs-number">52</span>: <span class="hljs-number">0xc</span>, <span class="hljs-comment">// 4</span>
            <span class="hljs-number">81</span>: <span class="hljs-number">0x4</span>, <span class="hljs-comment">// Q</span>
            <span class="hljs-number">87</span>: <span class="hljs-number">0x5</span>, <span class="hljs-comment">// W</span>
            <span class="hljs-number">69</span>: <span class="hljs-number">0x6</span>, <span class="hljs-comment">// E</span>
            <span class="hljs-number">82</span>: <span class="hljs-number">0xD</span>, <span class="hljs-comment">// R</span>
            <span class="hljs-number">65</span>: <span class="hljs-number">0x7</span>, <span class="hljs-comment">// A</span>
            <span class="hljs-number">83</span>: <span class="hljs-number">0x8</span>, <span class="hljs-comment">// S</span>
            <span class="hljs-number">68</span>: <span class="hljs-number">0x9</span>, <span class="hljs-comment">// D</span>
            <span class="hljs-number">70</span>: <span class="hljs-number">0xE</span>, <span class="hljs-comment">// F</span>
            <span class="hljs-number">90</span>: <span class="hljs-number">0xA</span>, <span class="hljs-comment">// Z</span>
            <span class="hljs-number">88</span>: <span class="hljs-number">0x0</span>, <span class="hljs-comment">// X</span>
            <span class="hljs-number">67</span>: <span class="hljs-number">0xB</span>, <span class="hljs-comment">// C</span>
            <span class="hljs-number">86</span>: <span class="hljs-number">0xF</span>  <span class="hljs-comment">// V</span>
        }

        <span class="hljs-built_in">this</span>.keysPressed = [];

        <span class="hljs-comment">// Some Chip-8 instructions require waiting for the next keypress. We initialize this function elsewhere when needed.</span>
        <span class="hljs-built_in">this</span>.onNextKeyPress = <span class="hljs-literal">null</span>;

        <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'keydown'</span>, <span class="hljs-built_in">this</span>.onKeyDown.bind(<span class="hljs-built_in">this</span>), <span class="hljs-literal">false</span>);
        <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'keyup'</span>, <span class="hljs-built_in">this</span>.onKeyUp.bind(<span class="hljs-built_in">this</span>), <span class="hljs-literal">false</span>);
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Keyboard;
</code></pre>
<p>Within the constructor, we created a keymap that's mapping keys on our keyboard to keys on the Chip-8 keyboard. As well as that, we have an array to keep track of pressed keys, a null variable (which we'll talk about later), and a couple of event listeners for handling keyboard input.</p>
<h3 id="heading-iskeypressedkeycode">isKeyPressed(keyCode)</h3>
<p>We need a way to check if a certain key is pressed. This will simply check the <code>keysPressed</code> array for the specified Chip-8 <code>keyCode</code>.</p>
<pre><code class="lang-javascript">isKeyPressed(keyCode) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.keysPressed[keyCode];
}
</code></pre>
<h3 id="heading-onkeydownevent">onKeyDown(event)</h3>
<p>In our constructor, we added a <code>keydown</code> event listener that will call this function when triggered.</p>
<pre><code class="lang-javascript">onKeyDown(event) {
    <span class="hljs-keyword">let</span> key = <span class="hljs-built_in">this</span>.KEYMAP[event.which];
    <span class="hljs-built_in">this</span>.keysPressed[key] = <span class="hljs-literal">true</span>;

    <span class="hljs-comment">// Make sure onNextKeyPress is initialized and the pressed key is actually mapped to a Chip-8 key</span>
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.onNextKeyPress !== <span class="hljs-literal">null</span> &amp;&amp; key) {
        <span class="hljs-built_in">this</span>.onNextKeyPress(<span class="hljs-built_in">parseInt</span>(key));
        <span class="hljs-built_in">this</span>.onNextKeyPress = <span class="hljs-literal">null</span>;
    }
}
</code></pre>
<p>All we're doing in here is adding the pressed key to our <code>keysPressed</code> array, and running <code>onNextKeyPress</code> if it's initialized and a valid key was pressed.</p>
<p>Let's talk about that if statement. One of the Chip-8 instructions (<code>Fx0A</code>) waits for a keypress before continuing execution. We'll make the <code>Fx0A</code> instruction initialize the <code>onNextKeyPress</code> function, which will allow us to mimic this behavior of waiting until the next keypress. Once we write this instruction, I'll explain this in more detail as it should make more sense when you see it.</p>
<h3 id="heading-onkeyupevent">onKeyUp(event)</h3>
<p>We also have an event listener for handling <code>keyup</code> events, and this function will be called when that event is triggered.</p>
<pre><code class="lang-javascript">onKeyUp(event) {
    <span class="hljs-keyword">let</span> key = <span class="hljs-built_in">this</span>.KEYMAP[event.which];
    <span class="hljs-built_in">this</span>.keysPressed[key] = <span class="hljs-literal">false</span>;
}
</code></pre>
<p><a target="_blank" href="https://github.com/Erigitic/chip8-emulator/blob/master/scripts/keyboard.js">Full keyboard.js Code</a></p>
<h2 id="heading-chip8js-1">chip8.js</h2>
<p>With the keyboard class created, we can head back into <code>chip8.js</code> and hook the keyboard up.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Renderer <span class="hljs-keyword">from</span> <span class="hljs-string">'./renderer.js'</span>;
<span class="hljs-keyword">import</span> Keyboard <span class="hljs-keyword">from</span> <span class="hljs-string">'./keyboard.js'</span>; <span class="hljs-comment">// NEW</span>

<span class="hljs-keyword">const</span> renderer = <span class="hljs-keyword">new</span> Renderer(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> keyboard = <span class="hljs-keyword">new</span> Keyboard(); <span class="hljs-comment">// NEW</span>
</code></pre>
<h2 id="heading-speakerjs">speaker.js</h2>
<p>Let's make some sounds now. This file is fairly straightforward and involves creating a simple sound and starting/stopping it.</p>
<h3 id="heading-constructor-1">constructor</h3>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-keyword">const</span> AudioContext = <span class="hljs-built_in">window</span>.AudioContext || <span class="hljs-built_in">window</span>.webkitAudioContext;

        <span class="hljs-built_in">this</span>.audioCtx = <span class="hljs-keyword">new</span> AudioContext();

        <span class="hljs-comment">// Create a gain, which will allow us to control the volume</span>
        <span class="hljs-built_in">this</span>.gain = <span class="hljs-built_in">this</span>.audioCtx.createGain();
        <span class="hljs-built_in">this</span>.finish = <span class="hljs-built_in">this</span>.audioCtx.destination;

        <span class="hljs-comment">// Connect the gain to the audio context</span>
        <span class="hljs-built_in">this</span>.gain.connect(<span class="hljs-built_in">this</span>.finish);
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Speaker;
</code></pre>
<p>All we're doing here is creating an <code>AudioContext</code> and connecting a gain to it so we can control the volume. I won't be adding volume control in this tutorial, but if you'd like to add it yourself you simply use the following:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Mute the audio</span>
<span class="hljs-built_in">this</span>.gain.setValueAtTime(<span class="hljs-number">0</span>, <span class="hljs-built_in">this</span>.audioCtx.currentTime);
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Unmute the audio</span>
<span class="hljs-built_in">this</span>.gain.setValueAtTime(<span class="hljs-number">1</span>, <span class="hljs-built_in">this</span>.audioCtx.currentTime);
</code></pre>
<h3 id="heading-playfrequency">play(frequency)</h3>
<p>This function does exactly what the name suggests: plays a sound at the desired frequency.</p>
<pre><code class="lang-javascript">play(frequency) {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.audioCtx &amp;&amp; !<span class="hljs-built_in">this</span>.oscillator) {
        <span class="hljs-built_in">this</span>.oscillator = <span class="hljs-built_in">this</span>.audioCtx.createOscillator();

        <span class="hljs-comment">// Set the frequency</span>
        <span class="hljs-built_in">this</span>.oscillator.frequency.setValueAtTime(frequency || <span class="hljs-number">440</span>, <span class="hljs-built_in">this</span>.audioCtx.currentTime);

        <span class="hljs-comment">// Square wave</span>
        <span class="hljs-built_in">this</span>.oscillator.type = <span class="hljs-string">'square'</span>;

        <span class="hljs-comment">// Connect the gain and start the sound</span>
        <span class="hljs-built_in">this</span>.oscillator.connect(<span class="hljs-built_in">this</span>.gain);
        <span class="hljs-built_in">this</span>.oscillator.start();
    }
}
</code></pre>
<p>We are creating an oscillator which is what will be playing our sound. We set its frequency, the type, connect it to the gain, then finally play the sound. Nothing too crazy here.</p>
<h3 id="heading-stop">stop()</h3>
<p>We eventually have to stop the sound so it doesn't play constantly.</p>
<pre><code class="lang-javascript">stop() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.oscillator) {
        <span class="hljs-built_in">this</span>.oscillator.stop();
        <span class="hljs-built_in">this</span>.oscillator.disconnect();
        <span class="hljs-built_in">this</span>.oscillator = <span class="hljs-literal">null</span>;
    }
}
</code></pre>
<p>All this is doing is stopping the sound, disconnecting it, and setting it to null so it can be reinitialized in <code>play()</code>.</p>
<p><a target="_blank" href="https://github.com/Erigitic/chip8-emulator/blob/master/scripts/speaker.js">Full speaker.js Code</a></p>
<h2 id="heading-chip8js-2">chip8.js</h2>
<p>We can now hook the speaker up to our main <code>chip8.js</code> file.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Renderer <span class="hljs-keyword">from</span> <span class="hljs-string">'./renderer.js'</span>;
<span class="hljs-keyword">import</span> Keyboard <span class="hljs-keyword">from</span> <span class="hljs-string">'./keyboard.js'</span>;
<span class="hljs-keyword">import</span> Speaker <span class="hljs-keyword">from</span> <span class="hljs-string">'./speaker.js'</span>; <span class="hljs-comment">// NEW</span>

<span class="hljs-keyword">const</span> renderer = <span class="hljs-keyword">new</span> Renderer(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> keyboard = <span class="hljs-keyword">new</span> Keyboard();
<span class="hljs-keyword">const</span> speaker = <span class="hljs-keyword">new</span> Speaker(); <span class="hljs-comment">// NEW</span>
</code></pre>
<h2 id="heading-cpujs">cpu.js</h2>
<p>Now we're getting into the actual Chip-8 emulator. This is where things get a little bit crazy, but I'll do my best to explain everything in a way that hopefully makes sense of it all.</p>
<h3 id="heading-constructorrenderer-keyboard-speaker">constructor(renderer, keyboard, speaker)</h3>
<p>We need to initialize a few Chip-8 specific variables within our constructor, along with a few other variables. We're going to be looking at <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.0">section 2</a> of the technical reference to figure out the specifications for our Chip-8 emulator.</p>
<p>Here are the specifications for Chip-8:</p>
<ul>
<li>4KB (4096 bytes) of memory</li>
<li>16 8-bit registers</li>
<li>A 16-bit register (<code>this.i</code>) to store memory addresses</li>
<li>Two timers. One for the delay, and one for the sound.</li>
<li>A program counter that stores the address currently being executed</li>
<li>An array to represent the stack</li>
</ul>
<p>We also have a variable that stores whether the emulator is paused or not, and the execution speed of the emulator.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CPU</span> </span>{
    <span class="hljs-keyword">constructor</span>(renderer, keyboard, speaker) {
        <span class="hljs-built_in">this</span>.renderer = renderer;
        <span class="hljs-built_in">this</span>.keyboard = keyboard;
        <span class="hljs-built_in">this</span>.speaker = speaker;

        <span class="hljs-comment">// 4KB (4096 bytes) of memory</span>
        <span class="hljs-built_in">this</span>.memory = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(<span class="hljs-number">4096</span>);

        <span class="hljs-comment">// 16 8-bit registers</span>
        <span class="hljs-built_in">this</span>.v = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(<span class="hljs-number">16</span>);

        <span class="hljs-comment">// Stores memory addresses. Set this to 0 since we aren't storing anything at initialization.</span>
        <span class="hljs-built_in">this</span>.i = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Timers</span>
        <span class="hljs-built_in">this</span>.delayTimer = <span class="hljs-number">0</span>;
        <span class="hljs-built_in">this</span>.soundTimer = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Program counter. Stores the currently executing address.</span>
        <span class="hljs-built_in">this</span>.pc = <span class="hljs-number">0x200</span>;

        <span class="hljs-comment">// Don't initialize this with a size in order to avoid empty results.</span>
        <span class="hljs-built_in">this</span>.stack = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>();

        <span class="hljs-comment">// Some instructions require pausing, such as Fx0A.</span>
        <span class="hljs-built_in">this</span>.paused = <span class="hljs-literal">false</span>;

        <span class="hljs-built_in">this</span>.speed = <span class="hljs-number">10</span>;
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> CPU;
</code></pre>
<h3 id="heading-loadspritesintomemory">loadSpritesIntoMemory()</h3>
<p>For this function, we'll be referencing <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.4">section 2.4</a> of the technical reference.</p>
<p>Chip-8 makes use of 16, 5 byte, sprites. These sprites are simply the hex digits 0 through F. You can see all of the sprites, with their binary and hex values, in section 2.4. </p>
<p>In our code, we simply store the hex values of the sprites that the technical reference provides in an array. If you don't want to type them all out by hand, please feel free to copy and paste the array into your project.</p>
<p>The reference states that these sprites are stored in the interpreter section of memory (0x000 to 0x1FFF). Let's go ahead and look at the code for this function to see how this is done.</p>
<pre><code class="lang-javascript">loadSpritesIntoMemory() {
    <span class="hljs-comment">// Array of hex values for each sprite. Each sprite is 5 bytes.</span>
    <span class="hljs-comment">// The technical reference provides us with each one of these values.</span>
    <span class="hljs-keyword">const</span> sprites = [
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 0</span>
        <span class="hljs-number">0x20</span>, <span class="hljs-number">0x60</span>, <span class="hljs-number">0x20</span>, <span class="hljs-number">0x20</span>, <span class="hljs-number">0x70</span>, <span class="hljs-comment">// 1</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 2</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 3</span>
        <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0x10</span>, <span class="hljs-comment">// 4</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 5</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 6</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0x20</span>, <span class="hljs-number">0x40</span>, <span class="hljs-number">0x40</span>, <span class="hljs-comment">// 7</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 8</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x10</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// 9</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-comment">// A</span>
        <span class="hljs-number">0xE0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xE0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xE0</span>, <span class="hljs-comment">// B</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// C</span>
        <span class="hljs-number">0xE0</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xE0</span>, <span class="hljs-comment">// D</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-comment">// E</span>
        <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0xF0</span>, <span class="hljs-number">0x80</span>, <span class="hljs-number">0x80</span>  <span class="hljs-comment">// F</span>
    ];

    <span class="hljs-comment">// According to the technical reference, sprites are stored in the interpreter section of memory starting at hex 0x000</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; sprites.length; i++) {
        <span class="hljs-built_in">this</span>.memory[i] = sprites[i];
    }
}
</code></pre>
<p>All we did was loop through each byte in the <code>sprites</code> array and stored it in memory starting at hex <code>0x000</code>.</p>
<h3 id="heading-loadprogramintomemoryprogram">loadProgramIntoMemory(program)</h3>
<p>In order to run ROMs, we have to load them into memory. This is a lot easier then it might sound. All that we have to do is loop through the contents of the ROM/program and store it in memory. The technical reference specifically <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.1">tells us</a> that "most Chip-8 programs start at location 0x200". So when we load the ROM into memory, we start at <code>0x200</code> and increment from there.</p>
<pre><code class="lang-javascript">loadProgramIntoMemory(program) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> loc = <span class="hljs-number">0</span>; loc &lt; program.length; loc++) {
        <span class="hljs-built_in">this</span>.memory[<span class="hljs-number">0x200</span> + loc] = program[loc];
    }
}
</code></pre>
<h3 id="heading-loadromromname">loadRom(romName)</h3>
<p>Now we have a way to load the ROM into memory, but we have to grab the ROM from the filesystem first before it can be loaded into memory. For this to work, you have to have a ROM. I've included a few in the <a target="_blank" href="https://github.com/Erigitic/chip8-emulator/tree/master/roms">GitHub repo</a> for you to download and put into the <code>roms</code> folder of your project.</p>
<p>JavaScript provides a way to make an HTTP request and retrieve a file. I've added comments to the code below to explain what's going on:</p>
<pre><code class="lang-javascript">loadRom(romName) {
    <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> XMLHttpRequest;
    <span class="hljs-keyword">var</span> self = <span class="hljs-built_in">this</span>;

    <span class="hljs-comment">// Handles the response received from sending (request.send()) our request</span>
    request.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// If the request response has content</span>
        <span class="hljs-keyword">if</span> (request.response) {
            <span class="hljs-comment">// Store the contents of the response in an 8-bit array</span>
            <span class="hljs-keyword">let</span> program = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(request.response);

            <span class="hljs-comment">// Load the ROM/program into memory</span>
            self.loadProgramIntoMemory(program);
        }
    }

    <span class="hljs-comment">// Initialize a GET request to retrieve the ROM from our roms folder</span>
    request.open(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'roms/'</span> + romName);
    request.responseType = <span class="hljs-string">'arraybuffer'</span>;

    <span class="hljs-comment">// Send the GET request</span>
    request.send();
}
</code></pre>
<p>From here, we can start on the CPU cycle which will handle the execution of instructions, along with a few other things.</p>
<h3 id="heading-cycle">cycle()</h3>
<p>I think it'll be easier to understand everything if you can see what happens every time the CPU cycles. This is the function we will be calling in our <code>step</code> function in <code>chip8.js</code>, which if you remember, is executed about 60 times per second. We're going to take this function piece by piece.</p>
<p>At this point, the functions being called within <code>cycle</code> have yet to be created. We'll create them soon.</p>
<p>The first piece of code within our <code>cycle</code> function is a for loop that handles the execution of instructions. This is where our <code>speed</code> variable comes into play. The higher this value, the more instructions that will be executed every cycle.</p>
<pre><code class="lang-javascript">cycle() {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.speed; i++) {

    }
}
</code></pre>
<p>We also want to keep in mind that instructions should only be executed when the emulator is running.</p>
<pre><code class="lang-javascript">cycle() {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.speed; i++) {
        <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.paused) {

        }
    }
}
</code></pre>
<p>If you take a look at <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.1">section 3.1</a>, you can see all the different instructions and their opcodes. They look something like <code>00E0</code> or <code>9xy0</code> to give a few examples. So our job is to grab that opcode from memory and pass that along to another function that'll handle the execution of that instruction. Let's take a look at the code first, and then I'll explain it:</p>
<pre><code class="lang-javascript">cycle() {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.speed; i++) {
        <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.paused) {
            <span class="hljs-keyword">let</span> opcode = (<span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.pc] &lt;&lt; <span class="hljs-number">8</span> | <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.pc + <span class="hljs-number">1</span>]);
            <span class="hljs-built_in">this</span>.executeInstruction(opcode);
        }
    }
}
</code></pre>
<p>Let's take a look at this line in particular: <code>let opcode = (this.memory[this.pc] &lt;&lt; 8 | this.memory[this.pc + 1]);</code>. For those that aren't very familiar with bitwise operations, this can be very intimidating.</p>
<p>First of all, each instruction is 16 bits (2 bytes) long (<a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.0">3.0</a>), but our memory is made up of 8 bit (1 byte) pieces. This means we have to combine two pieces of memory in order to get the full opcode. That's why we have <code>this.pc</code> and <code>this.pc + 1</code> in the line of code above. We're simply grabbing both halves of the opcode. </p>
<p>But you can't just combine two, 1-byte values to get a 2-byte value. To properly do this, we need to shift the first piece of memory, <code>this.memory[this.pc]</code>, 8 bits left to make it 2 bytes long. In the most basic of terms, this will add two zeros, or more accurately hex value <code>0x00</code> onto the right-hand side of our 1-byte value, making it 2 bytes. </p>
<p>For example, shifting hex <code>0x11</code> 8 bits left will give us hex <code>0x1100</code>. From there, we bitwise OR (<code>|</code>) it with the second piece of memory, <code>this.memory[this.pc + 1])</code>.</p>
<p>Here's a step by step example that will help you better understand what this all means.</p>
<p>Let's assume a few values, each 1 byte in size:</p>
<p><code>this.memory[this.pc] = PC = 0x10</code>
<code>this.memory[this.pc + 1] = PC + 1 = 0xF0</code></p>
<p>Shift <code>PC</code> 8 bits (1 byte) left to make it 2 bytes:</p>
<p><code>PC = 0x1000</code></p>
<p>Bitwise OR <code>PC</code> and <code>PC + 1</code>:</p>
<p><code>PC | PC + 1 = 0x10F0</code></p>
<p>or</p>
<p><code>0x1000 | 0xF0 = 0x10F0</code></p>
<p>Lastly, we want to update our timers when are emulator is running (not paused), play sounds, and render sprites on the screen:</p>
<pre><code class="lang-javascript">cycle() {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.speed; i++) {
        <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.paused) {
            <span class="hljs-keyword">let</span> opcode = (<span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.pc] &lt;&lt; <span class="hljs-number">8</span> | <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.pc + <span class="hljs-number">1</span>]);
            <span class="hljs-built_in">this</span>.executeInstruction(opcode);
        }
    }

    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.paused) {
        <span class="hljs-built_in">this</span>.updateTimers();
    }

    <span class="hljs-built_in">this</span>.playSound();
    <span class="hljs-built_in">this</span>.renderer.render();
}
</code></pre>
<p>This function is the brain of our emulator in a way. It handles the execution of instructions, updates timers, plays sound, and renders content on the screen. </p>
<p>We don't have any of these functions created yet but seeing how the CPU cycles through everything will hopefully make these functions make a lot more sense when we do create them.</p>
<h3 id="heading-updatetimers">updateTimers()</h3>
<p>Let's move on to <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.5">section 2.5</a> and set up the logic for the timers and sound.</p>
<p>Each timer, delay and sound, decrement by 1 at a rate of 60Hz. In other words, every 60 frames our timers will decrement by 1.</p>
<pre><code class="lang-javascript">updateTimers() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.delayTimer &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">this</span>.delayTimer -= <span class="hljs-number">1</span>;
    }

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.soundTimer &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">this</span>.soundTimer -= <span class="hljs-number">1</span>;
    }
}
</code></pre>
<p>The delay timer is used for keeping track of when certain events occur. This timer is only used in two instructions: once for setting its value, and another for reading its value and branching to another instruction if a certain value is present.</p>
<p>The sound timer is what controls the length of the sound. As long as the value of <code>this.soundTimer</code> is greater than zero, the sound will continue to play. When the sound timer hits zero, the sound will stop. That brings us into our next function where we will be doing exactly that.</p>
<h3 id="heading-playsound">playSound()</h3>
<p>To reiterate, as long as the sound timer is greater than zero, we want to play a sound. We will be using the <code>play</code> function from our <code>Speaker</code> class we made earlier to play a sound with a frequency of 440.</p>
<pre><code class="lang-javascript">playSound() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.soundTimer &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">this</span>.speaker.play(<span class="hljs-number">440</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">this</span>.speaker.stop();
    }
}
</code></pre>
<h3 id="heading-executeinstructionopcode">executeInstruction(opcode)</h3>
<p>For this entire function, we'll be referencing <a target="_blank" href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.0">section 3.0 and 3.1</a> of the technical reference.</p>
<p>This is the final function we need for this file, and this one is long. We have to write out the logic for all 36 Chip-8 instructions. Thankfully, most of these instructions only require a few lines of code.</p>
<p>The first piece of information to be aware of is that all instructions are 2 bytes long. So every time we execute an instruction, or run this function, we have to increment the program counter (<code>this.pc</code>) by 2 so the CPU knows where the next instruction is.</p>
<pre><code class="lang-javascript">executeInstruction(opcode) {
    <span class="hljs-comment">// Increment the program counter to prepare it for the next instruction.</span>
    <span class="hljs-comment">// Each instruction is 2 bytes long, so increment it by 2.</span>
    <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
}
</code></pre>
<p>Let's take a look at this part of section 3.0 now:</p>
<pre><code>In these listings, the following variables are used:

nnn or addr - A <span class="hljs-number">12</span>-bit value, the lowest <span class="hljs-number">12</span> bits <span class="hljs-keyword">of</span> the instruction
n or nibble - A <span class="hljs-number">4</span>-bit value, the lowest <span class="hljs-number">4</span> bits <span class="hljs-keyword">of</span> the instruction
x - A <span class="hljs-number">4</span>-bit value, the lower <span class="hljs-number">4</span> bits <span class="hljs-keyword">of</span> the high byte <span class="hljs-keyword">of</span> the instruction
y - A <span class="hljs-number">4</span>-bit value, the upper <span class="hljs-number">4</span> bits <span class="hljs-keyword">of</span> the low byte <span class="hljs-keyword">of</span> the instruction
kk or byte - An <span class="hljs-number">8</span>-bit value, the lowest <span class="hljs-number">8</span> bits <span class="hljs-keyword">of</span> the instruction
</code></pre><p>To avoid repeating code, we should create variables for the <code>x</code> and <code>y</code> values as they are the ones used by nearly every instruction. The other variables listed above aren't used enough to warrant calculating their values every time.</p>
<p>These two values are each 4 bits (aka. half a byte or a nibble) in size. The <code>x</code> value is located in the lower 4 bits of the high byte and <code>y</code> is located in the upper 4 bits of the low byte.</p>
<p>For example, if we have an instruction <code>0x5460</code>, the high byte would be <code>0x54</code> and the low byte would be <code>0x60</code>.  The lower 4 bits, or nibble, of the high byte would be <code>0x4</code> and the upper 4 bits of the low byte would be <code>0x6</code>. Therefore, in this example, <code>x = 0x4</code> and <code>y= 0x6</code>.</p>
<p>Knowing all of that, let's write the code that'll grab the <code>x</code> and <code>y</code> values.</p>
<pre><code class="lang-javascript">executeInstruction(opcode) {
    <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;

    <span class="hljs-comment">// We only need the 2nd nibble, so grab the value of the 2nd nibble</span>
    <span class="hljs-comment">// and shift it right 8 bits to get rid of everything but that 2nd nibble.</span>
    <span class="hljs-keyword">let</span> x = (opcode &amp; <span class="hljs-number">0x0F00</span>) &gt;&gt; <span class="hljs-number">8</span>;

    <span class="hljs-comment">// We only need the 3rd nibble, so grab the value of the 3rd nibble</span>
    <span class="hljs-comment">// and shift it right 4 bits to get rid of everything but that 3rd nibble.</span>
    <span class="hljs-keyword">let</span> y = (opcode &amp; <span class="hljs-number">0x00F0</span>) &gt;&gt; <span class="hljs-number">4</span>;
}
</code></pre>
<p>To explain this, let's once again assume we have an instruction <code>0x5460</code>. If we <code>&amp;</code> (bitwise AND) that instruction with hex value <code>0x0F00</code> we'll end up with <code>0x0400</code>. Shift that 8 bits right and we end up with <code>0x04</code> or <code>0x4</code>. Same thing with <code>y</code>. We <code>&amp;</code> the instruction with hex value <code>0x00F0</code> and get <code>0x0060</code>. Shift that 4 bits right and we end up with <code>0x006</code> or <code>0x6</code>.</p>
<p>Now for the fun part, writing the logic for all 36 instructions. For each instruction, before you write the code, I highly recommend reading what that instruction does in the technical reference as you'll understand it a lot better.</p>
<p>I'm going to provide you with the empty switch statement you'll be using as it's quite long.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">switch</span> (opcode &amp; <span class="hljs-number">0xF000</span>) {
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x0000</span>:
        <span class="hljs-keyword">switch</span> (opcode) {
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x00E0</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x00EE</span>:
                <span class="hljs-keyword">break</span>;
        }

        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x1000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x2000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x3000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x4000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x5000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x6000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x7000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x8000</span>:
        <span class="hljs-keyword">switch</span> (opcode &amp; <span class="hljs-number">0xF</span>) {
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x0</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x1</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x2</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x3</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x4</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x5</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x6</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x7</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0xE</span>:
                <span class="hljs-keyword">break</span>;
        }

        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0x9000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xA000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xB000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xC000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xD000</span>:
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xE000</span>:
        <span class="hljs-keyword">switch</span> (opcode &amp; <span class="hljs-number">0xFF</span>) {
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x9E</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0xA1</span>:
                <span class="hljs-keyword">break</span>;
        }

        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">0xF000</span>:
        <span class="hljs-keyword">switch</span> (opcode &amp; <span class="hljs-number">0xFF</span>) {
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x07</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x0A</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x15</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x18</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x1E</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x29</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x33</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x55</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">0x65</span>:
                <span class="hljs-keyword">break</span>;
        }

        <span class="hljs-keyword">break</span>;

    <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Unknown opcode '</span> + opcode);
}
</code></pre>
<p>As you can see from <code>switch (opcode &amp; 0xF000)</code>, we're grabbing the upper 4 bits of the most significant byte of the opcode. If you take a look at the different instructions in the technical reference you'll notice that we can narrow down the different opcodes by that very first nibble.</p>
<h4 id="heading-0nnn-sys-addr">0nnn - SYS addr</h4>
<p>This opcode can be ignored.</p>
<h4 id="heading-00e0-cls">00E0 - CLS</h4>
<p>Clear the display.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x00E0</span>:
    <span class="hljs-built_in">this</span>.renderer.clear();
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-00ee-ret">00EE - RET</h4>
<p>Pop the last element in the <code>stack</code> array and store it in <code>this.pc</code>. This will return us from a subroutine.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x00EE</span>:
    <span class="hljs-built_in">this</span>.pc = <span class="hljs-built_in">this</span>.stack.pop();
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>The technical reference states this instruction also "subtracts 1 from the stack pointer". The stack pointer is used to point to the topmost level of the stack. But thanks to our <code>stack</code> array, we don't need to worry about where the top of the stack is since it's handled by the array. So for the rest of the instructions, if it says something about the stack pointer, you can safely ignore it.</p>
<h4 id="heading-1nnn-jp-addr">1nnn - JP addr</h4>
<p>Set the program counter to the value stored in <code>nnn</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x1000</span>:
    <span class="hljs-built_in">this</span>.pc = (opcode &amp; <span class="hljs-number">0xFFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<p><code>0xFFF</code> grabs the value of <code>nnn</code>. So <code>0x1426 &amp; 0xFFF</code> will give us <code>0x426</code> and then we store that in <code>this.pc</code>.</p>
<h4 id="heading-2nnn-call-addr">2nnn - CALL addr</h4>
<p>For this, the technical reference says we have to increment the stack pointer so it points to the current value of <code>this.pc</code>. Again, we aren't using a stack pointer in our project as our <code>stack</code> array handles that for us. So instead of incrementing that, we just push <code>this.pc</code> onto the stack which will give us the same result. And just like with opcode <code>1nnn</code>, we grab the value of <code>nnn</code> and store that in <code>this.pc</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x2000</span>:
    <span class="hljs-built_in">this</span>.stack.push(<span class="hljs-built_in">this</span>.pc);
    <span class="hljs-built_in">this</span>.pc = (opcode &amp; <span class="hljs-number">0xFFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-3xkk-se-vx-byte">3xkk - SE Vx, byte</h4>
<p>This is where our <code>x</code> value we calculated above comes into play.</p>
<p>This instruction compares the value stored in the <code>x</code> register (<code>Vx</code>) to the value of <code>kk</code>. Note that <code>V</code> signifies a register, and the value following it, in this case <code>x</code>, is the register number. If they are equal, we increment the program counter by 2, effectively skipping the next instruction.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x3000</span>:
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[x] === (opcode &amp; <span class="hljs-number">0xFF</span>)) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>The <code>opcode &amp; 0xFF</code> part of the if statement is simply grabbing the last byte of the opcode. This is the <code>kk</code> portion of the opcode.</p>
<h4 id="heading-4xkk-sne-vx-byte">4xkk - SNE Vx, byte</h4>
<p>This instruction is very similar to <code>3xkk</code>, but instead skips the next instruction if <code>Vx</code> and <code>kk</code> are NOT equal.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x4000</span>:
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[x] !== (opcode &amp; <span class="hljs-number">0xFF</span>)) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-5xy0-se-vx-vy">5xy0 - SE Vx, Vy</h4>
<p>Now we're making use of both <code>x</code> and <code>y</code>. This instruction, like the previous two, will skip the next instruction if a condition is met. In the case of this instruction, if <code>Vx</code> is equal to <code>Vy</code> we skip the next instruction.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x5000</span>:
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[x] === <span class="hljs-built_in">this</span>.v[y]) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-6xkk-ld-vx-byte">6xkk - LD Vx, byte</h4>
<p>This instruction will set the value of <code>Vx</code> to the value of <code>kk</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x6000</span>:
    <span class="hljs-built_in">this</span>.v[x] = (opcode &amp; <span class="hljs-number">0xFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-7xkk-add-vx-byte">7xkk - ADD Vx, byte</h4>
<p>This instruction adds <code>kk</code> to <code>Vx</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x7000</span>:
    <span class="hljs-built_in">this</span>.v[x] += (opcode &amp; <span class="hljs-number">0xFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-8xy0-ld-vx-vy">8xy0 - LD Vx, Vy</h4>
<p>Before discussing this instruction, I'd like to explain what's going on with <code>switch (opcode &amp; 0xF)</code>. Why the switch within a switch? </p>
<p>The reasoning behind this is we have a handful of different instructions that fall under <code>case 0x8000:</code>. If you take a look at those instructions in the technical reference, you'll notice the last nibble of each one of these instructions ends with a value <code>0-7</code> or <code>E</code>. </p>
<p>We have this switch to grab that last nibble, and then create a case for each one to properly handle it. We do this a few more times throughout the main switch statement.</p>
<p>With that explained, let's get on to the instruction. Nothing crazy with this one, just setting the value of <code>Vx</code> equal to the value of <code>Vy</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x0</span>:
    <span class="hljs-built_in">this</span>.v[x] = <span class="hljs-built_in">this</span>.v[y];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-8xy1-or-vx-vy">8xy1 - OR Vx, Vy</h4>
<p>Set <code>Vx</code> to the value of <code>Vx OR Vy</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x1</span>:
    <span class="hljs-built_in">this</span>.v[x] |= <span class="hljs-built_in">this</span>.v[y];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-8xy2-and-vx-vy">8xy2 - AND Vx, Vy</h4>
<p>Set <code>Vx</code> equal to the value of <code>Vx AND Vy</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x2</span>:
    <span class="hljs-built_in">this</span>.v[x] &amp;= <span class="hljs-built_in">this</span>.v[y];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-8xy3-xor-vx-vy">8xy3 - XOR Vx, Vy</h4>
<p>Set <code>Vx</code> equal to the value of <code>Vx XOR Vy</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x3</span>:
    <span class="hljs-built_in">this</span>.v[x] ^= <span class="hljs-built_in">this</span>.v[y];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-8xy4-add-vx-vy">8xy4 - ADD Vx, Vy</h4>
<p>This instruction sets <code>Vx</code> to <code>Vx + Vy</code>. Sounds easy, but there is a little more to it. If we read the description for this instruction provided in the technical reference it says the following:</p>
<blockquote>
<p>If the result is greater than 8 bits (i.e., &gt; 255,) VF is set to 1, otherwise 0. Only the lowest 8 bits of the result are kept, and stored in Vx.</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x4</span>:
    <span class="hljs-keyword">let</span> sum = (<span class="hljs-built_in">this</span>.v[x] += <span class="hljs-built_in">this</span>.v[y]);

    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">if</span> (sum &gt; <span class="hljs-number">0xFF</span>) {
        <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">1</span>;
    }

    <span class="hljs-built_in">this</span>.v[x] = sum;
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>Taking this line by line, we first add <code>this.v[y]</code> to <code>this.v[x]</code> and store that value in a variable <code>sum</code>. From there we set <code>this.v[0xF]</code>, or <code>VF</code>, to 0. We do this to avoid having to use an if-else statement on the next line. If the sum is greater than 255, or hex <code>0xFF</code>, we set <code>VF</code> to 1. Finally, we set <code>this.v[x]</code>, or <code>Vx</code>, to the sum.</p>
<p>You might be wondering how we go about ensuring "only the lowest 8 bits of the result are kept, and stored in Vx". Thanks to <code>this.v</code> being a <code>Uint8Array</code>, any value over 8 bits automatically has the lower, rightmost, 8 bits taken and stored in the array. Therefore we don't need to do anything special with it.</p>
<p>Let me provide you with an example to make more sense of this. Assume we try to put decimal 257 into the <code>this.v</code> array. In binary that value is <code>100000001</code>, a 9-bit value. When we attempt to store that 9-bit value into the array, it will only take the lower 8 bits. This means binary <code>00000001</code>, which is 1 in decimal, would be stored in <code>this.v</code>.</p>
<h4 id="heading-8xy5-sub-vx-vy">8xy5 - SUB Vx, Vy</h4>
<p>This instruction subtracts <code>Vy</code> from <code>Vx</code>. Just like overflow is handled in the previous instruction, we have to handle underflow for this one.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x5</span>:
    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[x] &gt; <span class="hljs-built_in">this</span>.v[y]) {
        <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">1</span>;
    }

    <span class="hljs-built_in">this</span>.v[x] -= <span class="hljs-built_in">this</span>.v[y];
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>Once again, since we're using a <code>Uint8Array</code>, we don't have to do anything to handle underflow as it's taken care of for us. So -1 will become 255, -2 becomes 254, and so forth.</p>
<h4 id="heading-8xy6-shr-vx-vy">8xy6 - SHR Vx {, Vy}</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x6</span>:
    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = (<span class="hljs-built_in">this</span>.v[x] &amp; <span class="hljs-number">0x1</span>);

    <span class="hljs-built_in">this</span>.v[x] &gt;&gt;= <span class="hljs-number">1</span>;
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>This line <code>this.v[0xF] = (this.v[x] &amp; 0x1);</code> is going to determine the least-significant bit and set <code>VF</code> accordingly.</p>
<p>This is a lot easier to understand if you look at its binary representation. If <code>Vx</code>, in binary, is <code>1001</code>, <code>VF</code> will be set to 1 since the least-significant bit is 1. If <code>Vx</code> is <code>1000</code>, <code>VF</code> will be set to 0.</p>
<h4 id="heading-8xy7-subn-vx-vy">8xy7 - SUBN Vx, Vy</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x7</span>:
    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[y] &gt; <span class="hljs-built_in">this</span>.v[x]) {
        <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">1</span>;
    }

    <span class="hljs-built_in">this</span>.v[x] = <span class="hljs-built_in">this</span>.v[y] - <span class="hljs-built_in">this</span>.v[x];
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>This instruction subtracts <code>Vx</code> from <code>Vy</code> and stores the result in <code>Vx</code>. If <code>Vy</code> is larger then <code>Vx</code>, we need to store 1 in <code>VF</code>, otherwise we store 0.</p>
<h4 id="heading-8xye-shl-vx-vy">8xyE - SHL Vx {, Vy}</h4>
<p>This instruction not only shifts <code>Vx</code> left 1, but also sets <code>VF</code> to either 0 or 1 depending on if a condition is met.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xE</span>:
    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = (<span class="hljs-built_in">this</span>.v[x] &amp; <span class="hljs-number">0x80</span>);
    <span class="hljs-built_in">this</span>.v[x] &lt;&lt;= <span class="hljs-number">1</span>;
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>The first line of code, <code>this.v[0xF] = (this.v[x] &amp; 0x80);</code>, is grabbing the most significant bit of <code>Vx</code> and storing that in <code>VF</code>. To explain this, we have an 8-bit register, <code>Vx</code>, and we want to get the most significant, or leftmost, bit. To do this we need to AND <code>Vx</code> with binary <code>10000000</code>, or <code>0x80</code> in hex. This will accomplish setting <code>VF</code> to the proper value.</p>
<p>After that, we simply multiply <code>Vx</code> by 2 by shifting it left 1.</p>
<h4 id="heading-9xy0-sne-vx-vy">9xy0 - SNE Vx, Vy</h4>
<p>This instruction simply increments the program counter by 2 if <code>Vx</code> and <code>Vy</code> are not equal.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x9000</span>:
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.v[x] !== <span class="hljs-built_in">this</span>.v[y]) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-annn-ld-i-addr">Annn - LD I, addr</h4>
<p>Set the value of register <code>i</code> to <code>nnn</code>. If the opcode is <code>0xA740</code> then <code>(opcode &amp; 0xFFF)</code> will return <code>0x740</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xA000</span>:
    <span class="hljs-built_in">this</span>.i = (opcode &amp; <span class="hljs-number">0xFFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-bnnn-jp-v0-addr">Bnnn - JP V0, addr</h4>
<p>Set the program counter (<code>this.pc</code>) to <code>nnn</code> plus the value of register 0 (<code>V0</code>).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xB000</span>:
    <span class="hljs-built_in">this</span>.pc = (opcode &amp; <span class="hljs-number">0xFFF</span>) + <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-cxkk-rnd-vx-byte">Cxkk - RND Vx, byte</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xC000</span>:
    <span class="hljs-keyword">let</span> rand = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">0xFF</span>);

    <span class="hljs-built_in">this</span>.v[x] = rand &amp; (opcode &amp; <span class="hljs-number">0xFF</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>Generate a random number in the range 0-255 and then AND that with the lowest byte of the opcode. For example, if the opcode is <code>0xB849</code>, then <code>(opcode &amp; 0xFF)</code> would return <code>0x49</code>.</p>
<h4 id="heading-dxyn-drw-vx-vy-nibble">Dxyn - DRW Vx, Vy, nibble</h4>
<p>This is a big one! This instruction handles the drawing and erasing of pixels on the screen. I'm going to provide you all the code and explain it line-by-line.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xD000</span>:
    <span class="hljs-keyword">let</span> width = <span class="hljs-number">8</span>;
    <span class="hljs-keyword">let</span> height = (opcode &amp; <span class="hljs-number">0xF</span>);

    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> row = <span class="hljs-number">0</span>; row &lt; height; row++) {
        <span class="hljs-keyword">let</span> sprite = <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i + row];

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> col = <span class="hljs-number">0</span>; col &lt; width; col++) {
            <span class="hljs-comment">// If the bit (sprite) is not 0, render/erase the pixel</span>
            <span class="hljs-keyword">if</span> ((sprite &amp; <span class="hljs-number">0x80</span>) &gt; <span class="hljs-number">0</span>) {
                <span class="hljs-comment">// If setPixel returns 1, which means a pixel was erased, set VF to 1</span>
                <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.renderer.setPixel(<span class="hljs-built_in">this</span>.v[x] + col, <span class="hljs-built_in">this</span>.v[y] + row)) {
                    <span class="hljs-built_in">this</span>.v[<span class="hljs-number">0xF</span>] = <span class="hljs-number">1</span>;
                }
            }

            <span class="hljs-comment">// Shift the sprite left 1. This will move the next next col/bit of the sprite into the first position.</span>
            <span class="hljs-comment">// Ex. 10010000 &lt;&lt; 1 will become 0010000</span>
            sprite &lt;&lt;= <span class="hljs-number">1</span>;
        }
    }

    <span class="hljs-keyword">break</span>;
</code></pre>
<p>We have a <code>width</code> variable set to 8 because each sprite is 8 pixels wide, so it's safe to hardcode that value in. Next, we set <code>height</code> to the value of the last nibble (<code>n</code>) of the opcode. If our opcode is <code>0xD235</code>, <code>height</code> will be set to 5. From there we set <code>VF</code> to 0, which if necessary, will be set to 1 later on if pixels are erased.</p>
<p>Now onto the for loops. Remember that a sprite looks something like this:</p>
<pre><code><span class="hljs-number">11110000</span>
<span class="hljs-number">10010000</span>
<span class="hljs-number">10010000</span>
<span class="hljs-number">10010000</span>
<span class="hljs-number">11110000</span>
</code></pre><p>Our code is going row by row (first <code>for</code> loop), then it's going bit by bit or column by column (second <code>for</code> loop) through that sprite.</p>
<p>This piece of code, <code>let sprite = this.memory[this.i + row];</code>, is grabbing 8-bits of memory, or a single row of a sprite, that's stored at <code>this.i + row</code>. The technical reference states we start at the address stored in <code>I</code>, or <code>this.i</code> in our case, when we read sprites from memory.</p>
<p>Within our second <code>for</code> loop, we have an <code>if</code> statement that is grabbing the leftmost bit and checking to see if it's greater than 0. </p>
<p>A value of 0 indicates that the sprite does not have a pixel at that location, so we don't need to worry about drawing or erasing it. If the value is 1, we move on to another if statement that checks the return value of <code>setPixel</code>. Let's look into the values passed into that function.</p>
<p>Our <code>setPixel</code> call looks like this: <code>this.renderer.setPixel(this.v[x] + col, this.v[y] + row)</code>. According to the technical reference, the <code>x</code> and <code>y</code> positions are located in <code>Vx</code> and <code>Vy</code> respectively. Add the <code>col</code> number to <code>Vx</code> and the <code>row</code> number to <code>Vy</code>, and you get the desired position to draw/erase a pixel. </p>
<p>If <code>setPixel</code> returns 1, we erase the pixel and set <code>VF</code> to 1. If it returns 0, we don't do anything, keeping the value of <code>VF</code> equal to 0.</p>
<p>Lastly, we are shifting the sprite left 1 bit. This allows us to go through each bit of the sprite. </p>
<p>For example, if <code>sprite</code> is currently set to <code>10010000</code>, it will become <code>0010000</code> after being shifted left. From there, we can go through another iteration of our inner <code>for</code> loop to determine whether or not to draw a pixel. And continuing this process till we reach the end or our sprite.</p>
<h4 id="heading-ex9e-skp-vx">Ex9E - SKP Vx</h4>
<p>This one is fairly simple and just skips the next instruction if the key stored in <code>Vx</code> is pressed, by incrementing the program counter by 2.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x9E</span>:
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.keyboard.isKeyPressed(<span class="hljs-built_in">this</span>.v[x])) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-exa1-sknp-vx">ExA1 - SKNP Vx</h4>
<p>This does the opposite of the previous instruction. If the specified key is not pressed, skip the next instruction.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0xA1</span>:
    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.keyboard.isKeyPressed(<span class="hljs-built_in">this</span>.v[x])) {
        <span class="hljs-built_in">this</span>.pc += <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx07-ld-vx-dt">Fx07 - LD Vx, DT</h4>
<p>Another simple one. We're just setting <code>Vx</code> to the value stored in <code>delayTimer</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x07</span>:
    <span class="hljs-built_in">this</span>.v[x] = <span class="hljs-built_in">this</span>.delayTimer;
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx0a-ld-vx-k">Fx0A - LD Vx, K</h4>
<p>Taking a look at the technical reference, this instruction pauses the emulator until a key is pressed. Here's the code for it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x0A</span>:
    <span class="hljs-built_in">this</span>.paused = <span class="hljs-literal">true</span>;

    <span class="hljs-built_in">this</span>.keyboard.onNextKeyPress = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">key</span>) </span>{
        <span class="hljs-built_in">this</span>.v[x] = key;
        <span class="hljs-built_in">this</span>.paused = <span class="hljs-literal">false</span>;
    }.bind(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<p>We first set <code>paused</code> to true in order to pause the emulator. Then, if you remember from our <code>keyboard.js</code> file where we set <code>onNextKeyPress</code> to null, this is where we initialize it. With the <code>onNextKeyPress</code> function initialized, the next time the <code>keydown</code> event is triggered, the following code in our <code>keyboard.js</code> file will be run:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// keyboard.js</span>
<span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.onNextKeyPress !== <span class="hljs-literal">null</span> &amp;&amp; key) {
    <span class="hljs-built_in">this</span>.onNextKeyPress(<span class="hljs-built_in">parseInt</span>(key));
    <span class="hljs-built_in">this</span>.onNextKeyPress = <span class="hljs-literal">null</span>;
}
</code></pre>
<p>From there, we set <code>Vx</code> to the pressed key's keycode and finally start the emulator back up by setting <code>paused</code> to false.</p>
<h3 id="heading-fx15-ld-dt-vx">Fx15 - LD DT, Vx</h3>
<p>This instruction simply sets the value of the delay timer to the value stored in register <code>Vx</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x15</span>:
    <span class="hljs-built_in">this</span>.delayTimer = <span class="hljs-built_in">this</span>.v[x];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx18-ld-st-vx">Fx18 - LD ST, Vx</h4>
<p>This instruction is very similar to Fx15 but sets the sound timer to <code>Vx</code> instead of the delay timer.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x18</span>:
    <span class="hljs-built_in">this</span>.soundTimer = <span class="hljs-built_in">this</span>.v[x];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx1e-add-i-vx">Fx1E - ADD I, Vx</h4>
<p>Add <code>Vx</code> to <code>I</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x1E</span>:
    <span class="hljs-built_in">this</span>.i += <span class="hljs-built_in">this</span>.v[x];
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx29-ld-f-vx-add-i-vx">Fx29 - LD F, Vx - ADD I, Vx</h4>
<p>For this one, we are setting <code>I</code> to the location of the sprite at <code>Vx</code>. It's multiplied by 5 because each sprite is 5 bytes long.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x29</span>:
    <span class="hljs-built_in">this</span>.i = <span class="hljs-built_in">this</span>.v[x] * <span class="hljs-number">5</span>;
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx33-ld-b-vx">Fx33 - LD B, Vx</h4>
<p>This instruction is going to grab the hundreds, tens, and ones digit from register <code>Vx</code> and store them in registers <code>I</code>, <code>I+1</code>, and <code>I+2</code> respectively.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x33</span>:
    <span class="hljs-comment">// Get the hundreds digit and place it in I.</span>
    <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i] = <span class="hljs-built_in">parseInt</span>(<span class="hljs-built_in">this</span>.v[x] / <span class="hljs-number">100</span>);

    <span class="hljs-comment">// Get tens digit and place it in I+1. Gets a value between 0 and 99,</span>
    <span class="hljs-comment">// then divides by 10 to give us a value between 0 and 9.</span>
    <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i + <span class="hljs-number">1</span>] = <span class="hljs-built_in">parseInt</span>((<span class="hljs-built_in">this</span>.v[x] % <span class="hljs-number">100</span>) / <span class="hljs-number">10</span>);

    <span class="hljs-comment">// Get the value of the ones (last) digit and place it in I+2.</span>
    <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i + <span class="hljs-number">2</span>] = <span class="hljs-built_in">parseInt</span>(<span class="hljs-built_in">this</span>.v[x] % <span class="hljs-number">10</span>);
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx55-ld-i-vx">Fx55 - LD [I], Vx</h4>
<p>In this instruction, we are looping through registers <code>V0</code> through <code>Vx</code> and storing its value in memory starting at <code>I</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x55</span>:
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> registerIndex = <span class="hljs-number">0</span>; registerIndex &lt;= x; registerIndex++) {
        <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i + registerIndex] = <span class="hljs-built_in">this</span>.v[registerIndex];
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h4 id="heading-fx65-ld-vx-i">Fx65 - LD Vx, [I]</h4>
<p>Now on to the last instruction. This one does the opposite of <code>Fx55</code>. It reads values from memory starting at <code>I</code> and stores them in registers <code>V0</code> through <code>Vx</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-number">0x65</span>:
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> registerIndex = <span class="hljs-number">0</span>; registerIndex &lt;= x; registerIndex++) {
        <span class="hljs-built_in">this</span>.v[registerIndex] = <span class="hljs-built_in">this</span>.memory[<span class="hljs-built_in">this</span>.i + registerIndex];
    }
    <span class="hljs-keyword">break</span>;
</code></pre>
<h2 id="heading-chip8js-3">chip8.js</h2>
<p>With our CPU class created, let's finish up our <code>chip8.js</code> file by loading in a ROM and cycling our CPU. We'll need to import <code>cpu.js</code> and initialize a CPU object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Renderer <span class="hljs-keyword">from</span> <span class="hljs-string">'./renderer.js'</span>;
<span class="hljs-keyword">import</span> Keyboard <span class="hljs-keyword">from</span> <span class="hljs-string">'./keyboard.js'</span>;
<span class="hljs-keyword">import</span> Speaker <span class="hljs-keyword">from</span> <span class="hljs-string">'./speaker.js'</span>;
<span class="hljs-keyword">import</span> CPU <span class="hljs-keyword">from</span> <span class="hljs-string">'./cpu.js'</span>; <span class="hljs-comment">// NEW</span>

<span class="hljs-keyword">const</span> renderer = <span class="hljs-keyword">new</span> Renderer(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> keyboard = <span class="hljs-keyword">new</span> Keyboard();
<span class="hljs-keyword">const</span> speaker = <span class="hljs-keyword">new</span> Speaker();
<span class="hljs-keyword">const</span> cpu = <span class="hljs-keyword">new</span> CPU(renderer, keyboard, speaker); <span class="hljs-comment">// NEW</span>
</code></pre>
<p>Our <code>init</code> function becomes:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    fpsInterval = <span class="hljs-number">1000</span> / fps;
    then = <span class="hljs-built_in">Date</span>.now();
    startTime = then;

    cpu.loadSpritesIntoMemory(); <span class="hljs-comment">// NEW</span>
    cpu.loadRom(<span class="hljs-string">'BLITZ'</span>); <span class="hljs-comment">// NEW</span>
    loop = requestAnimationFrame(step);
}
</code></pre>
<p>When our emulator is initialized we will load the sprites into memory and load up the <code>BLITZ</code> rom. Now we just need to cycle the CPU:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">step</span>(<span class="hljs-params"></span>) </span>{
    now = <span class="hljs-built_in">Date</span>.now();
    elapsed = now - then;

    <span class="hljs-keyword">if</span> (elapsed &gt; fpsInterval) {
        cpu.cycle(); <span class="hljs-comment">// NEW</span>
    }

    loop = requestAnimationFrame(step);
}
</code></pre>
<p>With that done, we should now have a working Chip8 emulator.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I started this project a while ago and was fascinated by it. Emulator creation was always something that interested me but never made sense to me. That was until I learned about Chip-8 and the simplicity of it in comparison to more advanced systems out there. </p>
<p>The moment I finished this emulator, I knew I had to share it with other people by providing an in-depth, step-by-step guide to creating it yourself. The knowledge I gained, and hopefully you've gained, will no doubt prove useful elsewhere.</p>
<p>All in all, I hope you enjoyed the article and learned something. I aimed to explain everything in detail and in as simple of a way as possible. </p>
<p>Regardless, if anything is still confusing you or you just have a question, please feel free to let me know over on <a target="_blank" href="https://twitter.com/ericgrandt">Twitter</a> or post an issue on the <a target="_blank" href="https://github.com/Erigitic/chip8-emulator/issues">GitHub repo</a> as I'd love to help you out.</p>
<p>I'd like to leave you with a couple of ideas on features you can add to your Chip-8 emulator:</p>
<ul>
<li>Audio control (mute, change frequency, change wave type (sine, triangle), etc)</li>
<li>Ability to change render scale and emulator speed from the UI</li>
<li>Pause and unpause</li>
<li>Ability to save and load a save</li>
<li>ROM selection</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How does String.padStart actually work? ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough Previously, I shared my usage of padStart to elegantly replace what would’ve been loads of if statements. This magical method threw me off my rocker. I simply couldn’t believe it existed. What it does Mozilla Developer Network (MDN... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-does-string-padstart-actually-work-abba34d982e/</link>
                <guid isPermaLink="false">66d461957df3a1f32ee7f8be</guid>
                
                    <category>
                        <![CDATA[ binary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ bitwise ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 31 Dec 2017 20:40:59 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*jANUTARhf9DaSPo_FdobsQ.gif" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p><a target="_blank" href="https://medium.com/@yazeedb/youtube-durations-in-4-lines-of-javascript-e9a92cea67a4">Previously</a>, I shared my usage of <code>padStart</code> to elegantly replace what would’ve been loads of <code>if</code> statements. This magical method threw me off my rocker. I simply couldn’t believe it existed.</p>
<h3 id="heading-what-it-does">What it does</h3>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart">Mozilla Developer Network (MDN) Docs</a>:</p>
<blockquote>
<p>The <code>padStart()</code> method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.</p>
</blockquote>
<p>Keep <strong>prepending a string</strong> to <strong>another string</strong> until the <strong>target length</strong> is met.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*XgjBHs6faLKurpx6WOxmaQ.png" alt="1*XgjBHs6faLKurpx6WOxmaQ" width="1264" height="278" loading="lazy"><img src="https://cdn-media-1.freecodecamp.org/images/1*kvWWV9-Le3akATlMGLFIUA.png" alt="1*kvWWV9-Le3akATlMGLFIUA" width="1236" height="532" loading="lazy"></p>
<p>If the length is already less than the original string’s length, nothing happens.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*tmVv1tdy9Ye099ca2YBD4w.png" alt="1*tmVv1tdy9Ye099ca2YBD4w" width="1164" height="276" loading="lazy"></p>
<p>And since <code>padStart</code> returns a string, we can chain its methods.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*LhQzpSiSSlvTDkcHyL8HtA.png" alt="1*LhQzpSiSSlvTDkcHyL8HtA" width="1064" height="374" loading="lazy"></p>
<p>See? 1, 2, 3, 4, and 5 are all less than or equal to <code>world</code>'s length of 5, so <code>padStart</code> doesn’t do anything.</p>
<h3 id="heading-browser-support">Browser support</h3>
<p>Unfortunately, support’s currently “meh”</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OsJkuMt7gxC407zlxv1Imw.png" alt="1*OsJkuMt7gxC407zlxv1Imw" width="1060" height="348" loading="lazy">Desktop support<img src="https://cdn-media-1.freecodecamp.org/images/1*dtwqtBR1j9vDDi2AkpP61Q.png" alt="1*dtwqtBR1j9vDDi2AkpP61Q" width="1260" height="394" loading="lazy">Mobile support</p>
<p>You can either use <a target="_blank" href="http://babeljs.io/#polyfill">babel-polyfill</a> or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart#Polyfill">the polyfill by MDN</a>.</p>
<p>Here’s MDN’s polyfill.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Zf4kxLLpi3CsYN94Nl4axQ.png" alt="1*Zf4kxLLpi3CsYN94Nl4axQ" width="1600" height="753" loading="lazy"></p>
<h3 id="heading-some-points-of-interest">Some points of interest:</h3>
<ul>
<li><strong>Prototypes</strong> (lines 1 and 2)</li>
<li><strong>Bitwise operators</strong> (line 4)</li>
<li><code>padString.repeat</code> (line 14)</li>
<li><code>padString.slice</code> (line 17)</li>
</ul>
<p>I’m down to step through them if you are ?</p>
<p>Lines 1 and 2 aren’t that bad: “If <code>padStart</code> isn’t supported by the browser, let’s create our own <code>padStart</code> and add it” (that’s polyfill-ing in a nutshell).</p>
<p>A common way to check a method’s browser support is to inspect its object’s prototype. Since <code>padStart</code> is a string method, it should exist on <code>String.prototype</code>.</p>
<p>My old version of Safari doesn’t support <code>padStart</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*8zmT7mTVUn2Q4MqunHXicg.png" alt="1*8zmT7mTVUn2Q4MqunHXicg" width="1306" height="338" loading="lazy">My Safari’s padStart support</p>
<p>But my Chrome and Firefox do.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*paNRJ_6YQ9ThHHxkwEpZwA.png" alt="1*paNRJ_6YQ9ThHHxkwEpZwA" width="1360" height="322" loading="lazy">Chrome padStart support<img src="https://cdn-media-1.freecodecamp.org/images/1*jn3Exskqn_8EAQORGs_FKg.png" alt="1*jn3Exskqn_8EAQORGs_FKg" width="804" height="204" loading="lazy">Firefox padStart support</p>
<p>Consider this safety check on line 1</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">String</span>.prototype.padStart) {
}
</code></pre>
<p>That <code>if</code> statement would only return <code>true</code> in my old Safari. It returns <code>false</code> in Chrome/Firefox, so no polyfill-ing happens.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Zf4kxLLpi3CsYN94Nl4axQ.png" alt="1*Zf4kxLLpi3CsYN94Nl4axQ" width="1600" height="753" loading="lazy"></p>
<p>Moving on, line 2 creates a new function called <code>padStart</code> and assigns it to <code>String.prototype.padStart</code>. Because of JavaScript’s inheritance model, any string created afterwards can use <code>padStart</code>.</p>
<p>This function takes two parameters</p>
<p>1. <code>targetLength</code>: How long should the resulting string be?</p>
<p>2. <code>padString</code>: What are we padding it with?</p>
<p>Let’s shower this code with <code>debugger</code> statements.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ttFL0luCSlQzdyOh-lpzOA.png" alt="1*ttFL0luCSlQzdyOh-lpzOA" width="1600" height="1175" loading="lazy"></p>
<p>I also removed that <code>if</code> statement from line 1, so even the native <code>String.prototype.padStart</code> will be overridden by this function–makes it useful if you want to debug in Chrome.</p>
<p><strong><em>Don’t override prototypes in production, kids!</em></strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*srYXzRnU1Qt46J3x91vKjQ.png" alt="1*srYXzRnU1Qt46J3x91vKjQ" width="599" height="331" loading="lazy"></p>
<p>Using our initial example</p>
<pre><code class="lang-js"><span class="hljs-string">'world'</span>.padStart(<span class="hljs-number">11</span>, <span class="hljs-string">'hello '</span>);
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*lFrlt-xxEwyByiesDNqHpw.png" alt="1*lFrlt-xxEwyByiesDNqHpw" width="1600" height="509" loading="lazy"></p>
<p>Check out line 2. We see that <code>targetLength</code> and <code>padString</code> made their way into our function. No craziness yet, but it’s coming. I’ve been avoiding line 5 long enough.</p>
<h3 id="heading-bitwise-operators">Bitwise operators</h3>
<p>The comment above line 5 briefly describes its purpose: “If <code>targetLength</code> is a number, round it down. If it’s not a number, make it 0”.</p>
<p><strong>Bitwise operators</strong> make this possible.</p>
<p><code>targetLength &gt;&gt; 0;</code></p>
<p>This operator <code>&gt;&gt;</code> is known as a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Right_shift">sign-propagating right shift</a> (LOLWUT?).
You use it with two numbers</p>
<p><code>a &gt;&gt; b</code></p>
<p><strong>What this does:</strong></p>
<ol>
<li><code>a</code> is converted into binary (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers">details here</a>).</li>
<li>Binary <code>a</code> gets <em>right-shifted</em> <code>b</code> times.</li>
</ol>
<p>Our <code>targetLength</code> is 11–that’s 1011 in binary (here’s a <a target="_blank" href="https://www.binaryhexconverter.com/binary-to-decimal-converter">converter</a> if you don’t believe me ?).</p>
<p>A side effect of converting to binary is that numbers get rounded down and <em>most</em> non-numbers become 0.</p>
<p>Try the following examples</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*G9R342JuTLzAhZ3zXB5qYw.png" alt="1*G9R342JuTLzAhZ3zXB5qYw" width="914" height="563" loading="lazy"></p>
<p>See? Fractions become whole numbers. Non-numbers become 0, with one notable exception…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*S5QRnVnjsJaP6LSR-f1yVg.png" alt="1*S5QRnVnjsJaP6LSR-f1yVg" width="914" height="231" loading="lazy"></p>
<p>Binary is just 1’s and 0’s, right? Those 1’s and 0’s represent “on” and “off” switches–<code>true</code> and <code>false</code>. <code>true</code>'s binary form is 1, and <code>false</code>'s binary form is 0. Just keep that in mind.</p>
<p>So now that we’ve “sanitized” <code>targetLength</code>, we begin the right-shifting.</p>
<p>Right-shift means you move each bit to the right <code>n</code> times. That’s it.</p>
<p>Here’s a PowerPoint visualization of <code>11 &gt;&gt; 1</code> (I forgot how great PowerPoint actually is).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*jANUTARhf9DaSPo_FdobsQ.gif" alt="1*jANUTARhf9DaSPo_FdobsQ" width="600" height="338" loading="lazy"></p>
<p>Turn 11 into 1011 and right-shift it 1 time. Your end result is 101, which is 5 in binary.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*hWhIMjgIzV8HsBHsoqaXkw.png" alt="1*hWhIMjgIzV8HsBHsoqaXkw" width="684" height="146" loading="lazy"></p>
<p>But our code says <code>targetLength &gt;&gt; 0</code>.</p>
<h3 id="heading-so-were-right-shifting-0-times">So we’re right-shifting 0 times…</h3>
<p>The whole point of right-shifting 0 times is to abuse that side effect of converting <code>targetLength</code> into binary. We don’t actually want to shift anything because that’ll change the value.</p>
<h3 id="heading-moving-on">Moving on</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*9fp5LQLp8M02XXNypggPAw.png" alt="1*9fp5LQLp8M02XXNypggPAw" width="1600" height="641" loading="lazy"></p>
<p>Jump to line 7’s <code>debugger</code> now. <code>targetLength</code> has been sanitized. <strong>Next!</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*5olkuOlk90Alu9tVfbjS9Q.png" alt="1*5olkuOlk90Alu9tVfbjS9Q" width="1600" height="592" loading="lazy"></p>
<p><strong>Line 11.</strong></p>
<pre><code class="lang-js">padString = <span class="hljs-built_in">String</span>(padString || <span class="hljs-string">' '</span>);
</code></pre>
<p>If we don’t provide a <code>padString</code> argument, it defaults to an empty space. I actually never noticed until now.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*esccGoVlxpemIBmMunjmXA.png" alt="1*esccGoVlxpemIBmMunjmXA" width="1600" height="637" loading="lazy"></p>
<p><strong>Line 17.</strong></p>
<p>Notice how line 13 had another safety check, “If the original string’s length is greater than <code>targetLength</code>, don’t do anything. Just return the original string”</p>
<p>That makes sense because if our <code>targetLength</code> is 1, but the string is already 10 characters, what’s the point? We demonstrated that earlier with</p>
<pre><code class="lang-js"><span class="hljs-comment">// just returns 'world'</span>
<span class="hljs-string">'world'</span>.padStart(<span class="hljs-number">0</span>, <span class="hljs-string">'hello '</span>);
</code></pre>
<p>Line 18 determines how many <em>more</em> characters we need by subtracting <code>targetLength</code> from the original string’s length. We need 6, in this case.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*fNa4w2qk360VICQLqvp6jQ.png" alt="1*fNa4w2qk360VICQLqvp6jQ" width="1600" height="595" loading="lazy"></p>
<p><strong>Line 27.</strong></p>
<p>We skipped that <code>if</code> statement on line 20 because <code>targetLength</code> and <code>padString.length</code> just happened to be the same, but we’ll revisit that soon.</p>
<p>For now, we’re stopped right before line 29. Let’s break it up.</p>
<pre><code class="lang-js">padString.slice(<span class="hljs-number">0</span>, targetLength);
</code></pre>
<p>The good old <code>String.prototype.slice</code> method.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice"><strong>MDN Docs</strong></a>:</p>
<blockquote>
<p>The <code>slice()</code> method extracts a section of a string and returns it as a new string.</p>
</blockquote>
<p>It’s index-based, so we’re starting at index 0 of <code>padString</code>, and grabbing the amount of characters equal to <code>targetLength</code>. It’s kind of like</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*5fgldncMrn1M42TDNexc5w.png" alt="1*5fgldncMrn1M42TDNexc5w" width="862" height="790" loading="lazy"></p>
<p>Return that sliced <code>padString</code> combined with the original string, and you’re done!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*dPcP4geY5bM3H_Qu53rF3Q.png" alt="1*dPcP4geY5bM3H_Qu53rF3Q" width="1250" height="146" loading="lazy"></p>
<h3 id="heading-almost-done"><em>Almost</em> done</h3>
<p>I’d normally conclude here, but we haven’t explored that <code>if</code> statement on line 20. To make sure we hit it this time, let’s try another earlier example</p>
<pre><code class="lang-js"><span class="hljs-string">'yo'</span>.padStart(<span class="hljs-number">20</span>, <span class="hljs-string">'yo'</span>);
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*xMe4-5cz9E4TcaxRV-OpCw.png" alt="1*xMe4-5cz9E4TcaxRV-OpCw" width="1600" height="395" loading="lazy"></p>
<p>I skipped to line 20 because we already know what happens up to this point.</p>
<p><code>if (targetLength &gt; padString.length)</code></p>
<p><code>targetLength</code> is 18, and <code>padString</code> is <code>'yo'</code>, with 2 as its length.
18 &gt; 2, so what next?</p>
<pre><code class="lang-js">padString += padString.repeat(targetLength / padString.length);
</code></pre>
<p>Remember, <code>padStart</code> returns a <em>sliced</em> <code>padString</code> + original string. If you want to pad <code>'yo'</code> with <code>'yo'</code> until it’s 20 characters long, you’ll have to repeat many times. This is where that logic happens, using <code>padString.repeat</code>.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat"><strong>MDN Docs</strong></a>:</p>
<blockquote>
<p>The <code>repeat()</code> method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.</p>
</blockquote>
<p>So it copy/pastes the string <code>n</code> times.</p>
<p>In order to find out how many repeats we need, divide <code>targetLength</code> by <code>padString.length</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*8uNfkR56h7AhooHJILFSJQ.png" alt="1*8uNfkR56h7AhooHJILFSJQ" width="902" height="142" loading="lazy"></p>
<p>Repeat <code>'yo'</code> 9 times and get a string of <code>'yo'</code>s that is 18 characters long. Add that to your original <code>'yo'</code>, and your final count is 20 characters.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*0A9siQbKWnKn6cFuidfNMQ.png" alt="1*0A9siQbKWnKn6cFuidfNMQ" width="1284" height="408" loading="lazy"></p>
<p>Mission accomplished. Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
