<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cassy Cassy on Medium]]></title>
        <description><![CDATA[Stories by Cassy Cassy on Medium]]></description>
        <link>https://medium.com/@cassycassy?source=rss-3a908956a602------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MycUZtpWNF8Ckkee.</url>
            <title>Stories by Cassy Cassy on Medium</title>
            <link>https://medium.com/@cassycassy?source=rss-3a908956a602------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 00:17:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cassycassy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What’s Reason switch from Node.js to Golang]]></title>
            <link>https://medium.com/@cassycassy/whats-reason-switch-from-node-js-to-golang-246e49468ffe?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/246e49468ffe</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Tue, 25 Oct 2016 02:55:00 GMT</pubDate>
            <atom:updated>2016-10-25T02:55:00.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3IS7ec1H3eUO-JNZalmM2A.png" /></figure><p>I’ve dabbled in JavaScript since college, made a few web pages here and there and while JS was always an enjoyable break from C or Java, I regarded it as a fairly limited language, imbued with the special purpose of serving up animations and pretty little things to make users go “ooh” and “aah”. It was the first language I taught anyone who wanted to learn how to code because it was simple enough to pick up and would quickly deliver tangible results to the developer. Smash it together with some HTML and CSS and you have a web page. Beginner programmers love that stuff.</p><p>Then something happened two years ago. At that time, I was in a researchy position working mostly on server-side code and app prototypes for Android. It wasn’t long before Node.js popped up on my radar. Backend JavaScript? Who would take that seriously? At best, it seemed like a new attempt to make server-side development easier at the cost of performance, scalability, etc. Maybe it’s just my ingrained developer skepticism, but there’s always been that alarm that goes off in my brain when I read about something being fast and easy and production-level.</p><p>Then came the research, the testimonials, the tutorials, the side-projects and 6 months later I realized I had been doing nothing <em>but</em> Node since I first read about it. It was just too easy, especially since I was in the business of prototyping new ideas every couple months. But Node wasn’t just for prototypes and pet projects. Even big boy companies like Netflix had parts of their stack running Node. Suddenly, the world was full of nails and I had found my hammer.</p><p>Fast forward another couple months and I’m at my current job as a backend developer for <a href="http://www.digg.com/">Digg</a>. When I joined, back in April of 2015, the stack at Digg was primarily Python with the exception of two services written in, wait for it, Node. I was even more thrilled to be assigned the task of reworking one of the services which had been causing issues in our pipeline.</p><p>Our troublesome Node service had a fairly straightforward purpose. Digg uses Amazon S3 for storage which is peachy, except S3 has no support for batch GET operations. Rather than putting all the onus on our Python web server to request up to 100+ keys at a time from S3, the decision was made to take advantage of Node’s easy async code patterns and great concurrency handling. And so Octo, the S3 content fetching service, was born.</p><p>Node Octo performed well except for when it didn’t. Once a day it needed to handle a traffic spike where the requests per minute jump from 50 to 200+. Also keep in mind that for each request, Octo typically fetches somewhere between 10–100 keys from S3. That’s potentially 20,000 S3 GETs a minute. The logs showed that our service slowed down substantially during these spikes, but the trouble was it didn’t always recover. As such, we were stuck bouncing our EC2 instances every couple weeks after Octo would seize up and fall flat on its face.</p><p>The requests to the service also pass along a strict timeout value. After the clock hits X number of milliseconds since receiving the request, Octo is supposed to return to the client whatever it has successfully fetched from S3 and move on. However, even with a max timeout of 1200ms, in Octo’s worst moments we had request handling times spiking up to 10 seconds.</p><p>The code was heavily asynchronous and we were caching S3 key values aggressively. Octo was also running across 2 medium EC2 instances which we bumped up to 4.</p><p>I reworked the code three times, digging deeper than ever into Node optimizations, gotchas, and tricks for squeezing every last bit of performance out of it. I reviewed benchmarks for popular Node webserver frameworks, like Express or Hapi, vs. Node’s built-in HTTP module. I removed any third party modules that, while nice to have, slowed down code execution. The result was three, one-off iterations all suffering from the same issue. No matter how hard I tried, I couldn’t get Octo to timeout properly and I couldn’t reduce the slow down during request spikes.</p><p>A theory eventually emerged and it had to do with the way Node’s event loop works. If you don’t know about the event loop, here’s some insight from <a href="https://nodesource.com/blog/understanding-the-nodejs-event-loop/">Node Source</a>:</p><blockquote><em>Node’s “event loop” is central to being able to handle high throughput scenarios. It is a magical place filled with unicorns and rainbows, and is the reason Node can essentially be “single threaded” while still allowing an arbitrary number of operations to be handled in the background.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Pkw8JVov6EZOuwlY.png" /></figure><p>You can see when all the unicorns and rainbows went to hell and back again as we bounced the service.</p><p>With event loop blocking as the biggest culprit on my list, it was just a matter of figuring why it was getting so backed up in the first place.</p><p>Most developers have heard about Node’s non-blocking I/O model; it’s great because it means all requests are handled asynchronously without blocking execution, or incurring any overhead (like with threads and processes) and as the developer you can be blissfully unaware what’s happening in the backend. However, it’s always important to keep in mind that Node is single-threaded which means none of your code runs in parallel. I/O may not block the server but your code certainly does. If I call sleep for 5 seconds, my server will be unresponsive during that time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RqPG6TvauNyeIenn.png" /></figure><p>Visualizing the Event Loop — <a href="https://strongloop.com/strongblog/node-js-performance-event-loop-monitoring/">StrongLoop</a></p><p>And the non-blocking code? As requests are processed and events are triggered, messages are queued along with their respective callback functions. To explain further, here’s an excerpt from a particularly insightful <a href="http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/">blog post from Carbon Five</a>:</p><blockquote><em>In a loop, the queue is polled for the next message (each poll<br>referred to as a “tick”) and when a message is encountered, the<br>callback for that message is executed. The calling of this callback<br>function serves as the initial frame in the call stack, and due to<br>JavaScript being single-threaded, further message polling and<br>processing is halted pending the return of all calls on the stack.<br>Subsequent (synchronous) function calls add new call frames to the<br>stack…</em></blockquote><p>Our Node service may have handled incoming requests like champ if all it needed to do was return immediately available data. But instead it was waiting on a ton of nested callbacks all dependent on responses from S3 (which can be god awful slow at times). Consequently, when any request timeouts happened, the event and its associated callback was put on an already overloaded message queue. While the timeout event might occur at 1 second, the callback wasn’t getting processed until all other messages currently on the queue, and their corresponding callback code, were finished executing (potentially seconds later). I can only imagine the state of our stack during the request spikes. In fact, I didn’t need to imagine it. A little bit of CPU profiling gave us a pretty vivid picture. Sorry for all the scrolling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*oBMsQXlqWz7uonbn.png" /></figure><p>As a quick intro to flame graphs, the y axis represents the number of frames on the stack, where each function is the parent of the function above it. The x axis has to do with the sample population more so than the passage of time. It’s the width of the boxes which show the total time on-CPU; greater width may indicate slower functions or it may simply mean that the function is called more often. You can see in Octo’s flame graph the huge spikes in our stack depth. More detailed info on profiling and flame graphs can be found <a href="http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html">here</a>.</p><p>In light of these realizations, it was time to entertain the idea that maybe Node.js wasn’t the perfect candidate for the job. My CTO and I sat down and had a chat about our options. We certainly didn’t want to continue bouncing Octo every other week and we were both very interested in a promising case study that had cropped up on the internet: <a href="http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/">Handling 1 Million Requests per Minute with Go</a></p><p>If the title wasn’t tantalizing enough, the topic was on creating a service for making PUT requests to S3 (wow, other people have these problems too?). It wasn’t the first time we had talked about using Golang somewhere in our stack and now we had a perfect test subject.</p><p>Two weeks later, after my initial crash course introduction to Golang, we had a brand new Octo service up and running. I modeled it closely after the inspiring solution outlined in <a href="https://www.malwarebytes.org/">Malwarebyte’s</a> Golang article; the service has a worker pool and a delegator which passes off incoming jobs to idle workers. Each worker runs on its own goroutine, and returns to the pool once the job is done. Simple and effective. The immediate results were pretty spectacular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*kWcVsopbfXzFYuKt.png" /></figure><p>Our average response time from the service was almost cut in half, our timeouts (in the scenario that S3 was slow to respond) were happening on time, and our traffic spikes had minimal effects on the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*_Jw3dTaiaNFCGw28.png" /></figure><p>Blue = Node.js Octo | Green = Golang Octo</p><p>With our Golang upgrade, we are easily able to handle 200 requests per minute and 1.5 million S3 item fetches per day. And those 4 load-balanced instances we were running Octo on initially? We’re now doing it with 2.</p><p>Since our transition to Golang we haven’t looked back. While the majority of our stack is (and probably will always be) in Python, we’ve begun the process of modularizing our code base and spinning up microservices to handle specific roles in our system. Alongside Octo, we now have 3 other Golang services in production which power our realtime message system and serve up important metadata for our content. We’re also very proud of the newest addition to our Golang codebase, <a href="http://digg.com/diggbot">DiggBot</a>.</p><p>This is not to say that Golang is a silver bullet for all our problems. We’re careful to consider the needs of each of our services. As a company, we make the effort to stay on top of new and emerging technologies and to always ask ourselves, can we be doing this better? It’s a constantly evolving process and one that takes careful research and planning.</p><p>I’m proud to say that this story has a happy ending as our Octo service has been up and running for a couple months with great success (a few bug fixes aside). For now, Digg is going the way of the Gopher.</p><p>“_This article was originally published on <a href="https://medium.com/@theflapjack103/the-way-of-the-gopher-6693db15ae1f#.8kn0wbrtp">Medium</a> by <a href="https://twitter.com/TheFlapjack103">Alexandra Grant</a></p><h3>Suggest</h3><p>☞ <a href="https://school.codequs.com/p/HkOSdfyY">Google Go Programming for Beginners (Golang)</a></p><p>☞ <a href="https://school.codequs.com/p/rJxyQ9HF">Beginners : Google’s Go (golang) Programming Language</a></p><p>☞ <a href="https://school.codequs.com/p/S1lGQqHt">Learn Google Go — Golang Programming for Beginners</a></p><p>☞ <a href="https://school.codequs.com/p/ByN5z5rt">The Go Programming Language Guide: Code Like a Pro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246e49468ffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Tutorial for Absolute Beginners [New]]]></title>
            <link>https://medium.com/@cassycassy/c-tutorial-for-absolute-beginners-new-79e60d8f7b8f?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e60d8f7b8f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-program]]></category>
            <category><![CDATA[c-programming-language]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Mon, 24 Oct 2016 01:51:48 GMT</pubDate>
            <atom:updated>2016-10-24T01:51:48.995Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaJJCnVmQyk4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaJJCnVmQyk4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaJJCnVmQyk4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23b6bbd2f79508c34c152fce372dd50/href">https://medium.com/media/f23b6bbd2f79508c34c152fce372dd50/href</a></iframe><p>Want to learn a different programming language? C# is a great place to start. Step through 24 practical and easy-to-understand C# training episodes, with our talented friend Bob Tabor, from Developer University, as he teaches you the fundamentals of C# programming. Tune in to learn the basics of the C# language, and learn to apply them in your programming endeavors, like video games, mobile environments, and client apps.</p><p>Learn C# by stepping through the basics with Bob: get the tools, see how to write code, debug features, explore customizations, and much more! Search for and focus on the information you need, in this C# for beginners course, which has topics separated out into individual videos. Get to know the grammar, create and use methods, manipulate strings, and see how to handle events. Plus, get a look at next steps as you learn to develop Windows and web applications.</p><p>1 | Course Introduction<br>Hear an introduction to the topic, learn expectations for the series, and hear tips on how to get the most out of it. Plus, find out where to download the software you need.</p><p>2 | Installing Visual Studio<br>Get the details on installing Visual Studio.</p><p>3 | Creating Your First C# Program<br>Learn how to create a simple application, and get an explanation of common solutions to different problems you might encounter as you begin writing and compiling code.</p><p>4 | Understanding Your First C# Program<br>To better understand the grammar of C# at a high level, return to the program we just built to break apart each of the key words and symbols.</p><p>5 | Working with Code Files, Projects, and Solutions<br>Learn how to open and close individual files in a project, the relationship between projects and solutions, and more.</p><p>6 | Understanding Data Types and Variables<br>Add C# syntax to your vocabulary by exploring fundamental building blocks: data types and variables. In addition, learn about basic topics, such as naming conventions and data type conversions.</p><p>7 | The if Decision Statement<br>Get an introduction to the if Decision statement, along with the conditional operator. Find out how to refactor code to make it more compact and less likely to produce errors.</p><p>8 | Operators, Expressions, and Statements<br>Learn how to create a properly formed C# statement made up of expressions that include operators and operands. Hear about compilation errors that occur when the syntax rules of C# are ignored.</p><p>9 | for Iteration Statement<br>Look at several different types of iteration statements, how to utilize “code snippets” to help remind you of the syntax for this complex statement, and debugging in action.</p><p>10 | Understanding Arrays<br>Learn about arrays, and see how to declare and utilize arrays. Watch demos on a couple of powerful built-in methods that give arrays added features.</p><p>11 | Defining and Calling Methods<br>Create a helper method, create and call methods to retrieve a value, create and use input parameters, learn about string formatting, and create overloaded methods.</p><p>12 | While Iteration Statement<br>Learn a new iteration statement that allows you to continue performing a block of code until a condition is no longer true.</p><p>13 | Working with Strings<br>Look at built-in String methods to manipulate the content inside of a literal string and at the StringBuilder class for concatenating many strings together in a memory- and resource-friendly manner.</p><p>14 | Working with Dates and Times<br>Find out how to work with Date and Time data, how to create new instances of DateTime, how to add time, and how to format the data for display. Take a look at the TimeSpan class.</p><p>15 | Understanding Classes<br>Learn how classes are defined and new instances are created, how to define Properties, and how to both set values and get values for a given instance of the class.</p><p>16 | More About Classes and Methods<br>Dig into more details about classes: create a new instance, add class references, pass the reference to a method. Plus, review overloaded methods, static versus instance methods, and constructors.</p><p>17 | Understanding Scope and Accessibility Modifiers<br>Explore variable scope and how accessibility modifiers are used by the .NET Framework Class Library to expose or hide implementation of their given services to consumers of that given class.</p><p>18 | Understanding Namespaces and Working with the .NET Class Library<br>Learn about namespaces and how to find the classes for your applications by searching Bing and MSDN.</p><p>19 | Creating and Adding References to Assemblies<br>Learn about .NET assemblies: code libraries and executables, debug and release versions of assemblies. Plus, see how to reference assemblies, utilize NuGet, and create references to custom libraries.</p><p>20 | Working with Collections<br>See an “old style” collection, along with several of the newer, strongly typed generic collections (List and Dictionary) utilizing the generics syntax.</p><p>21 | Working with LINQ<br>Explore Structured Query Language and the LINQ syntax. See a demo projecting data onto existing types and new anonymous types.</p><p>22 | Enumerations and the Switch Decision Statement<br>See a demo on the use of Enumerations, create a custom enumeration, and then use it in a simple application that demonstrates a third Decision statement, the switch.</p><p>23 | Gracefully Handling Exceptions<br>Learn how to use the try catch finally block to anticipate potential problems so as to shield the end user from those problems as much as possible. Explore best practices when checking for exceptions.</p><p>24 | Understanding Events and Event-Driven Programming<br>Learn how events are utilized in the .NET Framework Class Library. Begin with the Timer class, and graduate to building a basic “Hello world” application.</p><p>25 | Where to Go from Here<br>Hear approaches to solving common issues, where to go for help, how to search for answers, and become part of the .NET community. View a long-term path to learn more about developing applications.</p><h3>Learn</h3><pre>Learn how to declare and utilize arrays.<br>Create and use methods.<br>Use iteration statements.<br>Manipulate strings.<br>Learn how to work with Date and Time data.<br>Define and create classes and use properties.<br>Apply more advanced class details.<br>Contrast variable scope and accessiblity modifiers.<br>Find and use namespaces.<br>Create and reference assemblies.<br>See how to use collections.<br>Learn when and how to use LINQ.<br>Use enumerations.<br>Prevent exceptions.<br>See a demo on how to handle events.<br>Explore next steps to learn more about developing Windows and web applications.<br>Understand course expectations, and obtain software.<br>Create an application.<br>Understand C# grammar.<br>Discover the relationship between projects and solutions.<br>Learn the fundamental building blocks of working with C#.<br>Use if Decision statements and the conditional operator.<br>Create a properly formed C# statement, and resolve compilation errors.<br>Understand iteration statements and when to use them.<br>See a demo on how to declare and utilize arrays.<br>Create and use methods.<br>Use iteration statements.<br>Manipulate strings.<br>Learn how to work with Date and Time data.<br>Define and create classes and use properties.<br>Use if Decision statements and the conditional operator.<br>See a demo on how to declare and utilize arrays.<br>Install Visual Studio.</pre><p><strong>If you found this post interesting, follow and support us.<br>Suggest for you:</strong></p><p>☞<a href="https://codequs.com/a/ryRrOxc6">C and C++ Programming : Step-by-Step Tutorial</a></p><p>☞<a href="https://codequs.com/a/BJsyLOWs">Learn C programming: C language</a></p><p>☞<a href="https://codequs.com/a/H1ok21TO"><em>Learn to Program with C++</em></a></p><p>☞<a href="https://codequs.com/a/ryB1ak6u">Object Oriented Programming with C++</a></p><p>☞<a href="https://codequs.com/a/HyUdpyad">Advanced C++ Programming Training Course</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e60d8f7b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a JavaScript 3D Minecraft Editor?]]></title>
            <link>https://medium.com/@cassycassy/how-to-build-a-javascript-3d-minecraft-editor-d4db1fba9b94?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4db1fba9b94</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Thu, 20 Oct 2016 02:45:14 GMT</pubDate>
            <atom:updated>2016-10-20T02:45:14.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTlNC0-ww5BfWX2fcPzkaQ.jpeg" /></figure><p>I’ve always wanted to build a 3D game. I’ve just never had the time and energy to learn the intricacies of 3D programming. Then I discovered I didn’t need to…</p><p>While tinkering one day, I got to thinking that maybe I could simulate a 3D environment using CSS transformations. I stumbled across an old article about creating 3D worlds with HTML and CSS.</p><p>I wanted to simulate a Minecraft world (or a tiny part of it at least). Minecraft is a sandbox game, in which you can break and place blocks. I wanted the same kind of functionality, but with HTML, <a href="https://codequs.com/a/ryMLq9dd">JavaScript</a>, and CSS.</p><p>Come along as I describe what I learned, and how it can help you to be more creative with your CSS transformations!</p><p><strong>Note:</strong> Most of the code for this tutorial can be found <a href="https://github.com/assertchris-tutorials/tutorial-javascript-minecraft-editor/">on Github</a>. I’ve tested it in the latest version of Chrome. I can’t promise it will look exactly the same in other browsers, but the core concepts are universal.</p><p><em>This is just half of the adventure. If you’d like to know how to persist the designs to an actual server, check out the sister post, PHP Minecraft Mod. There we explore ways to interact with a Minecraft server, to manipulate it in real time and respond to user input.</em></p><h3>The Things We’re Already Doing</h3><p>I’ve written my fair share of <a href="https://codequs.com/a/Hy3CJR7i">CSS</a> and I’ve come to understand it quite well, for the purpose of building websites. But that understanding is predicated on the assumption that I’m going to be working in a 2D space.</p><p>Let’s consider an example:</p><pre>.tools {<br>      position: absolute;<br>      left: 35px;<br>      top: 25px;<br>      width: 200px;<br>      height: 400px;<br>      z-index: 3;<br>    }</pre><pre>    .canvas {<br>      position: absolute;<br>      left: 0;<br>      top: 0;<br>      width: 100%;<br>      height: 100%;<br>      z-index: 2;<br>    }</pre><p>Here we have a canvas element, starting at the top left corner of the page, and stretching all the way to the bottom right. On top of that, we’re adding a tools element. It starts 25px from the left and 35px from the top of the page, and measures 200px wide by 400px high.</p><p>Depending on the order div.tools and div.canvas are added to the markup, it’s entirely possible that div.canvascould overlap div.tools. That is except for the z-index styles applied to each.</p><p>You’re probably used to thinking of elements, styled in this way, as 2D surfaces with the potential to overlap each other. But that overlapping is essentially a third dimension. left, top, and z-index may as well be renamed to x,y, and z. So long as we assume every element has a fixed depth of 1px, and z-index has an implicit px unit, we’re already thinking in 3D terms.</p><p>What some of us tend to struggle with are the concepts of rotation and translation in this third dimension…</p><h3>The Theory of Transformations</h3><p>CSS translations duplicate this familiar functionality, in an API that extends beyond the limitations top, left, and z-index place on us. It’s possible to replace some of our previous styles with translations:</p><pre>.tools {<br>      position: absolute;<br>      background: green;<br>      /*<br>        left: 35px;<br>        top: 25px;<br>      */<br>      transform-origin: 0 0;<br>      transform: translate(35px, 25px);<br>      width: 200px;<br>      height: 400px;<br>      z-index: 3;<br>    }</pre><p>Instead of defining left and top offsets (with an assumed origin of 0px from the left and 0px from the top), we can declare an explicit origin. We can perform all sorts of transformations on this element, for which use 0 0 as the centre. translate(35px, 25px) moves the element 35px to the right and 25px down. We can use negative values to move the element left and/or up.</p><p>With the ability to define an origin for our transformations, we can start to do other interesting things as well. For example, we can rotate and scale elements:</p><pre>transform-origin: center;<br>    transform: scale(0.5) rotate(45deg);</pre><p>Every element starts with a default transform-origin of 50% 50% 0, but a value of center sets x, y, and z to the equivalent of 50%. We can scale our element to a value between 0 and 1, and rotate it (clockwise) by degrees or radians. And we can convert between the two with:</p><ul><li>45deg = (45 * Math.PI) / 180 ≅ 0.79rad</li><li>0.79rad = (0.79 * 180) / Math.PI ≅ 45deg</li></ul><p>To rotate an element anti-clockwise, we just need to use a negative deg or rad value.</p><p>What’s even more interesting, about these transformations, is that we can use 3D versions of them.</p><p>Evergreen browsers have pretty good support for these styles, though they may require vendor prefixes. CodePen has a neat “autoprefix” option, but you can add libraries like PostCSS to your local code to achieve the same thing.</p><h3>The First Block</h3><p>Let’s begin to create our 3D world. We’ll start by making a space in which to place our blocks. Create a new file, called index.html:</p><pre>&lt;!doctype html&gt;<br>    &lt;html&gt;<br>      &lt;head&gt;<br>        &lt;style&gt;<br>          html, body {<br>            padding: 0;<br>            margin: 0;<br>            width: 100%;<br>            height: 100%;<br>          }</pre><pre>          .scene {<br>            position: absolute;<br>            left: 50%;<br>            top: 50%;<br>            margin: -192px 0 0 -192px;<br>            width: 384px;<br>            height: 384px;<br>            background: rgba(100, 100, 255, 0.2);<br>            transform: rotateX(60deg) rotateZ(60deg);<br>            transform-style: preserve-3d;<br>            transform-origin: 50% 50% 50%;<br>          }<br>        &lt;/style&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;<br>        &lt;div class=&quot;scene&quot;&gt;&lt;/div&gt;<br>        &lt;script src=&quot;https://code.jquery.com/jquery-3.1.0.slim.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;script src=&quot;http://ricostacruz.com/jquery.transit/jquery.transit.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;script&gt;<br>          // TODO<br>        &lt;/script&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;</pre><p>Here we stretch the body to the full width and height, resetting padding to 0px. Then we create a smallishdiv.scene, which we’ll use to hold various blocks. We use 50% left and top, as well as a negative left and topmargin (equal to half the width and height) to horizontally and vertically centre it. Then we tilt it slightly (using 3D rotation) so that we have a perspective view of where the blocks will be.</p><p>Notice how we define transform-style:preserve-3d. This is so that child elements can also be manipulated in a 3D space.</p><p>Now, let’s start to add a block shape to the scene. We’ll need to create a new JavaScript file, called block.js:</p><pre>&quot;use strict&quot;</pre><pre>    class Block {<br>      constructor(x, y, z) {<br>        this.x = x;<br>        this.y = y;<br>        this.z = z;</pre><pre>        this.build();<br>      }</pre><pre>      build() {<br>        // TODO: build the block<br>      }</pre><pre>      createFace(type, x, y, z, rx, ry, rz) {<br>        // TODO: return a block face<br>      }</pre><pre>      createTexture(type) {<br>        // TODO: get the texture<br>      }<br>    }</pre><p>Each block needs to be a 6-sided, 3D shape. We can break the different parts of construction into methods to (1) build the whole block, (2) build each surface, and (3) get the texture of each surface.</p><p>Each of these behaviours (or methods) are contained within an ES6 class. It’s a neat way to group data structures and the methods that operate on them together. You may be familiar with the traditional form:</p><pre>function Block(x, y, z) {<br>      this.x = x;<br>      this.y = y;<br>      this.z = z;</pre><pre>      this.build();<br>    }</pre><pre>    var proto = Block.prototype;</pre><pre>    proto.build = function() {<br>      // TODO: build the block<br>    };</pre><pre>    proto.createFace = function(type, x, y, z, rx, ry, rz) {<br>      // TODO: return a block face<br>    }</pre><pre>    proto.createTexture = function(type) {<br>      // TODO: get the texture<br>    }</pre><p>This may look a little different, but it’s much the same. In addition to shorter syntax, ES6 classes also provide shortcuts for extending prototypes and calling overridden methods. But I digress…</p><p>Let’s work from the bottom up:</p><pre>createFace(type, x, y, z, rx, ry, rz) {<br>      return $(`&lt;div class=&quot;side side-${type}&quot; &gt;&lt;/div&gt;`)<br>        .css({<br>          transform: `<br>            translateX(${x}px)<br>            translateY(${y}px)<br>            translateZ(${z}px)<br>            rotateX(${rx}deg)<br>            rotateY(${ry}deg)<br>            rotateZ(${rz}deg)<br>          `,<br>          background: this.createTexture(type)<br>        });<br>    }</pre><pre>    createTexture(type) {<br>      return `rgba(100, 100, 255, 0.2)`;<br>    }</pre><p>Each surface (or face) consists of a rotated and translated div. We can’t make elements thicker than 1px, but we can simulate depth by covering up all the holes and using multiple elements parallel to each other. We can give the block the illusion of depth, even though it is hollow.</p><p>To that end, the createFace method takes a set of coordinates: x, y, and z for the position of the face. We also provide rotations for each axis, so that we can call createFace with any configuration and it will translate and rotate the face just how we want it to.</p><p>Let’s build the basic shape:</p><pre>build() {<br>      const size = 64;<br>      const x = this.x * size;<br>      const y = this.y * size;<br>      const z = this.z * size;</pre><pre>      const block = this.block = $(`&lt;div class=&quot;block&quot; &gt;&lt;/div&gt;`)<br>        .css({<br>          transform: `<br>            translateX(${x}px)<br>            translateY(${y}px)<br>            translateZ(${z}px)<br>          `<br>        });</pre><pre>      $(`&lt;div class=&quot;x-axis&quot; &gt;&lt;/div&gt;`)<br>        .appendTo(block)<br>        .css({<br>          transform: `<br>            rotateX(90deg)<br>            rotateY(0deg)<br>            rotateZ(0deg)<br>          `<br>        });</pre><pre>      $(`&lt;div class=&quot;y-axis&quot; &gt;&lt;/div&gt;`)<br>        .appendTo(block)<br>        .css({<br>          transform: `<br>            rotateX(0deg)<br>            rotateY(90deg)<br>            rotateZ(0deg)<br>          `<br>        });</pre><pre>      $(`&lt;div class=&quot;z-axis&quot; &gt;&lt;/div&gt;`)<br>        .appendTo(block);<br>    }</pre><p>We’re used to thinking in terms of single pixel positions, but a game like Minecraft works at a larger scale. Every block is bigger, and the coordinate system deals with the position of the block, not individual pixels that make it up. I want to convey the same sort of idea here…</p><p>When someone creates a new block, at 1 × 2 × 3, I want that to mean 0px × 64px × 128px. So we multiply each coordinate by the default size (in this case 64px, because that’s the size of the textures in the texture pack we’ll be using).</p><p>Then we create a container div (which we call div.block). Inside it we place another 3 divs. These will show us the axis of our block – they’re like guides in a 3D rendering program. We should also add some new CSS for our block:</p><pre>.block {<br>      position: absolute;<br>      left: 0;<br>      top: 0;<br>      width: 64px;<br>      height: 64px;<br>      transform-style: preserve-3d;<br>      transform-origin: 50% 50% 50%;<br>    }</pre><pre>    .x-axis,<br>    .y-axis,<br>    .z-axis {<br>      position: absolute;<br>      left: 0;<br>      top: 0;<br>      width: 66px;<br>      height: 66px;<br>      transform-origin: 50% 50% 50%;<br>    }</pre><pre>    .x-axis {<br>      border: solid 2px rgba(255, 0, 0, 0.3);<br>    }</pre><pre>    .y-axis {<br>      border: solid 2px rgba(0, 255, 0, 0.3);<br>    }</pre><pre>    .z-axis {<br>      border: solid 2px rgba(0, 0, 255, 0.3);<br>    }</pre><p>This styling is similar to what we’ve seen before. We need to remember to set transform-style:preserve-3d on the.block, so that the axis are rendered in their own 3D space. We give each a different colour, and make them slightly bigger than the block they’re contained in. This is so that they’ll be visible even when the block has sides.</p><p>Let’s create a new block, and add it to the div.scene:</p><pre>let first = new Block(1, 1, 1);</pre><pre>    $(&quot;.scene&quot;).append(first.block);</pre><p>Now, let’s add those faces:</p><pre>this<br>      .createFace(&quot;top&quot;, 0, 0, size / 2, 0, 0, 0)<br>      .appendTo(block);</pre><pre>    this<br>      .createFace(&quot;side-1&quot;, 0, size / 2, 0, 270, 0, 0)<br>      .appendTo(block);</pre><pre>    this<br>      .createFace(&quot;side-2&quot;, size / 2, 0, 0, 0, 90, 0)<br>      .appendTo(block);</pre><pre>    this<br>      .createFace(&quot;side-3&quot;, 0, size / -2, 0, -270, 0, 0)<br>      .appendTo(block);</pre><pre>    this<br>      .createFace(&quot;side-4&quot;, size / -2, 0, 0, 0, -90, 0)<br>      .appendTo(block);</pre><pre>    this<br>      .createFace(&quot;bottom&quot;, 0, 0, size / -2, 0, 180, 0)<br>      .appendTo(block);</pre><p>I found this code to be a bit of trial and error (owing to my limited experience with 3D perspective). Each element starts off in exactly the same position as the div.z-axis element. That is, in the vertical centre of the div.block and facing the top.</p><p>So, for the “top” element, I had to translate it “up” by half the size of the block, but I didn’t have to rotate it in any way. For the “bottom” element, I had to rotate it 180 degrees (along the x or y axis), and move it down by half the size of the block.</p><p>Using similar thinking, I rotated and translated each of the remaining sides. I also had to add corresponding CSS for them:</p><pre>.side {<br>      position: absolute;<br>      left: 0;<br>      top: 0;<br>      width: 64px;<br>      height: 64px;<br>      backface-visibility: hidden;<br>      outline: 1px solid rgba(0, 0, 0, 0.3);<br>    }</pre><p><em>Adding </em><em>backface-visibility:hidden prevents the “bottom” side of the elements from being rendered. Usually they would just appear the same (only mirrored) no matter how they were rotated. With hidden back faces, only the “top” side is rendered. Take care when turning this on: your surfaces need to be rotated the right way around or sides of the block will just disappear. That’s the reason for the 90/270/-90/-270 rotations I’ve given the sides.</em></p><p>Let’s make this block look a bit more realistic. We need to create a new file, called block.dirt.js, and override thecreateTexture method:</p><pre>&quot;use strict&quot;</pre><pre>    const DIRT_TEXTURES = {<br>      &quot;top&quot;: [<br>        &quot;textures/dirt-top-1.png&quot;,<br>        &quot;textures/dirt-top-2.png&quot;,<br>        &quot;textures/dirt-top-3.png&quot;<br>      ],<br>      &quot;side&quot;: [<br>        &quot;textures/dirt-side-1.png&quot;,<br>        &quot;textures/dirt-side-2.png&quot;,<br>        &quot;textures/dirt-side-3.png&quot;,<br>        &quot;textures/dirt-side-4.png&quot;,<br>        &quot;textures/dirt-side-5.png&quot;<br>      ]<br>    };</pre><pre>    class Dirt extends Block {<br>      createTexture(type) {<br>        if (type === &quot;top&quot; || type === &quot;bottom&quot;) {<br>          const texture = DIRT_TEXTURES.top.random();</pre><pre>          return `url(https://medium.com/$%7Btexture%7D)`;<br>        }</pre><pre>        const texture = DIRT_TEXTURES.side.random();</pre><pre>        return `url(https://medium.com/$%7Btexture%7D)`;<br>      }<br>    }</pre><pre>    Block.Dirt = Dirt;</pre><p>We’re going to use a popular texture pack, called <a href="http://bdcraft.net/purebdcraft-minecraft">Sphax PureBDCraft</a>. It’s free to download and use (provided you’re not try to sell it on), and it comes in a variety of sizes. I’m using the x64 version.</p><p>We begin by defining a look-up table for the textures of the sides and top of the block. The texture pack doesn’t specify which textures should be used for the bottom, so we’ll just reuse the top textures.</p><p>If the side needing a texture is “top” or “bottom”, then we fetch a random texture from the “top” list. The random method doesn’t exist, until we define it:</p><pre>Array.prototype.random = function() {<br>      return this[Math.floor(Math.random() * this.length)];<br>    };</pre><p>Similarly, if we need a texture for a side, we fetch a random one. These textures are seamless, so the randomisation works in our favour.</p><h3>Making a Scene</h3><p>How do we make this interactive? Well, a good place to start is with a scene. We’ve already been placing blocks in the scene, so now we just have to enable dynamic placement!</p><p>To begin with, we can render a flat surface of blocks:</p><pre>const $scene = $(&quot;.scene&quot;);</pre><pre>    for (var x = 0; x &lt; 6; x++) {<br>      for (var y = 0; y &lt; 6; y++) {<br>        let next = new Block.Dirt(x, y, 0);<br>        next.block.appendTo($scene);<br>      }<br>    }</pre><p>Great, that gives us a flat surface to start adding blocks to. Now, let’s highlight surfaces as we hover over them with our cursor:</p><pre>.block:hover .side {<br>      outline: 1px solid rgba(0, 255, 0, 0.5);<br>    }</pre><p>Something strange is going on, though:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bn1iV4IqQrn9eWYw.gif" /></figure><p>This is because the surfaces are clipping through each other randomly. There’s no nice way to fix this problem, but we can prevent it from happening by scaling the blocks slightly:</p><pre>const block = this.block = $(`&lt;div class=&quot;block&quot; &gt;&lt;/div&gt;`)<br>      .css({<br>        transform: `<br>          translateX(${x}px)<br>          translateY(${y}px)<br>          translateZ(${z}px)<br>          scale(0.99)<br>        `<br>      });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cN22_ccj5NdLB397.gif" /></figure><p><em>While this does make things look better, it will affect performance the more blocks there are in the scene. Tread lightly when scaling many elements at a time…</em></p><p>Let’s tag each surface with the block and type that belong to it:</p><pre>createFace(type, x, y, z, rx, ry, rz) {<br>      return $(`&lt;div class=&quot;side side-${type}&quot; &gt;&lt;/div&gt;`)<br>        .css({<br>          transform: `<br>            translateX(${x}px)<br>            translateY(${y}px)<br>            translateZ(${z}px)<br>            rotateX(${rx}deg)<br>            rotateY(${ry}deg)<br>            rotateZ(${rz}deg)<br>          `,<br>          background: this.createTexture(type)<br>        })<br>        .data(&quot;block&quot;, this)<br>        .data(&quot;type&quot;, type);<br>    }</pre><p>Then, as we click on a surface, we can derive a new set of coordinates and create a new block:</p><pre>function createCoordinatesFrom(side, x, y, z) {<br>      if (side == &quot;top&quot;) {<br>        z += 1;<br>      }</pre><pre>      if (side == &quot;side-1&quot;) {<br>        y += 1;<br>      }</pre><pre>      if (side == &quot;side-2&quot;) {<br>        x += 1;<br>      }</pre><pre>      if (side == &quot;side-3&quot;) {<br>        y -= 1;<br>      }</pre><pre>      if (side == &quot;side-4&quot;) {<br>        x -= 1;<br>      }</pre><pre>      if (side == &quot;bottom&quot;) {<br>        z -= 1;<br>      }</pre><pre>      return [x, y, z];<br>    }</pre><pre>    const $body = $(&quot;body&quot;);</pre><pre>    $body.on(&quot;click&quot;, &quot;.side&quot;, function(e) {<br>      const $this = $(this);<br>      const previous = $this.data(&quot;block&quot;);</pre><pre>      const coordinates = createCoordinatesFrom(<br>        $this.data(&quot;type&quot;),<br>        previous.x,<br>        previous.y,<br>        previous.z<br>      );</pre><pre>      const next = new Block.Dirt(...coordinates);</pre><pre>      next.block.appendTo($scene);<br>    });</pre><p>createCoordinatesFrom has a simple but important task. Given the type of side, and the coordinates for the block to which it belongs, createCoordinatesFrom should return a new set of coordinates. These are where the new block will be placed.</p><p>Then we’ve attached an event listener. It will be triggered for each div.side that gets clicked. As this happens, we get the block to which the side belongs, and derive a new set of coordinates for the next block. Once we have those, we create the block and append it to the scene.</p><h3>Seeing Ghosts</h3><p>It would be helpful to see an outline of the block that we’re about to place, before we place it. This is sometimes referred to as “showing a ghost” of the thing we’re about to do.</p><p>The code to enable this is quite similar to that which we’ve already seen:</p><pre>let ghost = null;</pre><pre>    function removeGhost() {<br>      if (ghost) {<br>        ghost.block.remove();<br>        ghost = null;<br>      }<br>    }</pre><pre>    function createGhostAt(x, y, z) {<br>      const next = new Block.Dirt(x, y, z);</pre><pre>      next.block<br>        .addClass(&quot;ghost&quot;)<br>        .appendTo($scene);</pre><pre>      ghost = next;<br>    }</pre><pre>    $body.on(&quot;mouseenter&quot;, &quot;.side&quot;, function(e) {<br>      removeGhost();</pre><pre>      const $this = jQuery(this);<br>      const previous = $this.data(&quot;block&quot;);</pre><pre>      const coordinates = createCoordinatesFrom(<br>        $this.data(&quot;type&quot;),<br>        previous.x,<br>        previous.y,<br>        previous.z<br>      );</pre><pre>      createGhostAt(...coordinates);<br>    });</pre><pre>    $body.on(&quot;mouseleave&quot;, &quot;.side&quot;, function(e) {<br>      removeGhost();<br>    });</pre><p>The main difference is that we maintain a single instance of the ghost block. As each new one is created, the old one is removed. This could benefit from a few additional styles:</p><pre>.ghost {<br>      pointer-events: none;<br>    }</pre><pre>    .ghost .side {<br>      opacity: 0.6;<br>      pointer-events: none;<br>      -webkit-filter: brightness(1.5);<br>    }</pre><p>Left active, the pointer events associated with the elements of the ghost would counteract the mouseenter andmouseleave events of the side underneath. Since we don’t need to interact with the ghost elements, we can disable these pointer events.</p><h3>Changing Perspective</h3><p>The more interactivity we add, the harder it is to see what’s going on. It seems like a good time to do something about that. It’d be awesome if we could zoom and rotate the viewport, to be able to see what’s going on a little better…</p><p>Let’s start with zoom. Many interfaces (and games) allow viewport zooming by scrolling the mouse wheel. Different browsers handle mouse wheel events in different ways, so it make sense to <a href="https://github.com/jquery/jquery-mousewheel">use an abstraction library</a>.</p><p>Once that’s installed, we can hook into the events:</p><pre>let sceneTransformScale = 1;</pre><pre>    $body.on(&quot;mousewheel&quot;, function(event) {<br>      if (event.originalEvent.deltaY &gt; 0) {<br>        sceneTransformScale -= 0.05;<br>      } else {<br>        sceneTransformScale += 0.05;<br>      }</pre><pre>      $scene.css({<br>        &quot;transform&quot;: `<br>          scaleX(${sceneTransformScale})<br>          scaleY(${sceneTransformScale})<br>          scaleZ(${sceneTransformScale})<br>        `<br>      });<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JCVM4PRHyqG0nkpp.gif" /></figure><p>Now we can control the scale of the entire scene, just by scrolling the mouse wheel. Unfortunately, the moment we do, the rotations are overridden. We need to take the rotation into account, as we allow dragging the viewport with the mouse to adjust it:</p><pre>let sceneTransformX = 60;<br>    let sceneTransformY = 0;<br>    let sceneTransformZ = 60;<br>    let sceneTransformScale = 1;</pre><pre>    const changeViewport = function() {<br>      $scene.css({<br>        &quot;transform&quot;: `<br>          rotateX(${sceneTransformX}deg)<br>          rotateY(${sceneTransformY}deg)<br>          rotateZ(${sceneTransformZ}deg)<br>          scaleX(${sceneTransformScale})<br>          scaleY(${sceneTransformScale})<br>          scaleZ(${sceneTransformScale})<br>        `<br>      });<br>    };</pre><p>This function won’t only account for the scale factor of the scene, but also the x, y, and z rotations factors. We also need to change our zooming event listener:</p><pre>$body.on(&quot;mousewheel&quot;, function(event) {<br>      if (event.originalEvent.deltaY &gt; 0) {<br>        sceneTransformScale -= 0.05;<br>      } else {<br>        sceneTransformScale += 0.05;<br>      }</pre><pre>      changeViewport();<br>    });</pre><p>Now, we can start to rotate the scene. We need:</p><ol><li>An event listener for when the drag action starts</li><li>An event listener for when the mouse moves (while dragging)</li><li>An event listener for when the drag action stops</li></ol><p>Something like these should do the trick:</p><pre>Number.prototype.toInt = String.prototype.toInt = function() {<br>      return parseInt(this, 10);<br>    };</pre><pre>    let lastMouseX = null;<br>    let lastMouseY = null;</pre><pre>    $body.on(&quot;mousedown&quot;, function(e) {<br>      lastMouseX = e.clientX / 10;<br>      lastMouseY = e.clientY / 10;<br>    });</pre><pre>    $body.on(&quot;mousemove&quot;, function(e) {<br>      if (!lastMouseX) {<br>        return;<br>      }</pre><pre>      let nextMouseX = e.clientX / 10;<br>      let nextMouseY = e.clientY / 10;</pre><pre>      if (nextMouseX !== lastMouseX) {<br>        deltaX = nextMouseX.toInt() - lastMouseX.toInt();<br>        degrees = sceneTransformZ - deltaX;</pre><pre>        if (degrees &gt; 360) {<br>            degrees -= 360;<br>        }</pre><pre>        if (degrees &lt; 0) {<br>            degrees += 360;<br>        }</pre><pre>        sceneTransformZ = degrees;<br>        lastMouseX = nextMouseX;</pre><pre>        changeViewport();<br>      }</pre><pre>      if (nextMouseY !== lastMouseY) {<br>        deltaY = nextMouseY.toInt() - lastMouseY.toInt();<br>        degrees = sceneTransformX - deltaY;</pre><pre>        if (degrees &gt; 360) {<br>            degrees -= 360;<br>        }</pre><pre>        if (degrees &lt; 0) {<br>            degrees += 360;<br>        }</pre><pre>        sceneTransformX = degrees;<br>        lastMouseY = nextMouseY;</pre><pre>        changeViewport();<br>      }<br>    });</pre><pre>    $body.on(&quot;mouseup&quot;, function(e) {<br>      lastMouseX = null;<br>      lastMouseY = null;<br>    });</pre><p>On mousedown we capture the initial mouse x and y coordinates. As the mouse moves (if the button is still being pressed) we adjust the sceneTransformZ and sceneTransformX by a scaled amount. There’s no harm in letting the values go over 360 degrees or below 0 degrees, but these would look terrible if we wanted to render them onscreen.</p><p>Computation inside a mousemove event listener can be computationally expensive due to how much this even listener may be triggered. There are potentially millions of pixels on the screen, and this listener could be triggered as the mouse moves to each one. That is why we exit early if the mouse button isn’t being held down.</p><p>When the mouse button is released, we unset the lastMouseX and lastMouseY, so that the mousemove listener stops computing things. We could just clear lastMouseX, but clearing both feels cleaner to me.</p><p>Unfortunately, the mousedown event can interfere with the click event on block sides. We can get around this by preventing event bubbling:</p><pre>$scene.on(&quot;mousedown&quot;, function(e) {<br>      e.stopPropagation();<br>    });</pre><p>Give it a whirl…</p><h3>Removing Blocks</h3><p>Let’s round out the experiment by adding the ability to remove blocks. We need to do a couple of subtle but important things:</p><ol><li>Change hover border colour from green to red</li><li>Disable the block ghosts</li></ol><p>It’ll be easier to do these with CSS, as long as we have a body class to indicate whether we’re in addition (normal) mode or subtraction mode:</p><pre>$body.on(&quot;keydown&quot;, function(e) {<br>      if (e.altKey || e.controlKey || e.metaKey) {<br>        $body.addClass(&quot;subtraction&quot;);<br>      }<br>    });</pre><pre>    $body.on(&quot;keyup&quot;, function(e) {<br>      $body.removeClass(&quot;subtraction&quot;);<br>    });</pre><p>When a modifier key is pressed (alt, control, or command), this code will make sure body has a subtractionclass. This makes it easier to target various elements using this class:</p><pre>.subtraction .block:hover .side {<br>      outline: 1px solid rgba(255, 0, 0, 0.5);<br>    }</pre><pre>    .subtraction .ghost {<br>      display: none;<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nG4dQREwkgPasSxL.gif" /></figure><p><em>We’re checking for a number of modifier keys, since different operating systems intercept different modifiers. For example, </em><em>altKey and </em><em>metaKey work on macOS, whereas </em><em>controlKey works on Ubuntu.</em></p><p>If we click on a block, when we’re in subtraction mode, we should remove it:</p><pre>$body.on(&quot;click&quot;, &quot;.side&quot;, function(e) {<br>      const $this = $(this);<br>      const previous = $this.data(&quot;block&quot;);</pre><pre>      if ($body.hasClass(&quot;subtraction&quot;)) {<br>        previous.block.remove();<br>        previous = null;<br>      } else {<br>        const coordinates = createCoordinatesFrom(<br>          $this.data(&quot;type&quot;),<br>          previous.x,<br>          previous.y,<br>          previous.z<br>        );</pre><pre>        const next = new Block.Dirt(...coordinates);<br>        next.block.appendTo($scene);<br>      }<br>    });</pre><p>This is the same .side click event listener we had before, but instead of just adding new blocks when a side is clicked, we first check if we’re in subtraction mode. If we are, the block we just clicked is removed from the scene.</p><p>There’s a long way to go before we support as many blocks and interactions as Minecraft, but this is a good start. What’s more, we managed to achieve this without needing to study advanced 3D techniques. It’s an unconventional (and creative) use of CSS transformations!</p><p><em>If you’re keen to do more with this code, head over to the </em><a href="https://codequs.com/p/HksufSzNJe/how-to-build-a-javascript-3d-minecraft-editor/#"><em>other half of this adventure</em></a><em>. You don’t have to be a PHP expert to interact with Minecraft servers. And just imagine the awesome things you can do with that knowledge…</em></p><h3>Suggest</h3><p>☞ <a href="https://codequs.com/a/rJErr6FF">Unity 5 Host Your Game Server Online like a PRO</a></p><p>☞ <a href="https://codequs.com/a/HJLIezai">Mastering 3D Animation in Unity</a></p><p>☞ <a href="https://codequs.com/a/B10zpuEd">JavaScript Bootcamp — 2016</a></p><p>☞ <a href="https://codequs.com/a/HyQrRJa_">Upgrade your JavaScript to ES6</a></p><p>☞ <a href="https://codequs.com/a/SJOOCdEO">JavaScript Tutorials: Understanding the Weird Parts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4db1fba9b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate Your Rails API with JWT]]></title>
            <link>https://medium.com/@cassycassy/authenticate-your-rails-api-with-jwt-3b37623cd988?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b37623cd988</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Sat, 15 Oct 2016 04:07:00 GMT</pubDate>
            <atom:updated>2016-10-15T04:07:00.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*m-aF25LnuFgHletrQt9GtQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*XKGG_rTX3_AQTTv2.jpg" /></figure><p>Authentication is one of the vital parts of any web application. There are innumerable libraries and frameworks that provide various options to perform authentication one way or another. These libraries take away much of the groundwork required to setup an authentication system, providing “magic” with what’s happening behind the scenes. For Rails, we have a number of authentication systems, the prominent one being <a href="https://github.com/plataformatec/devise/">Devise</a>.</p><p>Devise is an authentication engine that runs as part of our application and does all the heavy lifting when it comes to authentication. However, often times we don’t need many of the parts it provides. For example, Devise doesn’t work very well with API-based systems, which is why we have <a href="https://github.com/lynndylanhurley/devise_token_auth">the devise_token_auth gem</a>. devise_token_auth is a library that does what Devise does, but with tokens instead of sessions.</p><p>Today we’re going to explore building our own custom <a href="https://jwt.io/">JWT</a>-based authentication system from scratch. Let’s get started.</p><h3>Why JWT</h3><p>JWT (JSON Web Token, pronounced “jot”) is a self-contained authentication standard designed for securely exchanging data between systems. Since it’s self-contained, it doesn’t need any backing storage to work. Also, the JWT approach is very reliable and flexible, allowing it to be used with any client. It doesn’t have any overhead to get started and almost all languages have libraries that make working with JWTs a breeze.</p><p>We already have an excellent tutorial about JWT and how to use it with <a href="https://codequs.com/a/SJ2DLKtd">Rails</a>. If you’re new to JWT I’d suggest you to read it first to get an idea of what we’re going to create.</p><h3>Model</h3><p>We’ll begin by building a model for our app. The application will authenticae users, so let’s create a User model.</p><pre>rails g model user</pre><p>This command will create a migration file under <strong>db/migrate</strong> called <strong>XXX_create_users</strong>, where XXX is the current date. Add the following code to this file, which will add the columns we need:</p><pre>create_table :users do |t|<br>      t.string :email,              null: false<br>      t.string :password_digest,    null: false<br>      t.string   :confirmation_token<br>      t.datetime :confirmed_at<br>      t.datetime :confirmation_sent_at</pre><pre>      t.timestamps<br>    end</pre><p>Run rake db:migrate to run the migration.</p><p>We’re adding email and password_digest columns here, which are the basic columns required to register or authenticate a user. Of course, you can add more columns that makes sense, if you like. The confirmation_token,confirmed_at, and confirmation_sent_at columns are required for user confirmation. You can skip this if you don’t wish to confirm the emails.</p><h3>Validations</h3><p>Let’s add our validations to <strong>models/user.rb</strong>:</p><pre>validates_presence_of :email<br>    validates_uniqueness_of :email, case_sensitive: false<br>    validates_format_of :email, with: /@/</pre><p>We’re validating the uniqueness of email without case sensitivity and doing a simple format check of the email ensuring there is a @ in the email string. This might not be a solid validation, but there is no standard one and that’s why we verify the email upon registration.</p><h4>Callbacks</h4><p>We are going to make use of Rails’s <a href="http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password">has_secure_password</a> for handling the password hashing.</p><p>To start, add the gem bcrypt (it’s probably there, but commented out) to your <strong>Gemfile</strong> and run bundle install. Once the gem is installed, add the following line inside the User class in the file <strong>models/user.rb</strong>:</p><pre>class User &lt; ApplicationRecord<br>   has_secure_password<br>   ...</pre><p>Let’s also add callbacks that we want to perform before user creation. First, we’d want to lowercase the email and strip any spaces. Second, we’d have to generate a confirmation token that will be sent in the email to the user.</p><p>Add these before callbacks to the <strong>models/user.rb</strong> file:</p><pre>before_save :downcase_email<br>    before_create :generate_confirmation_instructions</pre><p>We downcase the email before saving it to the DB. The confirmation instructions should be generated only during the creation of the user record. Let’s add the methods:</p><pre>def downcase_email<br>      self.email = self.email.delete(&#39; &#39;).downcase<br>    end</pre><pre>    def generate_confirmation_instructions<br>      self.confirmation_token = SecureRandom.hex(10)<br>      self.confirmation_sent_at = Time.now.utc<br>    end</pre><p>If you plan to skip the confirmation, you can omit the above method and the corresponding callback.</p><h3>Registration</h3><h4>Create</h4><p>We now have the model setup, so let’s add an endpoint for user creation. Create our users controller:</p><pre>rails g controller users</pre><p>Add the below line to <strong>config/routes.rb</strong>:</p><pre>def create<br>      user = User.new(user_params)</pre><pre>      if user.save<br>        render json: {status: &#39;User created successfully&#39;}, status: :created<br>      else<br>        render json: { errors: user.errors.full_messages }, status: :bad_request<br>      end<br>    end</pre><pre>    private</pre><pre>    def user_params<br>      params.require(:user).permit(:email, :password, :password_confirmation)<br>    end</pre><p>We now have generated our UsersController. Head over to the controller (<strong>app/controllers/users_controller.rb</strong>) and add the following lines:</p><pre>def create<br>  user = User.new(user_params)</pre><pre>  if user.save<br>    render json: {status: &#39;User created successfully&#39;}, status: :created<br>  else<br>    render json: { errors: user.errors.full_messages }, status: :bad_request<br>  end<br>end</pre><pre>private</pre><pre>def user_params<br>  params.require(:user).permit(:email, :password, :password_confirmation)<br>end</pre><p>We now have an API endpoint to create a user! You can try it by starting the server and sending a POST request with the user details as JSON in the body. Here’s an example of what you could post to <a href="http://localhost:3000/users:">http://localhost:3000/users:</a></p><pre>{<br>      user: {<br>        email: &#39;test@example.com&#39;,<br>        password: &#39;anewpassword&#39;,<br>        password_confirmation: &#39;anewpassword&#39;<br>      }<br>    }</pre><p>You should receive the User created successfully message as the response. Subsequent requests with the same data should respond with error messages. That’s our validations in play. For those who are skipping the confirmation part, you can skip the following and head to the Login section.</p><h4>Confirmation</h4><p>One thing that is pending is the user confirmation. We are going to send an email confirmation to the user before creation and create an endpoint that validates the token to confirm the user.</p><p>To start, we have to send an email to the user when the record is successfully created. We wouldn’t be going through how to send emails since there are already good tutorials that cover how to do it. We should add the line to send email right after user.save in users_controller.</p><pre>...<br>    if user.save<br>      #Invoke send email method here<br>    ...</pre><p>Just make sure that you include the user.confirmation_token in your email. Ideally, the URL should lead to an endpoint that fetches the token and posts it to our API. Let’s create that post API endpoint.</p><p>Adda route to our <strong>config/routes.rb</strong> file for the confirm endpoint:</p><pre>resources :users, only: :create do<br>      collection do<br>        post &#39;confirm&#39;<br>      end<br>    end</pre><p>Now, create the confirm action in UsersController:</p><pre>def confirm<br>      token = params[:token].to_s</pre><pre>      user = User.find_by(confirmation_token: token)</pre><pre>      if user.present? &amp;&amp; user.confirmation_token_valid?<br>        user.mark_as_confirmed!<br>        render json: {status: &#39;User confirmed successfully&#39;}, status: :ok<br>      else<br>        render json: {status: &#39;Invalid token&#39;}, status: :not_found<br>      end<br>    end</pre><p>Let’s see what we’re doing here. First, we are fetching the token from params, calling to_s to handle the case where the token is not sent in the request. Next, fetch the corresponding user based on the confirmation token.</p><p>If the user is present and the confirmation isn’t expired, call the model method mark_as_confirmed! and respond with a success message. We have to add the confirmation_token_valid? and mark_as_confirmed! methods to ourUser model:</p><pre>def confirmation_token_valid?<br>      (self.confirmation_sent_at + 30.days) &gt; Time.now.utc<br>    end</pre><pre>    def mark_as_confirmed!<br>      self.confirmation_token = nil<br>      self.confirmed_at = Time.now.utc<br>      save<br>    end</pre><p>The confirmation_token_valid? method checks if the confirmation was sent in the last 30 days and, thus, is not expired. You can change it to any value you wish.</p><p>mark_as_confirmed! saves the confirmed time and nullifies the confirmation token so that the same confirmation email can’t be used to confirm the user again.</p><p>We now have the endpoint to confirm a user. You can test it by sending a post request to the endpointusers/confirm?token=&lt;CONFIRMATION_TOKEN&gt; and check the confirmed_at and confirmation_token value for the user. You should get User confirmed successfully. Subsequent requests with the same token should return Invalid token.</p><p>We now have a working registration as part of our app. Let’s create the final piece: the login endpoint.</p><h3>Login</h3><p>For login, we are going to create an endpoint to log the user in by sending the credentials of the user and responding with a JWT token. We also will add a helper method that can be used to secure endpoints that we want to be exposed only to authenticated users.</p><h4>Controller</h4><p>Let’s add the login route to our <strong>config/routes.rb</strong> file under users resource:</p><pre>resources :users, only: :create do<br>        collection do<br>          post &#39;confirm&#39;<br>          post &#39;login&#39;<br>        end<br>    end</pre><p>We have created a users/login route now. The controllers require some modification to pull in the json_web_tokencode and create the corresponding action in the UsersController.</p><p>In <strong>controllers/application_controller.rb</strong>, add the below line right after the class definition:</p><pre>require &#39;json_web_token&#39;</pre><p>In <strong>controllers/users_controller.rb</strong> add the following snippet:</p><pre>def login<br>      user = User.find_by(email: params[:email].to_s.downcase)</pre><pre>      if user &amp;&amp; user.authenticate(params[:password])<br>          auth_token = JsonWebToken.encode({user_id: user.id})<br>          render json: {auth_token: auth_token}, status: :ok<br>      else<br>        render json: {error: &#39;Invalid username / password&#39;}, status: :unauthorized<br>      end<br>    end</pre><p>Let’s go over this method step by step. First, we’re fetching the user from the email and, if present, call theauthenticate method passing the password that is supplied. The authenticate method is provided by thehas_secure_password helper.</p><p>Once we verify the email and password, encode the user’s id into a JWT token via our encode method fromJsonWebToken lib which we have yet to create. Then, return the token.</p><p>For those who are confirming emails, we have to disallow users who aren’t confirmed. Modify the controller action to include one more conditional:</p><pre>...<br>    if user &amp;&amp; user.authenticate(params[:password])<br>      if user.confirmed_at?<br>        auth_token = JsonWebToken.encode({user_id: user.id})<br>        render json: {auth_token: auth_token}, status: :ok<br>      else<br>        render json: {error: &#39;Email not verified&#39; }, status: :unauthorized<br>      end<br>    else<br>    ...</pre><p>Checking if the confirmed_at field is not empty does the job, meaning user has been confirmed before allowing them to login.</p><h4>JWT Library</h4><p>Now, let’s add the JWT library. Begin by adding the following gem to your Gemfile and do bundle install:</p><pre>gem &#39;jwt&#39;</pre><p>Once done, create a file called <strong>json_web_token.rb</strong> under <strong>lib/</strong> and add these lines:</p><pre>require &#39;jwt&#39;</pre><pre>    class JsonWebToken<br>      # Encodes and signs JWT Payload with expiration<br>      def self.encode(payload)<br>        payload.reverse_merge!(meta)<br>        JWT.encode(payload, Rails.application.secrets.secret_key_base)<br>      end</pre><pre>      # Decodes the JWT with the signed secret<br>      def self.decode(token)<br>        JWT.decode(token, Rails.application.secrets.secret_key_base)<br>      end</pre><pre>      # Validates the payload hash for expiration and meta claims<br>      def self.valid_payload(payload)<br>        if expired(payload) || payload[&#39;iss&#39;] != meta[:iss] || payload[&#39;aud&#39;] != meta[:aud]<br>          return false<br>        else<br>          return true<br>        end<br>      end</pre><pre>      # Default options to be encoded in the token<br>      def self.meta<br>        {<br>          exp: 7.days.from_now.to_i,<br>          iss: &#39;issuer_name&#39;,<br>          aud: &#39;client&#39;,<br>        }<br>      end</pre><pre>      # Validates if the token is expired by exp parameter<br>      def self.expired(payload)<br>        Time.at(payload[&#39;exp&#39;]) &lt; Time.now<br>      end<br>    end</pre><p>Let’s go through the code. First, in the encode method, merge the payload which is the user id with meta information such as expiry, issuer, and audience. You can learn about these “meta” claims from the JWT tutorial linked at the beginning of this post. Once merged, encode the payload using the JWT.encode method along with the secret key from our server. It is important that this key is kept secure since this is the master key for all the tokens our app issues.</p><p>Then, the decode method, which uses the decode method from the jwt gem to (you guessed it) decode the payload using the secret key. We have a couple of other helper methods, one is valid_payload which validates if the payload has been tampered with, and the expired method which validates whether the token has expired. The default expiry is set in the meta method which is 7 days, but you are free to change it as per your requirement.</p><p>Now we have a functioning login endpoint that we can use to login the user. Try calling the endpoint users/loginwith the below formatted data in the request body:</p><pre>{<br>      &quot;email&quot;: &quot;test@example.com&quot;,<br>      &quot;password&quot;: &quot;anewpassword&quot;<br>    }</pre><p>You should see a response similar to this,</p><pre>{<br>      &quot;auth_token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NzUzMTM5OTQsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50In0.5P3qJKelCdbTixnLyIrsLKSVnRLCv2lvHFpXqVKdPOs&quot;<br>    }</pre><p>There it is. Our authentication token for the user. We can now use this token to validate each request for the user.</p><h4>Authentication Helper</h4><p>Alright, we are going to create a helper method that gets the token from the header, validates the payload, and fetches the corresponding user from the DB. Open up <strong>/app/controllers/application_controller.rb</strong> and add the following:</p><pre>protected<br># Validates the token and user and sets the @current_user scope<br>def authenticate_request!<br>  if !payload || !JsonWebToken.valid_payload(payload.first)<br>    return invalid_authentication<br>  end</pre><pre>  load_current_user!<br>  invalid_authentication unless @current_user<br>end</pre><pre># Returns 401 response. To handle malformed / invalid requests.<br>def invalid_authentication<br>  render json: {error: &#39;Invalid Request&#39;}, status: :unauthorized<br>end</pre><pre>private<br># Deconstructs the Authorization header and decodes the JWT token.<br>def payload<br>  auth_header = request.headers[&#39;Authorization&#39;]<br>  token = auth_header.split(&#39; &#39;).last<br>  JsonWebToken.decode(token)<br>rescue<br>  nil<br>end</pre><pre># Sets the @current_user with the user_id from payload<br>def load_current_user!<br>  @current_user = User.find_by(id: payload[0][&#39;user_id&#39;])<br>end</pre><p>Here, authenticate_request! is the helper method that we are going to use to authenticate controller actions. It fetches the payload from the Authorization header of the request, then validates the payload using thevalid_payload method, which we’ve seen before. Once confirmed valid, it fetches the user using the user_id in the payload, loading the user record into the scope.</p><p>We can now add the authenticate_request method as a before_filter to any controller action that we want to be authenticated for the user.</p><h3>Conclusion</h3><p>With that we have come to the conclusion of this tutorial. We covered the meaty aspects of user authentication — registration, confirmation, and login — all through an API using JWT. You can take this forward as is or make any sort of modifications to parts of it, maybe adding separate components like password reset, email update, locking accounts, and much more.</p><p>The example app is hosted on <a href="https://github.com/avinoth/auth-scratch-demo">github</a>. Feel free to fork and mess with it.</p><p>I thank you for reading this tutorial and I hope it serves your purposes. Happy learning.</p><h3>Suggest</h3><p>☞ <a href="https://codequs.com/a/ByysfMId">Learn Rails: Build a Network Chatroom</a></p><p>☞ <a href="https://codequs.com/a/HyK9TB_o">Make Medium (medium.com) Clone in Ruby on Rails</a></p><p>☞ <a href="https://codequs.com/a/SyMg5vdj">Learn Rails: Quickly Code, Style and Launch 4 Web Apps</a></p><p>☞ <a href="https://codequs.com/a/BJd50inF">Rails 5: Learning Web Development the Ruby Way</a></p><p>☞ <a href="https://codequs.com/a/Sk6v-oEF">Professional Rails Code Along</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b37623cd988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Ruby Development Tool]]></title>
            <link>https://medium.com/@cassycassy/modern-ruby-development-tool-2a994134c6b?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a994134c6b</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Fri, 14 Oct 2016 08:50:20 GMT</pubDate>
            <atom:updated>2016-10-14T08:50:20.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3La3qc2Gysn76ZMKfIb3xQ.jpeg" /></figure><p>Web Development has evolved tremendously in the last 20 years. A modern development environment would be unrecognizable to to someone developing <a href="https://en.wikipedia.org/wiki/ColdFusion_Markup_Language">Coldfusion</a> in the late ’90s for example. The greater focus on best practices and developer productivity have certainly made software more maintainable, but this comes at the cost of added complexity. To navigate this complexity, a modern development environment is required; this article will outline some of my personal favorite tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QmWQj8syI0fxscAv.png" /></figure><h3>Tmux</h3><p>Tmux is a terminal multiplexer (think <a href="https://www.gnu.org/software/screen/">screen</a>), which means you can have several terminals in the same shell session. It allows you to split panes and move them around and reconnect to a tmux session from a different machine. This particularly shines when it is deployed on a server, as you can start a long-running task, disconnect, and your tmux session will keep running.</p><p>The real strength in Tmux for development lies in knowing in which window each of your different tools is running because with some quick window changing <a href="https://github.com/disavowd/tmux-dotfiles/blob/master/tmux.conf#L30-L33">shortcuts</a>, you can move so quickly that flow becomes instinctual. To aid this, <a href="https://github.com/tmuxinator/tmuxinator">tmuxinator</a> sets up profiles (protip: bind these to Tmux shortcuts to facilitate easy opening of different types of projects like Rails, Sinatra, etc), which complements Tmux nicely.</p><p>Additionally, Tmux is extendable through its <a href="https://github.com/tmux-plugins">plugin ecosystem</a>. Take a look, but I would recommend the <a href="https://github.com/tmux-plugins/tpm">Tmux Plugin Manager</a>, <a href="https://github.com/tmux-plugins/tmux-battery">tmux-battery</a>, and <a href="https://github.com/tmux-plugins/tmux-sensible">tmux sensible</a>.</p><p>If you are looking for a simple start with Tmux, check out <a href="https://www.sitepoint.com/tmux-a-simple-start/">this article</a>.</p><h3>Fish</h3><p>Bash is fine and all, but it hasn’t aged very well and better terminal alternatives are available. ZSH is an excellent choice, but I personally lack the motivation to invest time in learning how to configure yet another piece of software. To this end, I would recommend <a href="https://fishshell.com/">Fish</a>. It has excellent command completion, is fully scriptable, and looks much nicer than Bash. Best of all, it just works out of the box (although there are a couple of <a href="https://en.wikipedia.org/wiki/Friendly_interactive_shell#bash.2Ffish_Translation_table">minor idiosyncrasies</a> you’ll run into. Also, your Bash aliases won’t work, but translating is straightforward and these are comparatively low setup costs). I particularly enjoy interfacing with Git this way, but I recently discovered the excellent <a href="https://github.com/donnemartin/gitsome">Gitsome</a>, which offers excellent Github integration and unparalleled autocomplete, so I am currently vacillating between the two.</p><h3>Vim</h3><p>Vim is the cornerstone of my environment. Heavily customized to speed development, it bears more of a resemblance to a fully fledged (albeit lightweight!) IDE. Let’s walk through some generally useful plugins, and then get to some Ruby-specific ones. You can download my vim dotfiles <a href="https://github.com/disavowd/vim-dotfiles">here</a>.</p><p>Navigating a project can be cumbersome. Fortunately, Vim’s rich ecosystem really comes into its own here. For browsing a project, I recommend the excellent <a href="https://github.com/scrooloose/nerdtree">Nerdtree</a>. This will give you a browsable tree structure, affording you a neat high-level overview of the current directory and its children. Pressing m while in this view will allow you the ability to delete, create, and rename nodes without ever leaving vim. Sublime stalwarts will enjoy <a href="https://github.com/ctrlpvim/ctrlp.vim">ctrlp</a>; an excellent fuzzy matcher which particularly shines when you have similarly named files, like in a Rails project for example. Finally, I frequently want to access files I have used recently; <a href="https://github.com/yegappan/mru">MRU</a> does exactly this.</p><p>While those are some of my favorites, here are some other vim plugins that deserve special mention:</p><ul><li><a href="https://github.com/tpope/vim-fugitive">Fugitive</a>: Git integration directly in Vim</li><li><a href="https://github.com/ervandew/supertab">Supertab</a>: Code completion</li><li><a href="https://github.com/vim-airline/vim-airline">Airline</a>: Pleasant looking status bar</li><li><a href="https://github.com/tomtom/tcomment_vim">TComment</a>: Quick comment/uncomment functionality</li><li><a href="https://github.com/tpope/vim-surround">Surround</a>: Wrap the usual vim boundary selections in parenthesis or quotes</li><li><a href="https://github.com/Townk/vim-autoclose">Autoclose</a>: Automatically close brackets or quotes</li><li><a href="https://github.com/sjl/gundo.vim">Gundo</a>: Interface to Vim’s well hidden tree structure storing document changes, which frequently proves much more useful than the linear ‘undo’ functionality</li></ul><h3>Ruby Specific Plugins</h3><p>First up, you need to ensure your version of Vim is compiled with Ruby:</p><pre>vim --version | grep ruby</pre><p>The above command should include a +ruby. If it doesn’t, you need to either recompile Vim with ruby support (<a href="http://zaiste.net/2013/05/compiling_vim_with_ruby_and_python_support_on_ubuntu/">relatively trivial</a>) or install a version of Vim with Ruby support, like MacVim. While a lot of the plugins will work without it, you’ll miss out on useful features like autocompletion.</p><p><a href="https://github.com/vim-ruby/vim-ruby/">vim-ruby</a> is the first port of call. It adds syntax highlighting, IntelliSense-like autocompletion, and even compiler plugins. This should get you a lot of basic IDE functionality out of the box. It even has erb syntax highlighting!</p><p><a href="https://github.com/tpope">Tim Pope</a> is the man who has given us several excellent Ruby (and other) plugins. You could do worse than to check out his projects and integrate them into your workflow. If you’re going to get one plugin to aid your Rails development, it should be <a href="https://github.com/tpope/vim-rails">vim-rails</a>. This plugin brings all the command line functionality directly into Vim, which is tremendously useful when you marry it up with Vim shortcuts. Let’s delve into some useful commands here:</p><p>gf – This is a context aware switch that will jump you right into a related file. You can leverage the appropriately named :A (alternate) and :R (related) to go from model to schema, template to helper, and controller to functional test.</p><p>Interface with rails on the command line with :Rails (also rake can be accessed via :Rake, if you’re pre-Rails 5.)</p><p>You can extract partials by visually selecting an area and leveraging :Rextract &lt;filename&gt;. This seems such a minor feature but is incredibly useful when refactoring a clumsy view.</p><p>There are a ton of other <a href="https://github.com/tpope/vim-rails/blob/master/doc/rails.txt">useful shortcuts</a> and your time will be well invested in learning them.</p><p><a href="https://github.com/tpope/vim-dispatch">vim-dispatch</a> is another Tim Pope creation. This allows you to leverage Tmux to bring asynchronous functionality to Vim. Useful to kick off unit tests without blocking input or opening another pane.</p><p><a href="https://github.com/thoughtbot/vim-rspec">vim-rspec</a> is a lightweight RSpec runner for Vim. I enjoy the mappings if I’m not using Guard.</p><p>For further reading on this subject, check out <a href="https://www.sitepoint.com/effective-rails-development-vim/">this article</a> which is much more in depth.</p><p>Honorable mentions:</p><ul><li><a href="https://github.com/tpope/vim-endwise">vim-endwise</a>: automatically appends an end when you input def &lt;function_name&gt;. Think <a href="https://github.com/garbas/vim-snipmate">snipmate</a> but without having to invoke the shortcut.</li><li><a href="https://github.com/tpope/vim-bundler">vimbundler</a>: wraps bundler, which makes interfacing with it slightly nicer.</li><li><a href="https://github.com/tpope/vim-haml">vim-haml</a>: Cutting edge Vim runtime files for Haml, Sass, and SCSS — unnecessary but nice.</li></ul><p>This isn’t really a Vim plugin but I’ll include it here anyway: <a href="https://rubygems.org/gems/gem-browse">gem-browse</a> is a Ruby Gem that opens a library’s source file in your editor, which saves time when you need to wade through the source of some obscure library to see why your code isn’t executing as expected.</p><h3>Docker</h3><p><a href="https://www.docker.com/">Docker</a> is comparatively new technology compared with the others, but no less important. It facilitates easy and platform agnostic deployment by running a ‘container’ within a single Linux instance, avoiding the overhead of starting and maintaining traditional Virtual Machines. Additionally, the isolation afforded by this approach affords an extra layer of protection.</p><p>Docker used to be a bit difficult to get started with, necessitating the excellent <a href="https://www.viget.com/articles/how-to-use-docker-on-os-x-the-missing-guide">How to Use Docker on OS X: The Missing Guide</a>, but things are better now. Head over to <a href="https://docs.docker.com/">docker.com</a> to get started.</p><h3>Guard</h3><p>I am a huge fan of <a href="https://github.com/guard/guard">Guard</a>. While in large projects with huge batteries of tests, it doesn’t shine so much, any rapidly evolving project without this constraint benefits hugely from the instant feedback it provides to developers. By keeping the Spring preloader going, it can dramatically reduce time taken for tests to run, and I would wholeheartedly recommend pairing it with <a href="https://github.com/kern/minitest-reporters">minitest-reporters</a> for more informative test output.</p><h3>Pry</h3><p><a href="http://pryrepl.org/">Pry</a> is a fantastic addition to your gemset. A powerful alternative to irb, it allows command shell integration (git, vim, etc), syntax highlighting and powerful history viewing and replay functionality. Used in tandem with the <a href="https://github.com/pry/pry-doc">pry-doc</a> gem, it includes some neat features like show-doc to bring up documentation and show-source to view source of Ruby builtins. It can work well as a debugger and as someone who favors REPL driven development, I find it a breath of fresh air to use compared with the default irb.</p><h3>Pgcli</h3><p>With the advent of ORMs, SQL is something I interface with less regularly, which means autocomplete is a real time saver when I can’t remember exactly how to do something. <a href="http://pgcli.com/">Pgcli</a> (and its cousin <a href="http://mycli.net/">Mycli</a> if you’re stuck with mysql) offer this exact functionality and with syntax highlighting to boot. Highly recommended.</p><h3>Mutt</h3><p>If you can suffer through what is arguably the most painful configuration process in modern software, <a href="http://www.mutt.org/">Mutt</a> is an excellent choice for command line email access. It uses Vim bindings and I definitely appreciate not having to leave my shell to handle email.</p><h3>Irssi</h3><p>I find IRC an invaluable resource, but definitely something that works better in the shell. <a href="https://irssi.org/">irssi</a> is my client of choice (be sure to check out the <a href="https://scripts.irssi.org/">extensions</a>). I also hear good things about <a href="https://weechat.org/">weechat</a>.</p><h3>Summary</h3><p>We’ve covered a lot of ground here and, as always, there’s a ton more below the surface. Vim is where I spend most of my time, so I’ve spent proportionally much more time customizing it. Researching Tmux and your shell properly is definitely time well-spent. Naturally, this is all personal preference so you’re unlikely to develop using my exact setup, but you should hopefully have a better idea of what is out there and perhaps even integrate something new from here into your workflow.</p><h3>Suggest</h3><p>☞ <a href="https://codequs.com/a/SJ2DLKtd">The Complete Ruby on Rails Developer Course</a></p><p>☞ <a href="https://codequs.com/a/BJd50inF">Rails 5: Learning Web Development the Ruby Way</a></p><p>☞ <a href="https://codequs.com/a/rkIvPGQ_">Learn Ruby on Rails from Scratch</a></p><p>☞ <a href="https://codequs.com/a/BJmvdJaO">Ruby Scripting for Software Testers</a></p><p>☞ <a href="https://codequs.com/a/Sk8v6PX_">Python, Ruby, Shell — Scripting for Beginner</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a994134c6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The WordPress Customizer JavaScript APIs: Getting Started]]></title>
            <link>https://medium.com/@cassycassy/the-wordpress-customizer-javascript-apis-getting-started-e4cf7b79e6ee?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4cf7b79e6ee</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Thu, 13 Oct 2016 01:47:54 GMT</pubDate>
            <atom:updated>2016-10-13T01:47:54.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*0fZ1N35GHq9gNGU2m7fFng.jpeg" /></figure><p>The WordPress Customizer has been actively developed since its inception. The APIs are continually evolving, including the JavaScript API. However, it is one of the least documented APIs in the WordPress Codex. Hence there are only a few extensive records that show how to leverage the JavaScript API <em>practically</em>.</p><p>Leveraging the JavaScript API in the WordPress Customizer can actually enable us to serve a more compelling real-time experience while customizing the theme beyond casting the change from the Control to the Preview window.</p><p>You may be familiar with how the Customizer JavaScript API is being used to cast a change to the Preview window in real time. To do so, we set the Setting transport mode to postMessage and add the corresponding JavaScript code, as follows.</p><p><em>wp.customize( ‘blogname’, function( value ) {<br> value.bind( function( to ) {<br> $( ‘.site-title a’ ).text( to );<br> } );<br>} );</em></p><p>However, we can also stretch the API further to, for example, hide, show, or move a Section, Panel, a Control, change the value of a Setting based on another Setting value, and interconnect the Preview and the Control interactions. And these are what we are going to look into in this tutorial.</p><h3>The Settings and Controls</h3><p>To begin with, we’ll examine the “Settings” and “Controls” in the Customizer that we have added for the purpose of this tutorial. We will also look into the code that puts them in their place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*TlRXXz-2fJHGPrew.jpg" /></figure><p>In this tutorial, we will be focusing on the website “Site Title”. And as you can see above, we have two Controls: the native WordPress “Site Title” input field and our custom checkbox to enable or disable the “Site Title”. These two Controls reside in the “Site Identity” section. And on the right side of the image is the Preview, where you can see the “Site Title” being rendered.</p><p>Furthermore, as you can see below, we also have two Controls that reside in the Colors section to change the “Site Title” color and its hover state color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gXCpGhbsnD-0ALop.jpg" /></figure><h3>The Underlying Code</h3><p>Our theme herein is based on <a href="http://underscores.me/">Underscores</a>, which has all the Customizer-related code placed in the /inc/customizer.php file.</p><p><em>function tuts_customize_register( $wp_customize ) {</em><br> <br><em> $wp_customize-&gt;get_setting( ‘blogname’ )-&gt;transport = ‘postMessage’;<br> <br> $wp_customize-&gt;get_setting( ‘blogdescription’ )-&gt;transport = ‘postMessage’;<br> $wp_customize-&gt;get_control( ‘blogdescription’ )-&gt;priority = ‘12’;<br> <br> $wp_customize-&gt;get_setting( ‘header_textcolor’ )-&gt;default = ‘#f44336’;</em><br><em> $wp_customize-&gt;get_setting( ‘header_textcolor’ )-&gt;transport = ‘postMessage’;<br> <br> // Checkbox to Display Blogname<br> $wp_customize-&gt;add_setting( ‘display_blogname’, array(<br> ‘transport’ =&gt; ‘postMessage’,<br> ) );<br> <br> $wp_customize-&gt;add_control( ‘display_blogname’, array(</em><br><em> ‘label’ =&gt; __( ‘Display Site Title’, ‘tuts’ ),<br> ‘section’ =&gt; ‘title_tagline’,<br> ‘type’ =&gt; ‘checkbox’,<br> ‘priority’ =&gt; 11,<br> ) );<br> <br> // Add main text color setting and control.</em><br><em> $wp_customize-&gt;add_setting( ‘header_textcolor_hover’, array(<br> ‘default’ =&gt; ‘#C62828’,<br> ‘sanitize_callback’ =&gt; ‘sanitize_hex_color’,<br> ‘transport’ =&gt; ‘postMessage’,<br> ) );</em><br> <br><em> $wp_customize-&gt;add_control( new WP_Customize_Color_Control( $wp_customize, ‘header_textcolor_hover’, array(<br> ‘label’ =&gt; __( ‘Header Text Color: Hover’, ‘tuts’ ),<br> ‘section’ =&gt; ‘colors’,<br> ‘priority’ =&gt; ‘11’<br> ) ) );<br>}<br>add_action( ‘customize_register’, ‘tuts_customize_register’ );</em></p><p>And as you can see above, we have made a few modifications to the code, adhering to our need in this tutorial.</p><ul><li>We lower the WordPress built-in Setting, blogdescription, to 12 so that the checkbox Setting, display_blogname, appears below the &quot;Site Title&quot; input field.</li><li>We create a new Control named display_blogname. We set the priority to 11 which, in our case, resides between the &quot;Site Title&quot; and the &quot;Tagline&quot; input field.</li><li>Set the header_text default color to #f44336 and the transport type to postMessage.</li><li>We also create a new Setting, header_text_color. Similarly, we also set the priority to 11 so that it appears just below the header_textcolor Setting.</li></ul><p>All these Settings are set with postMessage instead of with refresh. The postMessage option allows the value to be transported asynchronously and displayed in the Preview window in real time. However, we will also have to write our own JavaScript to handle the change.</p><h3>Loading JavaScript</h3><p>We need to create two JavaScript files: one file, customizer-preview.js, to deal with the Preview and the other file, customizer-control.js, to handle the Controls inside the Customizer panel.</p><p><em>js<br>├── customizer-preview.js // 1. File to handle the Preview<br>├── customizer-control.js // 2. File to handle the Controls<br>├── navigation.js<br>└── skip-link-focus-fix.js</em></p><p>Within customizer-preview.js is the following code.</p><p><em>( function( $ ) {<br> // Codes here.<br>} )( jQuery );</em></p><p>It is currently an empty enclosed JavaScript function. We will discuss more specifically how we preview changes in the Preview window in the next tutorial of this series.</p><p>In the other file, customizer-control.js, we add the following code:</p><p><em>(function( $ ) {<br> wp.customize.bind( ‘ready’, function() {<br> var customize = this;<br> // Codes here<br> } );<br>})( jQuery );</em></p><p>As you can see above, we will wrap the code in this file upon the Customizer ready event. This will ensure everything within the Customizer is fully ready, including the Settings, Panels, and Controls, before we begin executing any customized functions.</p><p>Finally, once we have added the code, we will load these two JavaScript files in two different locations.</p><p><em>// 1. customizer-preview.js<br>function tuts_customize_preview_js() {<br> wp_enqueue_script( ‘tuts_customizer_preview’, get_template_directory_uri() . ‘/js/customizer-preview.js’, array( ‘customize-preview’ ), null, true );<br>}<br>add_action( ‘customize_preview_init’, ‘tuts_customize_preview_js’ );</em><br> <br><em>// 2. customizer-control.js<br>function tuts_customize_control_js() {<br> wp_enqueue_script( ‘tuts_customizer_control’, get_template_directory_uri() . ‘/js/customizer-control.js’, array( ‘customize-controls’, ‘jquery’ ), null, true );<br>}<br>add_action( ‘customize_controls_enqueue_scripts’, ‘tuts_customize_control_js’ );</em></p><p>The customizer-preview.js file will be loaded within the Customizer Preview window through the <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/customize_preview_init">customize_preview_init</a> Action hook. The customizer-control.js file will be loaded in the Customizer back-end, where the Setting and Control elements are accessible through the customize_controls_enqueue_scripts Action hook.</p><p><strong>Written by Louie R.</strong></p><p><strong>If you found this post interesting, follow and support us.<br>Suggest for you:</strong></p><p>☞<a href="https://codequs.com/a/H12CDA_2">Wordpress Backup &amp; Restore</a></p><p>☞<a href="https://codequs.com/a/HJO5GDOF">Wordpress Basic to Advanced Tutorials</a></p><p>☞<a href="https://codequs.com/a/S10ZNrCo">How to Create a WordPress Menu Driven Site &amp; blog</a></p><p>☞<a href="https://codequs.com/a/S1D8XceA">WordPress Marketing: Profits With Powerful WordPress Plugins</a></p><p>☞<a href="https://codequs.com/a/BkpRp0Cd">How To Start A Profitable Wordpress Blog Step By Step 2016</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4cf7b79e6ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First Python and Django Application]]></title>
            <link>https://medium.com/@cassycassy/build-your-first-python-and-django-application-95b1356960de?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b1356960de</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Mon, 10 Oct 2016 09:02:39 GMT</pubDate>
            <atom:updated>2016-10-10T09:02:39.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GgPJlmLF0H9nWDohH1dGw.png" /></figure><p>Fix markdown issue on the section for installing pipYou may have heard of Python before, especially if you have been coding for a while.</p><p>If not, Python is a high level, general purpose programming language. What this means is that you can use it to code up anything from a simple game to a website supporting millions of users per month.</p><p>In fact, several high profile sites with millions of visitors per month rely on Python for some of their services. Examples include <a href="https://www.youtube.com/">YouTube</a> and <a href="https://www.dropbox.com/">Dropbox</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OG3kuuarfB-MxNvy.png" /></figure><p>That being said, why should you use Python in the first place? Why not one of the many other popular languages out in the wild like Ruby or PHP? Well, with Python you get the following awesome benefits:</p><ol><li>Easily readable syntax.</li><li>Awesome community around the language.</li><li>Easy to learn.</li><li>Python is useful for a myriad of tasks from basic shell sripting to advanced web development.</li></ol><h3>When Not to Use Python</h3><p>While you can easily write a Desktop app with Python using tools like <a href="http://http//www.wxpython.org/">wxPython</a>, you generally would do better to use the specialized tools offered by the platform you are targeting for example .NET on Windows.</p><p>You should also not use Python when your particular use case has very specialized requirements which are better met by other languages. An example is when you are building an embedded system, a domain in which languages like C, C++ and Java dominate.</p><h3>Python 2 vs Python 3</h3><p>Python 2.7.x and 3.x are both being used extensively in the wild. Python 3 introduced changes into the language which required applications written in Python 2 to be rewritten in order to work with the Python 3.x branch. However, most libraries you will require to use have now been ported to Python 3.</p><p>This tutorial will use Python 3 which is at version 3.5.1 at the time of writing. The principles remain the same though and only minor syntax modifications will be required to get the code running under Python 2.7.x.</p><h3>Some Python Code Samples</h3><h3>Hello World</h3><p>As I said before, one of Python’s main benefits is its’ very easily readable syntax. How easy? Check out Python’s version of the ubiquitous Hello World.</p><pre># This line of code will print &quot;Hello, World!&quot; to your terminal<br>    print(&quot;Hello, World!&quot;)</pre><p>This code prints out Hello, World! to the console. You can easily try out this code by visiting <a href="https://repl.it/languages/python3">this site</a>, pasting the code samples in the editor on the right side of the page, and clicking the run button above the page to see the output.</p><h3>Conditional Logic</h3><p>Conditional logic is just as easy. Here is some code to check if a user’s age is above 18, and if it is, to print Access allowed or Access not allowed otherwise.</p><pre># read in age<br>    age = int(input(&quot;What&#39;s your age?&quot;))</pre><pre>    if age &gt;= 18:<br>        print(&quot;Access allowed&quot;)<br>    elif age &lt; 18 and age &gt; 0:<br>        print(&quot;Access not allowed&quot;)<br>    else:<br>        print(&quot;Invalid age&quot;)</pre><p>The input() function is used to read in keyboard input. You will therefore need to type something in the terminal prompt after running the script for rest of the script to execute. Note that the input() function is wrapped in theint() function.</p><p>This is because input() reads in values as strings and yet we need age to be an integer. We therefore have to cast the keyboard input into a string or else we will get an error for example when checking if the string is greater than 18.</p><p>Finally, note the else statement which executes for any other input which doesn’t fit the criteria being checked for in the if statements.</p><h3>Abstract Data Types</h3><p>Python also has some excellent built in abstract data types for holding collections of items. An example is a list which can be used to hold variables of any type. The following code shows how to create a list and iterate through it to print each item to the terminal.</p><pre># create a list called my_list<br>    my_list = [1, 2, 3, &quot;python&quot;, 67,  [4, 5]]</pre><pre>    # go through my_list and print every item<br>    for item in my_list:<br>        print item</pre><p>The code above creates a list with numbers, a string and a list (yes, lists can contain other lists!). To iterate through lists, a for-in loop comes in handy. Remember, lists are zero-indexed so we can also access list items using indexes. For example, to output the string python, you can write:</p><pre># create a list called my_list<br>    my_list = [1, 2, 3, &quot;python&quot;, 67,  [4, 5]]</pre><pre>    print(my_list[3])</pre><h3>Dictionaries</h3><p>Another excellent data type Python offers out of the box is dictionaries. Dictionaries store key-value pairs, kind of like JSON objects. Creating a dictionary is quite simple as well.</p><pre># create a dictionary<br>    person = {<br>                &quot;name&quot;: &quot;Amos&quot;,<br>                &quot;age&quot;: 23,<br>                &quot;hobbies&quot;: [&quot;Travelling&quot;, &quot;Swimming&quot;, &quot;Coding&quot;, &quot;Music&quot;]<br>            }</pre><pre>    # iterate through the dict and print the keys<br>    for key in person:<br>        print(key)</pre><pre>    # iterate through the dict&#39;s keys and print their values<br>    for key in person:<br>        print(person[key])</pre><p>Now that you know a little bit of Python, let’s talk about Django.</p><h3>Django</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dA-XTgDYfjIRjGYJ.png" /></figure><p><a href="https://www.djangoproject.com/">Django</a> is a Python web framework. It is free and open source and has been around since 2005. It is very mature and comes with excellent documentation and awesome features included by default. Some excellent tools it provides are:</p><ol><li>Excellent lightweight server for development and testing.</li><li>Good templating language.</li><li>Security features like CSRF included right out of the box.</li></ol><p>There are a myriad of other useful things included in Django but you shall probably discover them as you go along. We are going to be using Django to build our website in this tutorial.</p><h3>Setting Up</h3><p>In this tutorial, I will show you how to get a Django website up and running. Before we get there though, first grab a copy of the latest Python from the <a href="https://www.python.org/">Python website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*igBd5Xy5u3uYb-Bx.png" /></figure><blockquote><em>Note that if you are on OSX and you have Homebrew installed you can do</em></blockquote><pre>brew install python3</pre><blockquote><em>After that go straight to the </em><em>Getting started with Django section</em></blockquote><p>After installing the correct version for your OS, you will need to make sure it is set up correctly. Open a terminal and type:</p><pre>python3</pre><p>You should see something resembling the following:</p><pre>Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) <br>    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin<br>    Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>    &gt;&gt;&gt;</pre><p>This is the interactive Python shell. Hit CTRL + D to exit it for now</p><p>Next, we need to install pip. Pip is a python package manager that will enable us to get libraries we require in our app easily such as Django.</p><pre>sudo easy_install pip</pre><h3>Setting Up the Environment</h3><p>To avoid polluting our global scope with unecessary packages, we are going to use a virtual environment to store our packages. One excellent virtual environment manager available for free is virtualenv. You can get it by doing a pip install.</p><pre>pip install virtualenv</pre><p>Once that is done, create a folder called projects anywhere you like then cd into it.</p><pre>mkdir projects</pre><pre>cd projects</pre><p>Once inside the projects folder, create another folder called hello. This folder will hold our app.</p><pre>mkdir hello</pre><p>At this point, we need to create the environment to hold our requirements. We will do this inside the hello folder.</p><pre>virtualenv -p /usr/local/bin/python3 env</pre><p>The -p switch tells virtualenv the path to the python version you want to use. Feel free to switch out the path after it with your own Python installation path. The name env is the environment name. You can also change it to something else which fits the name of your project.</p><p>Once that is done, you should have a folder called env inside your hello folder. Your structure should now look something like this.</p><pre>projects<br>    ├─hello<br>    │   ├── env</pre><p>You are now ready to activate the environment and start coding!</p><pre>source env/bin/activate</pre><p>You will see a prompt with the environment name. That means the environment is active.</p><pre>(env)</pre><h3>Installing Django</h3><p>This is a simple pip install. The latest Django version at the time of writing is Django 1.9.6</p><pre>pip install django</pre><h3>Creating an App</h3><p>Now that Django is installed, we can use its start script to create a skeleton project. This is as simple as using its admin script in the following way.</p><pre>django-admin startproject helloapp</pre><p>Running this command creates a skeleton django app with the following structure:</p><pre>helloapp<br>    ├─helloapp<br>    │   ├── __init__.py<br>    │   ├── settings.py<br>    │   ├── urls.py<br>    │   └── wsgi.py<br>    └── manage.py</pre><p>When you look into the helloapp folder that was created, you will find a file called manage.py and another folder called helloapp. This is your main project folder and contains the project’s settings in a file called settings.py and the routes in your project in the file called urls.py. Feel free to open up the settings.py file to familiarize yourself with its contents.</p><p>Ready to move on? Excellent.</p><h3>Changing App Settings</h3><p>Let’s change a few settings. Open up the settings.py file in your favorite editor. Find a section called Installed Apps which looks something like this.</p><pre># helloapp/settings.py<br>    INSTALLED_APPS = [<br>        &#39;django.contrib.admin&#39;,<br>        &#39;django.contrib.auth&#39;,<br>        &#39;django.contrib.contenttypes&#39;,<br>        &#39;django.contrib.sessions&#39;,<br>        &#39;django.contrib.messages&#39;,<br>        &#39;django.contrib.staticfiles&#39;,<br>    ]</pre><p>Django operates on the concept of apps. An app is a self contained unit of code which can be executed on its own. An app can do many things such as serve a webpage on the browser or handle user authentication or anything else you can think of. Django comes with some default apps preinstalled such as the authentication and session manager apps. Any apps we will create or third-party apps we will need will be added at the bottom of the Installed Apps list after the default apps installed.</p><p>Before we create a custom app, let’s change the application timezone. Django uses the tz database timezones, a list of which can be found <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">here</a>.</p><p>The timezone setting looks like this.</p><pre># helloapp/settings.py<br>    TIME_ZONE = &#39;UTC&#39;</pre><p>Change it to something resembling this as appropriate for your timezone.</p><pre># helloapp/settings.py<br>    TIME_ZONE = &#39;America/Los_Angeles&#39;</pre><h3>Creating your own app</h3><p>It is important to note that Django apps follow the Model, View, Template paradigm. In a nutshell, the app gets data from a model, the view does something to the data and then renders a template containing the processed information. As such, Django templates correspond to views in traditional MVC and Django views can be likened to the controllers found in traditional MVC.</p><p>That being said, let’s create an app. cd into the first helloapp folder and type;</p><pre>python manage.py startapp howdy</pre><p>Running this command will create an app called howdy. Your file structure should now look something like this.</p><pre>helloapp<br>    ├── helloapp<br>    │        ├── __init__.py<br>    │        ├── settings.py<br>    │        ├── urls.py<br>    │        └── wsgi.py<br>    ├── howdy<br>    │        ├── __init__.py<br>    │        ├── admin.py<br>    │        ├── apps.py<br>    │        ├── migrations<br>    │        ├── models.py<br>    │        ├── tests.py<br>    │        └── views.py<br>    └── manage.py</pre><p>To get Django to recognize our brand new app, we need to add the app name to the Installed Apps list in oursettings.py file.</p><pre># helloapp/settings.py<br>    INSTALLED_APPS = [<br>        &#39;django.contrib.admin&#39;,<br>        &#39;django.contrib.auth&#39;,<br>        &#39;django.contrib.contenttypes&#39;,<br>        &#39;django.contrib.sessions&#39;,<br>        &#39;django.contrib.messages&#39;,<br>        &#39;django.contrib.staticfiles&#39;,<br>        &#39;howdy&#39;<br>    ]</pre><p>Once that is done, let’s run our server and see what will be output. We mentioned that Django comes with a built in lightweight web server which, while useful during development, should never be used in production. Run the server as follows:</p><pre>python manage.py runserver</pre><p>Your output should resemble the following:</p><pre>Performing system checks...</pre><pre>    System check identified no issues (0 silenced).</pre><pre>    You have unapplied migrations; your app may not work properly until they are applied.<br>    Run &#39;python manage.py migrate&#39; to apply them.</pre><pre>    June 04, 2016 - 07:42:08<br>    Django version 1.9.6, using settings &#39;helloapp.settings&#39;<br>    Starting development server at http://127.0.0.1:8000/<br>    Quit the server with CONTROL-C.</pre><p>If you look carefully, you will see a warning that you have unapplied migrations. Ignore that for now. Go to your browser and access http://127.0.0.1:8000/. If all is running smoothly, you should see the Django welcome page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pQtH5LQHVPmInvRd.png" /></figure><p>We are going to replace this page with our own template. But first, let’s talk migrations.</p><h3>Migrations</h3><p>Migrations make it easy for you to change your database schema (model) without having to lose any data. Any time you create a new database model, running migrations will update your database tables to use the new schema without you having to lose any data or go through the tedious process of dropping and recreating the database yourself.</p><p>Django comes with some migrations already created for its default apps. If your server is still running, stop it by hitting CTRL + C. Apply the migrations by typing:</p><pre>python manage.py migrate</pre><p>If successful, you will see an output resembling this one.</p><pre>Operations to perform:<br>      Apply all migrations: sessions, auth, contenttypes, admin<br>    Running migrations:<br>      Rendering model states... DONE<br>      Applying contenttypes.0001_initial... OK<br>      Applying auth.0001_initial... OK<br>      Applying admin.0001_initial... OK<br>      Applying admin.0002_logentry_remove_auto_add... OK<br>      Applying contenttypes.0002_remove_content_type_name... OK<br>      Applying auth.0002_alter_permission_name_max_length... OK<br>      Applying auth.0003_alter_user_email_max_length... OK<br>      Applying auth.0004_alter_user_username_opts... OK<br>      Applying auth.0005_alter_user_last_login_null... OK<br>      Applying auth.0006_require_contenttypes_0002... OK<br>      Applying auth.0007_alter_validators_add_error_messages... OK<br>      Applying sessions.0001_initial... OK</pre><p>Running the server now will not show any warnings.</p><h3>Urls &amp; Templates</h3><p>When we ran the server, the default Django page was shown. We need Django to access our howdy app when someone goes to the home page URL which is /. For that, we need to define a URL which will tell Django where to look for the homepage template.</p><p>Open up the urls.py file inside the inner helloapp folder. It should look like this.</p><pre># helloapp/urls.py<br>     &quot;&quot;&quot;helloapp URL Configuration</pre><pre>    The `urlpatterns` list routes URLs to views. For more information please see:</pre><pre>    https://docs.djangoproject.com/en/1.9/topics/http/urls/</pre><pre>    Examples:<br>    Function views<br>        1\. Add an import:  from my_app import views<br>        2\. Add a URL to urlpatterns:  url(https://medium.com/r&#39;^r&#39;^$&#39;, views.home, name=&#39;home&#39;#39;,%20views.home,%20name=&#39;home&#39;)<br>    Class-based views<br>        1\. Add an import:  from other_app.views import Home<br>        2\. Add a URL to urlpatterns:  url(https://medium.com/r&#39;^r&#39;^$&#39;, Home.as_view(#39;,%20Home.as_view(), name=&#39;home&#39;)<br>    Including another URLconf<br>        1\. Import the include() function: from django.conf.urls import url, include<br>        2\. Add a URL to urlpatterns:  url(https://medium.com/r&#39;^blog/&#39;,%20include(&#39;blog.urls&#39;))<br>    &quot;&quot;&quot;<br>    from django.conf.urls import url<br>    from django.contrib import admin</pre><pre>    urlpatterns = [<br>        url(https://medium.com/r&#39;^admin/&#39;,%20admin.site.urls),<br>    ]</pre><p>As you can see, there is an existing URL pattern for the Django admin site which comes by default with Django. Let’s add our own url to point to our howdy app. Edit the file to look like this.</p><pre># helloapp/urls.py<br>    from django.conf.urls import url, include<br>    from django.contrib import admin</pre><pre>    urlpatterns = [<br>        url(https://medium.com/r&#39;^admin/&#39;,%20admin.site.urls),<br>        url(https://medium.com/r&#39;^&#39;,%20include(&#39;howdy.urls&#39;)),<br>    ]</pre><p>Note that we have added an import for include from django.conf.urls and added a url pattern for an empty route. When someone accesses the homepage, (in our case <a href="http://localhost:8000/">http://localhost:8000</a>), Django will look for more url definitions in the howdy app. Since there are none, running the app will produce a huge stack trace due to anImportError.</p><pre>.<br>    .<br>    ImportError: No module named &#39;howdy.urls&#39;</pre><p>Let’s fix that. Go to the howdy app folder and create a file called urls.py. The howdy app folder should now look like this.</p><pre>├── howdy<br>    │   ├── __init__.py<br>    │   ├── admin.py<br>    │   ├── apps.py<br>    │   ├── migrations<br>    │   │   ├── __init__.py<br>    │   ├── models.py<br>    │   ├── tests.py<br>    │   ├── urls.py<br>    │   └── views.py</pre><p>Inside the new urls.py file, write this.</p><pre># howdy/urls.py<br>    from django.conf.urls import url<br>    from howdy import views</pre><pre>    urlpatterns = [<br>        url(https://medium.com/r&#39;^r&#39;^$&#39;, views.HomePageView.as_view(#39;,%20views.HomePageView.as_view()),<br>    ]</pre><p>This code imports the views from our howdy app and expects a view called HomePageView to be defined. Since we don’t have one, open the views.py file in the howdy app and write this code.</p><pre># howdy/views.py<br>    from django.shortcuts import render<br>    from django.views.generic import TemplateView</pre><pre>    # Create your views here.<br>    class HomePageView(TemplateView):<br>        def get(self, request, **kwargs):<br>            return render(request, &#39;index.html&#39;, context=None)</pre><p>This file defines a view called HomePageView. Django views take in a request and return a response. In our case, the method get expects a HTTP GET request to the url defined in our urls.py file. On a side note, we could rename our method to post to handle HTTP POST requests.</p><p>Once a HTTP GET request has been received, the method renders a template called index.html which is just a normal HTML file which could have special Django template tags written alongside normal HTML tags. If you run the server now, you will see the following error page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ns2pD7Pzy8jgpKal.png" /></figure><p>This is because we do not have any templates at all! Django looks for templates in a templates folder inside your app so go ahead and create one in your howdy app folder.</p><pre>mkdir templates</pre><p>Go into the templates folder you just created and create a file called index.html</p><pre>(env) hello/helloapp/howdy/templates<br>     &gt; touch index.html</pre><p>Inside the index.html file, paste this code.</p><pre>&lt;!-- howdy/templates/index.html --&gt;<br>    &lt;!DOCTYPE html&gt;<br>    &lt;html&gt;<br>        &lt;head&gt;<br>            &lt;meta charset=&quot;utf-8&quot;&gt;<br>            &lt;title&gt;Howdy!&lt;/title&gt;<br>        &lt;/head&gt;<br>        &lt;body&gt;<br>            &lt;h1&gt;Howdy! I am Learning Django!&lt;/h1&gt;<br>        &lt;/body&gt;<br>    &lt;/html&gt;</pre><p>Now run your server.</p><pre>python manage.py runserver</pre><p>You should see your template rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ZAqP2AjxPxLoWnC.png" /></figure><h3>Linking pages</h3><p>Let’s add another page. In your howdy/templates folder, add a file called about.html. Inside it, write this HTML code:</p><pre>&lt;!-- howdy/templates/about.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>   &lt;head&gt;<br>       &lt;meta charset=&quot;utf-8&quot;&gt;<br>       &lt;title&gt;Howdy!&lt;/title&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>       &lt;h1&gt;Welcome to the about page&lt;/h1&gt;<br>   &lt;p&gt;<br>   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc quis neque ex. Donec feugiat egestas dictum. In eget erat sit amet elit pellentesque convallis nec vitae turpis. Vivamus et molestie nisl. Aenean non suscipit velit. Nunc eleifend convallis consectetur. Phasellus ornare dolor eu mi vestibulum, ornare tempus lacus imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque ut sem ligula. Mauris volutpat vestibulum dui in cursus. Donec aliquam orci pellentesque, interdum neque sit amet, vulputate purus. Quisque volutpat cursus nisl, in volutpat velit lacinia id. Maecenas id felis diam. <br>   &lt;/p&gt;<br>   &lt;a href=&quot;/&quot;&gt;Go back home&lt;/a&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Once done, edit the original index.html page to look like this.</p><pre>&lt;!-- howdy/templates/index.html --&gt;<br>    &lt;!DOCTYPE html&gt;<br>    &lt;html&gt;<br>        &lt;head&gt;<br>            &lt;meta charset=&quot;utf-8&quot;&gt;<br>            &lt;title&gt;Howdy!&lt;/title&gt;<br>        &lt;/head&gt;<br>        &lt;body&gt;<br>            &lt;h1&gt;Howdy! I am Learning Django!&lt;/h1&gt;<br>         &lt;a href=&quot;/about/&quot;&gt;About Me&lt;/a&gt;<br>        &lt;/body&gt;<br>    &lt;/html&gt;</pre><p>Clicking on the About me link won’t work quite yet because our app doesn’t have a /about/ url defined. Let’s edit the urls.py file in our howdy app to add it.</p><pre># howdy/urls.py<br>    from django.conf.urls import url<br>    from howdy import views</pre><pre>    urlpatterns = [<br>        url(https://medium.com/r&#39;^r&#39;^$&#39;, views.HomePageView.as_view(#39;,%20views.HomePageView.as_view()),<br>        url(https://medium.com/r&#39;^about/r&#39;^about/$&#39;, views.AboutPageView.as_view(#39;,%20views.AboutPageView.as_view()), # Add this /about/ route<br>    ]</pre><p>Once we have added the route, we need to add a view to render the about.html template when we access the/about/ url. Let’s edit the views.py file in the howdy app.</p><pre># howdy/views.py<br>    from django.shortcuts import render<br>    from django.views.generic import TemplateView</pre><pre>    class HomePageView(TemplateView):<br>        def get(self, request, **kwargs):<br>            return render(request, &#39;index.html&#39;, context=None)</pre><pre>    # Add this view<br>    class AboutPageView(TemplateView):<br>        template_name = &quot;about.html&quot;</pre><p>Notice that in the second view, I did not define a get method. This is just another way of using the TemplateViewclass. If you set the template_name attribute, a get request to that view will automatically use the defined template. Try changing the HomePageView to use the format used in AboutPageView.</p><p>Running the server now and accessing the home page should display our original template with the newly added link to the about page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uhlAUxKh7VpiaPv5.png" /></figure><p>Clicking on the About me link should direct you to the About page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RSqq6Spd5XHdGXay.png" /></figure><p>On the About me page, clicking on the Go back home link should redirect you back to our original index page. Try editing both these templates to add more information about you.</p><h3>Conclusion</h3><p>That was just a brief look at how to get a Django website up and running. You can read more about Django on the<a href="https://www.djangoproject.com/">official Django docs</a>. The full code for this tutorial can also be found on <a href="https://github.com/andela-aomondi/helloapp">Github</a>.</p><h3>Suggest</h3><p>☞ <a href="https://school.codequs.com/p/S11HulLd">Learning Python for Data Analysis and Visualization</a></p><p>☞ <a href="https://school.codequs.com/p/ByndHMmO">Learn Python for Beginners!</a></p><p>☞ <a href="https://school.codequs.com/p/BkfCrOT_">Data Science: Deep Learning in Python</a></p><p>☞ <a href="https://school.codequs.com/p/Sk8v6PX_">Python, Ruby, Shell — Scripting for Beginner</a></p><p>☞ <a href="https://school.codequs.com/p/r1JQ5UOF">Python For Android Hacking Crash Course: Trojan Perspective</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b1356960de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to understand node.js easily?]]></title>
            <link>https://medium.com/@cassycassy/how-to-understand-node-js-easily-7362bc7dc2f5?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/7362bc7dc2f5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Fri, 07 Oct 2016 09:05:49 GMT</pubDate>
            <atom:updated>2016-10-07T09:05:49.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BFsDsY_HkgPugjuD.jpg" /></figure><p>To understand how <a href="https://codequs.com/a/H1yVjd-i">Node.js</a> works, first you need to understand a few key features of JavaScript that make it well suited for server-side development. JavaScript is a simple language, but it is also extremely flexible. This flexibility is the reason why it has stood the test of time. First-class functions and closures make it an ideal language for web applications.</p><p>JavaScript has a bad reputation for being unreliable. However, this notion couldn’t be further from the truth. Actually, JavaScript’s bad reputation comes from the DOM’s unreliability. The DOM (docment object model) is the API (application programming interface) that browser vendors provide to interact with the browser using JavaScript. The DOM has idiosyncrasies between browser vendors. However, JavaScript the language is well-defined and can be used reliably across browsers and Node.js. In this tutorial, we discuss a few fundamentals of JavaScript followed by how Node.js used JavaScript to provide a highly performant platform for web applications. Other people complain about how JavaScript handles programming errors (it tries to make invalid code work). However, in such cases, the developers are really to blame, as they need to be careful when working with a highly dynamic language.</p><p>[mks_progressbar name=”” level=”” value=”15″ height=”20″ color=”#ef4f37″ style=”squared”]</p><p>Variables</p><p>Variables are defined in <a href="https://codequs.com/a/HJqC6dN_">JavaScript</a> using the var keyword. For example, the following code segment creates a variable foo and logs it to the console. As you saw in the previous article, you would run this code from your console (terminal on Mac OS X and cmd on Windows) using node variable.js<br>variable.js</p><pre>var foo = 123;<br>console.log(foo); // 123</pre><p>The JavaScript runtime (the browser or Node.js) has the opportunity to define a few global variablesthat we can use in our code. One of them is the console object, which we have been using up to this point. The console object contains a member function (log), which takes any number of arguments and prints them to the console. We will discuss more global objects as they are used. As you will see, JavaScript contains most things you expect a good programming language to have.</p><p>Numbers</p><p>All numbers in JavaScript have the same floating point number type. Arithmetic operations (+,-,*,/,%) work on numbers as you would expect, as shown in</p><p>numbers.js</p><pre>var foo = 3;<br>var bar = 5;<br>console.log(foo + 1);   // 4<br>console.log(foo / bar); // 0.6<br>console.log(foo * bar); // 15<br>console.log(foo - bar); // -2;<br>console.log(foo % 2);   // remainder: 1</pre><p>Boolean</p><p>Two literals are defined for boolean values: true and false. You can assign these to variables and apply boolean operations to them as you would expect.</p><p>boolean.js</p><pre>var foo = true;<br>console.log(foo); // true</pre><pre>// Boolean operations (&amp;&amp;, ||, !) work as expected:<br>console.log(true &amp;&amp; true);   // true<br>console.log(true &amp;&amp; false);  // false<br>console.log(true || false);  // true<br>console.log(false || false); // false<br>console.log(!true);          // false<br>console.log(!false);         // true<br>[mks_progressbar name=&quot;&quot; level=&quot;&quot; value=&quot;40&quot; height=&quot;20&quot; color=&quot;#ef4f37&quot; style=&quot;squared&quot;]</pre><p>Arrays</p><p>You can create arrays quite easily in JavaScript using []. Arrays have many useful functions, a few of which are shown</p><p>arrays.js</p><pre>var foo = [];</pre><pre>foo.push(1);         // add at the end<br>console.log(foo);    // prints [1]</pre><pre>foo.unshift(2);      // add to the top<br>console.log(foo);    // prints [2,1]</pre><pre>// Arrays are zero index based:<br>console.log(foo[0]); // prints 2</pre><p>Object Literals</p><p>By explaining these few fundamental types, we have introduced you to object literals. The most common way of creating an object in JavaScript is using the object notation, {}. Objects can be extended arbitrarily at runtime. An example is shown in</p><p>objectLiterals1.js</p><pre>var foo = {};<br>console.log(foo); // {}<br>foo.bar = 123;    // extend foo<br>console.log(foo); // { bar: 123 }</pre><p>Instead of extending it at runtime, you can define which properties go on an object upfront by using the object literal notation shown</p><p>objectLiterals2.js</p><pre>var foo = {<br>    bar: 123<br>};<br>console.log(foo); // { bar: 123 }</pre><p>You can additionally nest object literals inside object literals, as shown in</p><p>objectLiterals3.js</p><pre>var foo = {<br>    bar: 123,<br>    bas: {<br>        bas1: &#39;some string&#39;,<br>        bas2: 345<br>    }<br>};<br>console.log(foo);</pre><p>And, of course, you can have arrays inside object literals as well, as shown in</p><p>objectLiterals4.js</p><pre>var foo = {<br>    bar: 123,<br>    bas: [1, 2, 3]<br>};<br>console.log(foo);</pre><p>And, you can also have these arrays themselves contain object literals,</p><p>objectLiterals5.js</p><pre>var foo = {<br>    bar: 123,<br>    bas: [{<br>        qux: 1<br>    },<br>    {<br>        qux: 2<br>    },<br>    {<br>        qux: 3<br>    }]<br>};<br>console.log(foo.bar);        // 123<br>console.log(foo.bas[0].qux); // 1<br>console.log(foo.bas[2].qux); // 2</pre><p>Object literals are extremely handy as function arguments and return values.</p><p>[mks_progressbar name=”” level=”” value=”55″ height=”20″ color=”#ef4f37″ style=”squared”]</p><p>Functions</p><p>Functions are really powerful in JavaScript. Most of the power of JavaScript comes from the way it handles the function type. We will examine functions in JavaScript in progressively more involved examples that follow.</p><p>Functions 101</p><p>A normal function structure in JavaScript is defined in</p><p>functionBody.js</p><pre>function functionName() {<br>    // function body<br>    // optional return;<br>}</pre><p>All functions return a value in JavaScript. In the absence of an explicit return statement, a function returns undefined. When you execute the code in , you get undefined on the console.</p><p>functionReturn.js</p><pre>function foo() { return 123; }<br>console.log(foo()); // 123</pre><pre>function bar() { }<br>console.log(bar()); // undefined</pre><p>We will discuss undefined functions more in this article when we look at default values.</p><p>Immediately Executing Function</p><p>You can execute a function immediatelyafter you define it. Simply wrap the function in parentheses () and invoke it, as shown in</p><p>ief1.js</p><pre>(function foo() {<br>    console.log(&#39;foo was executed!&#39;);<br>})();</pre><p>The reason for having an immediately executing function is to create a new variable scope. An if,else, or while does not create a new variable scope in JavaScript. This fact is demonstrated in</p><p>ief2.js</p><pre>var foo = 123;<br>if (true) {<br>    var foo = 456;<br>}<br>console.log(foo); // 456;</pre><p>The only recommended way of creating a new variable scope in JavaScript is using a function. So, in order to create a new variable scope, we can use an immediately executing function, as shown i</p><p><strong><em>.</em></strong> ief3.js</p><pre>var foo = 123;<br>if (true) {<br>    (function () { // create a new scope<br>        var foo = 456;<br>    })();<br>}<br>console.log(foo); // 123;</pre><p>Notice that we choose to avoid needlessly naming the function. This is called an <em>anonymous function</em>, which we will explain next.</p><p>Anonymous Function</p><p>A function without a name is called an anonymous function. In JavaScript, you can assign a function to a variable. If you are going to use a function as a variable, you don’t need to name the function. demonstrates two ways of defining a function inline. Both of these methods are equivalent.</p><p>anon.js</p><pre>var foo1 = function namedFunction() { // no use of name, just wasted characters<br>    console.log(&#39;foo1&#39;);<br>}<br>foo1(); // foo1</pre><pre>var foo2 = function () {              // no function name given i.e. anonymous function<br>    console.log(&#39;foo2&#39;);<br>}<br>foo2(); // foo2</pre><p>A programming language is said to have <em>first-class functions</em> if a function can be treated the same way as any other variable in the language. JavaScript has first-class functions.</p><p>Higher-Order Functions</p><p>Since JavaScript allows us to assign functions to variables, we can pass functions to other functions. Functions that take functions as arguments are called <em>higher-order functions</em>. A very common example of a higher-order function is setTimeout. This is shown in</p><p>higherOrder1.js</p><pre>setTimeout(function () {<br>    console.log(&#39;2000 milliseconds have passed since this demo started&#39;);<br>}, 2000);</pre><p>If you run this application in Node.js, you will see the console.log message after two seconds and then the application will exit. Note that we provided an anonymous function as the first argument tosetTimeout. This makes setTimeout a higher-order function.</p><p>It is worth mentioning that there is nothing stopping us from creating a function and passing that in. An example is shown in</p><p>higherOrder2.js</p><pre>function foo() {<br>    console.log(&#39;2000 milliseconds have passed since this demo started&#39;);<br>}<br>setTimeout(foo, 2000);</pre><p>Now that we have a firm understanding of object literals and functions, we can examine the concept of closures.</p><p>Closures</p><p>Whenever we have a function defined inside another function, the inner function has access to the variables declared in the outer function. Closures are best explained with examples.</p><p>you can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term <em>closure</em>. The concept in itself is simple enough and fairly intuitive.</p><p>closure1.js</p><pre>function outerFunction(arg) {<br>    var variableInOuterFunction = arg;</pre><pre>    function bar() {<br>        console.log(variableInOuterFunction); // Access a variable from the outer scope<br>    }</pre><pre>    // Call the local function to demonstrate that it has access to arg<br>    bar();<br>}</pre><pre>outerFunction(&#39;hello closure!&#39;);              // logs hello closure!</pre><p>Now the awesome part: The inner function can access the variables from the outer scope <em>even after the outer function has returned</em>. This is because the variables are still bound in the inner function and not dependent on the outer function. shows an example.</p><p>closure2.js</p><pre>function outerFunction(arg) {<br>    var variableInOuterFunction = arg;<br>    return function () {<br>        console.log(variableInOuterFunction);<br>    }<br>}</pre><pre>var innerFunction = outerFunction(&#39;hello closure!&#39;);</pre><pre>// Note the outerFunction has returned<br>innerFunction(); // logs hello closure!</pre><p>Now that we have an understanding of first-class functions and closures, we can look at what makes JavaScript a great language for server-side programming.</p><p>Understanding Node.js Performance</p><p>Node.js is focused on creating highly performant applications. In the following section, we introduce the I/O scaling problem. Then we show how it has been solved traditionally, followed by how Node.js solves it.</p><p>The I/O Scaling Problem</p><p>Node.js is focused on being the best way to write highly performant web applications. To understand how it achieves this, we need to know about the I/O scaling problem. Let us look at a rough estimate of the speed at which we can access data from various sources in terms of CPU cycles</p><p>Comparing common I/O sources</p><p>You can clearly see that Disk and Network access is in a completely different category from accessing data that is available in RAM and CPU cache.</p><p>Most web applications depend on reading data from disk or from another network source (for example, a database query). When an HTTP request is received and we need to load data from a database, typically this request will be spent waiting for a disk read or a network access call to complete.</p><p>These open connections and pending requests consume server resources (memory and CPU). In order to handle a large number of requests from different clients using the same web server, we have the I/O scaling problem.</p><p>Traditional Web Servers Using a Process Per Request</p><p>Traditional servers used to spin up a new process to handle every single web request. Spinning a new process for each request is an expensive operation, both in terms of CPU and memory. This is the way technologies like PHP used to work when they were first created.</p><p>In order to successfully reply to an HTTP request “A,” we need some data from a database. This read can potentially take a long time. For this entire read duration, we will have a process taking up CPU and memory while idling and waiting for the database response. Also, processes are slow to start and have a significant overhead in terms of RAM space. This does not scale for very long and that is the reason why modern web applications use a thread pool.</p><p>Traditional Web Servers Using a Thread Pool</p><p>Modern servers use a thread from a thread pool to serve each request. Since we already have a few Operating System (OS) threads created (hence a thread pool), we do not pay the penalty of starting and stopping OS processes (which are expensive to create and take up much more memory than a thread). When a request comes in, we assign a thread to process this request. This thread is reserved for the request in the entire duration that the request is being handled, as demonstrated in</p><p>Traditional web server using a thread pool</p><p>Because we save the overhead of creating a new process every time and the threads are lighter than processes, this method is much better than the original server design. Most web servers used this method a few years back and many continue to use today. However, this method is not without drawbacks. Again there is wasting of RAM between threads. Also the OS needs to context switch between threads (even when they are idle), and this results in wasted CPU resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*MkqZYtttMkn6QkfF.jpg" /></figure><p>The Nginx Way</p><p>We have seen that creating separate processes and separate threads to handle requests results in wasted OS resources. The way Node.js works is that there is a single thread handling requests. The idea that a single threaded server can perform better than a thread pool server is not new to Node.js. Nginx is built on this principle.</p><p>Nginx is a single-threaded web server and can handle a tremendous amount of concurrent requests. A simple benchmark comparing Nginx to Apache, both serving a single static file from the file system, is shown in</p><p>[</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*005nzPyWUxMBPByo.jpg" /></figure><p>Nginx vs. Apache requests/second vs. concurrent open connections</p><p>As you can see, when the number of concurrent connections goes up, Nginx can handle a lot more requests per second than Apache. What is more interesting is the memory consumption, as shown [</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*xLFJzD_R5JJqgAim.jpg" /></figure><p>Nginx vs. Apache memory usage vs. concurrent connections</p><p>With more concurrent connections, Apache needs to manage more threads and therefore consumes much more memory, whereas Nginx stays at a steady level.</p><p>Node.js Performance Secret</p><p>There is a single execution thread in JavaScript. This is the way web browsers have traditionally worked. If you have a long-running operation (such as waiting for a timer to complete or a database query to return), you must continue operation using a callback. provides a simple demo that uses the JavaScript runtime setTimeout function to simulate a long-running operation. You can run this code using Node.js.</p><p>simulateUserClick.js</p><pre>function longRunningOperation(callback) {<br>    // simulate a 3 second operation<br>    setTimeout(callback, 3000);<br>}</pre><pre>function userClicked() {<br>    console.log(&#39;starting a long operation&#39;);<br>    longRunningOperation(function () {<br>        console.log(&#39;ending a long operation&#39;);<br>    });<br>}<br>// simulate a user action<br>userClicked();</pre><p>This simulation is possible in JavaScript because we have first-class functions and passing functions — a callback is a well-supported pattern in the language. Things become interesting when you combine first-class functions with the concept of closures. Let us image that we are handling a web request and we have a long-running operation such as a database query that we need to do. A simulated version is shown</p><p>simulateWebRequest.js</p><pre>function longRunningOperation(callback) {<br>    // simulate a 3 second operation<br>    setTimeout(callback, 3000);<br>}</pre><pre>function webRequest(request) {<br>    console.log(&#39;starting a long operation for request:&#39;, request.id);<br>    longRunningOperation(function () {<br>        console.log(&#39;ending a long operation for request:&#39;, request.id);<br>    });<br>}<br>// simulate a web request<br>webRequest({ id: 1 });<br>// simulate a second web request<br>webRequest({ id: 2 });</pre><p>, because of closures, we have access to the correct user request after the long-running operation completes. We just handled two requests on a single thread without breaking a sweat. Now you should understand the following statement: “Node.js is highly performant, and it uses JavaScript because JavaScript supports first-class functions and closures.”</p><p>The immediate question that should come to mind when someone tells you that you only have a single thread to handle requests is, “But my computer has a quad core CPU. Using only a single thread will surely waste resources.” And the answer is that yes it will. However, there is a well-supported way around it that we will examine in when discussing deployment and scalability. Just a quick tip about what you will see there: It is actually really simple to use all the CPU cores with a separate JavaScript process for each CPU core using Node.js.</p><p>It is also important to note that there are threads managed by Node.js at the C level (such as for certain file system operations), but all the JavaScript executes in a single thread. This gives you the performance advantage of the JavaScript almost completely owning at least one thread.</p><p>More Node.js Internals</p><p>It is not terribly important to understand the internals of how Node.js works, but a bit more discussion make you more aware of the terminology when you discuss Node.js with your peers. At the heart of Node.js is an <em>event loop</em>.</p><p>Event loops enable any GUI application to work on any operating system. The OS calls a function within your application when something happens (for example, the user clicks a button), and then your application executes the logic contained inside this function to completion. Afterward, your application is ready to respond to new events that might have already arrived (and are there on the queue) or that might arrive later (based on user interaction).</p><p>Thread Starvation</p><p>Generally during the duration of a function called from an event in a GUI application, no other events can be processed. Consequently, if you do a long-running task within something like a click handler, the GUI will become unresponsive. This is something every computer user I have met has experienced at one point or another. This lack of availability of CPU resources is called <em>starvation</em>.</p><p>Node.js is built on the same event loop principle as you find in GUI programs. Therefore, it too can suffer from starvation. To understand it better, let’s go through a few code examples shows a small snippet of code that measures the time passed using console.time andconsole.timeEnd functions.</p><p>timeit.js</p><pre>console.time(&#39;timer&#39;);<br>setTimeout(function(){<br>   console.timeEnd(&#39;timer&#39;);<br>},1000)</pre><p>If you run this code, you should see a number quite close to what you would expect — in other words, 1000ms. This callback for the timeout is called from the Node.js event loop.</p><p>Now let’s write some code that takes a long time to execute, for instance, a nonoptimized method of calculating the nth Fibonacci number as shown in</p><p>largeOperation.js</p><pre>console.time(&#39;timeit&#39;);<br>function fibonacci(n) {<br>    if (n &lt; 2)<br>        return 1;<br>    elses<br>        return fibonacci(n - 2) + fibonacci(n - 1);<br>}<br>fibonacci(44);             // modify this number based on your system performance<br>console.timeEnd(&#39;timeit&#39;); // On my system it takes about 9000ms (i.e. 9 seconds)</pre><p>Now we have an event that can be raised from the Node.js event loop (setTimeout) and a function that can keep the JavaScript thread busy (fibonacci). We can now demonstrate starvation in Node.js. Let’s set up a time-out to execute. But before this time-out completes, we execute a function that takes a lot of CPU time and therefore holds up the CPU and the JavaScript thread. As this function is holding on to the JavaScript thread, the event loop cannot call anything else and therefore the time-out is delayed, as demonstrated in</p><p>starveit.js</p><pre>// utility funcion<br>function fibonacci(n) {<br>    if (n &lt; 2)<br>        return 1;<br>    else<br>        return fibonacci(n - 2) + fibonacci(n - 1);<br>}</pre><pre>// setup the timer<br>console.time(&#39;timer&#39;);<br>setTimeout(function () {<br>    console.timeEnd(&#39;timer&#39;); // Prints much more than 1000ms<br>}, 1000)</pre><pre>// Start the long running operation<br>fibonacci(44);</pre><p>One lesson here is that Node.js is not the best option if you have a high CPU task that you need to do <em>on a client request</em> in a multiclient server environment. However, if this is the case, you will be very hard-pressed to find a scalable software solution in any platform. Most high CPU tasks should take place offline and are generally offloaded to a database server using things such as materialized views, map reduce, and so on. Most web applications access the results of these computations over the network, and this is where Node.js shines — evented network I/O.</p><p>Now that you understand what an event loop means and the implications of the fact that JavaScript portion of Node.js is single-threaded, let’s take another look at why Node.js is great for I/O applications.</p><p>Data-Intensive Applications</p><p>Node.js is great for data-intensive applications. As we have seen, using a single thread means that Node.js has an extremely low-memory footprint when used as a web server and can potentially serve a lot more requests. Consider the simple scenario of a data intensive application that serves a dataset from a database to clients via HTTP. We know that gathering the data needed to respond to the client query takes a long time compared to executing code and/or reading data from RAM. shows how a traditional web server with a thread pool would look while it is responding to just two requests.</p><p>[</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/0*7Y0Acm_5XpiYIe7Q.jpg" /></figure><p>How a traditional server handles two requests</p><p>The same server in Node.js is shown in All the work is going to be inside a single thread, which results in lesser memory consumption and, due to the lack of thread context switching, lesser CPU load. Implementation-wise, the handleClientRequest is a simple function that calls out to the database (using a callback). When that callback returns, it completes the request using the request object it captured with a JavaScript closure. This is shown in the pseudocode</p><p>.How a Node.js server handles two requests</p><p><strong><em>.</em></strong> handleClientRequest.js</p><pre>function handleClientRequest(request) {<br>    makeDbCall(request.someInfo, function (result) {<br>        // The request corresponds to the correct db result because of closure<br>        request.complete(result);<br>    });<br>}</pre><p>Note that the HTTP request to the database is also managed by the event loop. The advantage of having async IO and why JavaScript + Node.js is a great fit for data-intensive applications should now be clear.</p><p>The V8 JavaScript Engine</p><p>It is worth mentioning that all the JavaScript inside Node.js is executed by the V8 JavaScript engine. V8 came into being with the Google Chrome project. V8 is the part of Chrome that runs the JavaScript when you visit a web page.</p><p>Anybody who has done any web development knows how amazing Google Chrome has been for the web. The browser usage statistics reflect that quite clearly. According to <a href="http://w3schools.org/">w3schools.org</a>(<a href="http://www.w3schools.com/browsers/browsers_stats.asp">www.w3schools.com/browsers/browsers_stats.asp</a>), nearly 56% of Internet users who visit their web site are now using Google Chrome. There are lots of reasons for this, but V8 and its speed is a very important factor. Besides speed, another reason for using V8 is that the Google engineers made it easy to integrate into other projects, and that it is platform independent.</p><p>More JavaScript</p><p>Now that we understand the motivation for using Node.js, let’s delve further into JavaScript so that we can write maintainable applications. In addition to the fact that you need to be good at JavaScript if you want to become a Node.js developer, another reason to be good at JavaScript is to take advantage of the thriving ecosystem around Node.js and JavaScript in general. The language with the greatest number of projects on GitHub is JavaScript. Node.js is the most popular server-side technology on GitHub, as shown and the third most popular repository overall.</p><p>[</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*7Dd31vWfYD6wRAzK.jpg" /></figure><p>Most popular repositories on GitHub</p><p>Everything Is a Reference</p><p>JavaScript was designed to be simple and work with limited computer resources. Whenever we assign one variable to another, JavaScript copies a reference to the variable. To understand what this means, have a look at</p><p>reference1.js</p><pre>var foo = { bas: 123 };<br>var bar = foo;<br>bar.bas = 456;<br>console.log(foo.bas); // 456</pre><p>Passing objects around in function calls is extremely lightweight no matter what the size of the object, since we only copy the reference to the object and not every single property of the object. To make true copies of data (that break the reference link), you can just create a new object literal as shown</p><p>reference2.js</p><pre>var foo = { bas: 123 };<br>var bar = { bas: foo.bas }; // copy</pre><pre>bar.bas = 456;              // change copy<br>console.log(foo.bas);       // 123, original is unchanged</pre><p>We can use quite a few third-party libraries to copy properties for arbitrary JavaScript objects. (It is a simple function we can write ourselves if we wanted.)</p><p>Default Values</p><p>The default value of any variable in JavaScript is undefined. You can see it being logged out where you create a variable but do not assign anything to it.</p><p>default1.js</p><pre>var foo;<br>console.log(foo); // undefined</pre><p>Similarly, a nonexistent property on a variable returns undefined</p><p>default2.js</p><pre>var foo = { bar: 123 };<br>console.log(foo.bar); // 123<br>console.log(foo.bas); // undefined</pre><p>Exact Equality</p><p>One thing to be careful about in JavaScript is the difference between == and === As JavaScript tries to be resilient against programming errors, == tries to do type coercion between two variables. For example, it converts a string to a number so that you can compare it with a number, as shown in</p><p>**<em>.</em>**equal1.js</p><pre>console.log(5 == &#39;5&#39;);  // true<br>console.log(5 === &#39;5&#39;); // false</pre><p>However, the choices it makes are not always ideal. For example, in the first statement is false because ’’ and ‘0’ are both strings and are clearly not equal. However, in the second case, both ‘0’ and the empty string (’’) are falsy (in other words, they behave like false) and are therefore equal with respect to ==. Both statements are false when you use ===.</p><p>equal2.js</p><pre>console.log(&#39;&#39; == &#39;0&#39;);  // false<br>console.log(&#39;&#39; == 0);    // true</pre><pre>console.log(&#39;&#39; === &#39;0&#39;); // false<br>console.log(&#39;&#39; === 0);   // false</pre><p>The tip here is to not compare different types to each another. Comparing different types of variables (such as a string with a number) is something you would not be able to do in a statically typed language anyway (a statically typed language is one where you <em>must</em> specify the type of a variable). If you keep this in mind, you can safely use ==. However, it is recommended that you always use === whenever possible.</p><p>Similar to == vs. ===, there are the inequality operators != and !==, which work in the same way. In other words, != does type coercion, whereas !== is strict.</p><p>null</p><p>null is a special JavaScript object used to denote an empty object. This is different from undefined, which is used by JavaScript for nonexistent and noninitialized values. You should not set anything toundefined because, by convention, undefined is the default value you should leave to the runtime. A good time to use null is when you want to explicitly say that something is not there, such as as a function argument. You will see its usage in the section on error handling in this tutorial.</p><p>Truthy and Falsy</p><p>One important concept in JavaScript is truthy values and falsy values. Truthy values are those that behave like true in boolean operations and falsy values are those that behave like false in boolean operations. It is generally easier to use if / else / ! for null / undefined instead of doing an explicit check. An example of the falsy nature of these values is shown in</p><p>truthyandfalsy.js</p><pre>console.log(null == undefined);  // true<br>console.log(null === undefined); // false</pre><pre>// Are these all falsy?<br>if (!false) {<br>    console.log(&#39;falsy&#39;);<br>}<br>if (!null) {<br>    console.log(&#39;falsy&#39;);<br>}<br>if (!undefined) {<br>    console.log(&#39;falsy&#39;);<br>}</pre><p>Other important falsy values are 0 and the empty string (”). All object literals and arrays are truthy in JavaScript.</p><p>Revealing Module Pattern</p><p>Functions that return objects are a great way to create similar objects. An object here means data and functionality bundled into a nice package, which is the most basic form of Object Oriented Programming (OOP) that one can do. At the heart of the revealing module pattern is JavaScript’s support for closures and ability to return arbitrary (function + data) object literals. is a simple example that shows how to create an object using this pattern.</p><p>revealingModules.js</p><pre>function printableMessage() {<br>    var message = &#39;hello&#39;;<br>    function setMessage(newMessage) {<br>        if (!newMessage) throw new Error(&#39;cannot set empty message&#39;);<br>        message = newMessage;<br>    }<br>    function getMessage() {<br>        return message;<br>    }</pre><pre>    function printMessage() {<br>        console.log(message);<br>    }</pre><pre>    return {<br>        setMessage: setMessage,<br>        getMessage: getMessage,<br>        printMessage: printMessage<br>    };<br>}</pre><pre>// Pattern in use<br>var awesome1 = printableMessage();<br>awesome1.printMessage(); // hello</pre><pre>var awesome2 = printableMessage();<br>awesome2.setMessage(&#39;hi&#39;);<br>awesome2.printMessage(); // hi</pre><pre>// Since we get a new object everytime we call the module function<br>// awesome1 is unaffected by awesome2<br>awesome1.printMessage(); // hello</pre><p>The great thing about this example is that it is a simple pattern to understand because it only utilizes closures, first-class functions, and object literals — concepts that are already familiar to you and that we covered extensively in the beginning of this tutorial.</p><p>Understanding this</p><p>The JavaScript keyword <strong>this</strong> has a very special place in the language. It is something that is passed to the function depending upon how you call it (somewhat like a function argument). The simplest way to think of it is that it refers to the calling context. The calling context is the prefix used to call a function. demonstrates its basic usage.</p><p>this1.js</p><pre>var foo = {<br>    bar: 123,<br>    bas: function () {<br>        console.log(&#39;inside this.bar is:&#39;, this.bar);<br>    }<br>}</pre><pre>console.log(&#39;foo.bar is: &#39;, foo.bar); // foo.bar is: 123<br>foo.bas();                            // inside this.bar is: 123</pre><p>Inside the function bas, this refers to foo since bas was called on foo and is therefore the calling context. So, what is the calling context if I call a function without any prefix? The default calling context is the Node.js global variable, as shown in</p><p>this2.js</p><pre>function foo() {<br>    console.log(&#39;is this called from globals? : &#39;, this === global); // true<br>}<br>foo();</pre><p>Note that if we were running it in the browser, the global variable would be window instead of global.</p><p>Of course, since JavaScript has great support for first-class functions, we can attach a function to any object and change the calling context, as shown in</p><p>this3.js</p><pre>var foo = {<br>    bar: 123<br>};</pre><pre>function bas() {<br>    if (this === global)<br>        console.log(&#39;called from global&#39;);<br>    if (this === foo)<br>        console.log(&#39;called from foo&#39;);<br>}</pre><pre>// global context<br>bas();     // called from global</pre><pre>// from foo<br>foo.bas = bas;<br>foo.bas(); // called from foo</pre><p>There is one last thing you need to know about this in JavaScript. If you call a function with the newJavaScript operator, it creates a new JavaScript object and this within the function refers to this newly created object. Again,provides another simple example.</p><p>this4.js</p><pre>function foo() {<br>    this.foo = 123;<br>    console.log(&#39;Is this global?: &#39;, this == global);<br>}</pre><pre>// without the new operator<br>foo(); // Is this global?: true<br>console.log(global.foo); // 123</pre><pre>// with the new operator<br>var newFoo = new foo();  // Is this global?: false<br>console.log(newFoo.foo); // 123</pre><p>You can see that we modified this.foo inside the function and newFoo.foo was set to that value.</p><p>Understanding Prototype</p><p>It is a common misunderstanding that JavaScript isn’t object-oriented. It is indeed true that until recently JavaScript has not had the class keyword. But functions in JavaScript are more powerful than they are in many other languages and can be used to mimic traditional object oriented principles. The secret sauce is the new keyword (which you have already seen) and a property called theprototype. Every object in JavaScript has an internal link to another object called the prototype. Before we look at creating traditional classes in JavaScript, let’s have a deeper look at prototype.</p><p>When you read a property on an object (for example, foo.bar reads the property bar from foo), JavaScript checks that this property exists on foo. If not, JavaScript checks if the property exists onfoo.<strong>proto</strong> and so on till <strong>proto</strong> itself is not present. If a value is found at any level, it is returned. Otherwise, JavaScript returns undefined</p><p>prototype1.js</p><pre>var foo = {};<br>foo.__proto__.bar= 123;<br>console.log(foo.bar); // 123</pre><p>Although this works, the __ prefix in JavaScript is conventionally used for properties that should not be used by user code (in other words, private/internal implementation details). Therefore, you should not use <strong>proto</strong> directly. The good news is that when you create an object using the new operator on a function, the <strong>proto</strong> is set to the function’s .prototype member, whichcan be verified with a simple bit of code, as shown in</p><p>prototype2.js</p><pre>// Lets create a test function and set a member on its prototype<br>function foo() { };<br>foo.prototype.bar = 123;</pre><pre>// Lets create a object using `new`<br>// foo.prototype will be copied to bas.__proto__<br>var bas = new foo();</pre><pre>// Verify the prototype has been copied<br>console.log(bas.__proto__ === foo.prototype); // true<br>console.log(bas.bar);                         // 123</pre><p>The reason why this is great is because prototypes are shared between all the objects (let’s call theseinstances) created from the same function. This fact is shown</p><p>prototype3.js</p><pre>// Lets create a test function and set a member on its prototype<br>function foo() { };<br>foo.prototype.bar = 123;</pre><pre>// Lets create two instances<br>var bas = new foo();<br>var qux = new foo();</pre><pre>// Show original value<br>console.log(bas.bar); // 123<br>console.log(qux.bar); // 123</pre><pre>// Modify prototype<br>foo.prototype.bar = 456;</pre><pre>// All instances changed<br>console.log(bas.bar); // 456<br>console.log(qux.bar); // 456</pre><p>Imagine you need 1,000 instances created. All the functionality you put on prototype is shared. And therefore lesson one: saves memory.</p><p>Prototype is great for reading data off an object. However, if you set a property on the object, you break the link with the prototype because (as explained earlier) the prototype is only accessed if the property does not exist on the object. This disconnection from a prototype property caused by setting a property on an object is shown in</p><p>prototype4.js</p><pre>// Lets create a test function and set a member on its prototype<br>function foo() { };<br>foo.prototype.bar = 123;</pre><pre>// Lets create two instances<br>var bas = new foo();<br>var qux = new foo();</pre><pre>// Overwrite the prototype value for bas<br>bas.bar = 456;<br>console.log(bas.bar); // 456 i.e. prototype not accessed</pre><pre>// Other objects remain unaffected<br>console.log(qux.bar); // 123</pre><p>You can see that when we modified bas.bar, bas.<strong>proto</strong>.bar was no longer accessed. Hence, lesson two: .prototype is not good for properties you plan on writing to.</p><p>The question becomes what we should use for properties we need to write to. Recall from our discussion on this that this refers to the object that is created when the function is called with thenew operator. So this is a perfect candidate for read/write properties and you should use it for all properties. But functions are generally not altered after creation. So functions are great candidates to go on .prototype. This way, functionality (functions/methods) is shared between all instances, and properties belong on individual objects. Now we can understand a pattern to write a class in JavaScript, which is shown in</p><p>class.js</p><pre>// Class definition<br>function someClass() {<br>    // Properties go here<br>    this.someProperty = &#39;some initial value&#39;;<br>}<br>// Member functions go here:<br>someClass.prototype.someMemberFunction = function () {<br>    /* Do something using this */<br>    this.someProperty = &#39;modified value&#39;;<br>}</pre><pre>// Creation<br>var instance = new someClass();</pre><pre>// Usage<br>console.log(instance.someProperty); // some initial value<br>instance.someMemberFunction();<br>console.log(instance.someProperty); // modified value</pre><p>Within the member function, we can get access to the current instance using this even though the same function body is shared between all instances. The reason should be obvious from our earlier discussion on this and the calling context. It is because we call a function on some instance, in other words, instance.someMemberFunction(). That is why inside the function this will refer to theinstance used.</p><p>The main difference here vs. the revealing module pattern is that functions are shared between all the instances and don’t take up memory for each new instance. This is because functions are only on.prototype and not on this. Most classes inside core Node.js are written using this pattern.</p><p>Error Handling</p><p>Error handling is an important part of any application. Errors can happen because of your code or even in code not in your controls, for example, database failure.</p><p>JavaScript has a great exception handling mechanism that you might already be familiar with from other programming languages. To throw an exception, you simply use the throw JavaScript keyword. To catch an exception, you can use the catch keyword. For code you want to run regardless of whether an exception was caught or not, you can use the finally keyword. . is a simple example that demonstrates this.</p><p>. error1.js</p><pre>try {<br>    console.log(&#39;About to throw an error&#39;);<br>    throw new Error(&#39;Error thrown&#39;);<br>}<br>catch (e) {<br>    console.log(&#39;I will only execute if an error is thrown&#39;);<br>    console.log(&#39;Error caught: &#39;, e.message);<br>}<br>finally {<br>    console.log(&#39;I will execute irrespective of an error thrown&#39;);<br>}</pre><p>The catch section executes only if an error is thrown. The finally section executes despite any errors thrown within the try section. This method of exception handling is great for synchronous JavaScript. However, it will not work under an async workflow. demonstrates this shortcoming.</p><p>error2.js</p><pre>try {<br>    setTimeout(function () {<br>        console.log(&#39;About to throw an error&#39;);<br>        throw new Error(&#39;Error thrown&#39;);<br>    }, 1000);<br>}<br>catch (e) {<br>    console.log(&#39;I will never execute!&#39;);<br>}</pre><pre>console.log(&#39;I am outside the try block&#39;);</pre><p>The reason why it does not work is because at the point in time when the callback for setTimeoutexecutes, we would already be outside the try/catch block. The setTimeout is going to call the function provided at a later point, and you can see that happen in this code sample since “I am outside the try block” is executed. The default behavior for uncaught exceptions in Node.js is to exit the process, and this is why our application crashes.</p><p>The correct way of doing this is to handle the error insidethe callback, as shown shown in</p><p>error3.js</p><pre>setTimeout(function () {<br>    try {<br>        console.log(&#39;About to throw an error&#39;);<br>        throw new Error(&#39;Error thrown&#39;);<br>    }<br>    catch (e) {<br>        console.log(&#39;Error caught!&#39;);<br>    }<br>}, 1000);</pre><p>This method works fine from inside an async function. But now we have an issue of finding a way to tell the code outside about the error. Let’s look at a concrete example. Consider a simplegetConnection function that takes a callbackwe need to call after a successful connection, as shown in</p><p>error4.js</p><pre>function getConnection(callback) {<br>    var connection;<br>    try {<br>        // Lets assume that the connection failed<br>        throw new Error(&#39;connection failed&#39;);</pre><pre>        // Notify callback that connection succeeded?<br>    }<br>    catch (error) {<br>        // Notify callback about error?<br>    }<br>}<br>[mks_progressbar name=&quot;&quot; level=&quot;&quot; value=&quot;95&quot; height=&quot;20&quot; color=&quot;#ef4f37&quot; style=&quot;squared&quot;]</pre><p>We need to notify the callback about success and failure. This is why Node.js has a convention of calling callbacks with the first argument of error if there is an error. If there is no error, we call back with the error set to null. As a result, a getConnection function designed for the Node.js ecosystem would be something like what is shown in</p><p>error5.js</p><pre>function getConnection(callback) {<br>    var connection;<br>    try {<br>        // Lets assume that the connection failed<br>        throw new Error(&#39;connection failed&#39;);</pre><pre>        // Notify callback that connection succeeded?<br>        callback(null, connection);<br>    }<br>    catch (error) {<br>        // Notify callback about error?<br>        callback(error, null);<br>    }<br>}</pre><pre>// Usage<br>getConnection(function (error, connection) {<br>    if (error) {<br>        console.log(&#39;Error:&#39;, error.message);<br>    }<br>    else {<br>        console.log(&#39;Connection succeeded:&#39;, connection);<br>    }<br>});</pre><p>Having the error as the first argument ensures consistency in error checking. This is the convention followed by all Node.js functions that have an error condition. A good example of this is the file system API, which we cover in future . Also note that developers tend to use the falsy nature of null to check for errors.</p><p>Summary</p><p>In this article we discussed important JavaScript concepts necessary to to be successful with Node.js. You should now have a deep understanding of what makes JavaScript and Node.js great for creating data-intensive applications and why it performs better than the technologies that preceded it. In the next tutorial, we will discuss more Node.js specific patterns and practices for creating maintainable applications.</p><p>Works Cited</p><p>Ryan Dahl (2009) Node.js from JSConf.</p><p>“Nginx vs. Apache,” <a href="http://blog.webfaction.com/2008/12/a-little-holiday-present-10000-reqssec-with-nginx-2/">http://blog.webfaction.com/2008/12/a-little-holiday-present-10000-reqssec-with-nginx-2/</a></p><p>“Browser Statistics,” <a href="http://www.w3schools.com/browsers/browsers_stats.asp">http://www.w3schools.com/browsers/browsers_stats.asp</a></p><p>“GitHub Repository Search by Stars,” <a href="https://github.com/search?o=desc&amp;q=stars%3A%3E1&amp;s=stars&amp;type=Repositories">https://github.com/search?o=desc&amp;q=stars%3A%3E1&amp;s=stars&amp;type=Repositories</a></p><h4>Suggest</h4><p>☞ <a href="https://codequs.com/a/BksJidbo">All about NodeJS</a></p><p>☞ <a href="https://codequs.com/a/HJwY85__">Learn Nodejs by Building 12 Projects</a></p><p>☞ <a href="https://codequs.com/a/SJOOCdEO">JavaScript Tutorials: Understanding the Weird Parts</a></p><p>☞ <a href="https://codequs.com/a/SJv5lWPF">Learn How To Deploy Node.Js App on Google Compute Engine</a></p><p>☞ <a href="https://codequs.com/a/rkAHdYU9">Become a Modern Web Developer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7362bc7dc2f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grokking Scope in JavaScript]]></title>
            <link>https://medium.com/@cassycassy/grokking-scope-in-javascript-52bacebadc66?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bacebadc66</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Tue, 20 Sep 2016 08:38:45 GMT</pubDate>
            <atom:updated>2016-09-20T08:38:45.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILgLx1TRUvYt5Ayfy5zjRA.png" /></figure><p>Scope, or the set of rules that determine where your variables live, is one of the most basic concepts of any programming language. It’s so fundamental, in fact, that it’s easy to forget how subtle the rules can be!</p><p>Understanding exactly how the <a href="https://codequs.com/a/Bys1Didu">JavaScript</a> engine “thinks” about scope will keep you from writing the common bugs that hoisting can cause, prepare you to wrap your head around closures, and get you that much closer to never writing bugs <em>ever</em> again.</p><p>… Well, it’ll help you understand hoisting and closures, anyway.</p><p>In this article, we’ll take a look at:</p><ul><li>the basics of scopes in JavaScript</li><li>how the interpreter decides what variables belong to what scope</li><li>how hoisting <em>really</em> works</li><li>how the ES6 keywords let and const change the game</li></ul><p>Let’s dive in.</p><h3>Lexical Scope</h3><p>If you’ve written even a line of JavaScript before, you’ll know that where you <em>define</em> your variables determines where you can <em>use</em> them. The fact that a variable’s visibility depends on the structure of your source code is called <em>lexical</em> <em>scope.</em></p><p>There are three ways to create scope in JavaScript:</p><ol><li><strong>Create a function</strong>. Variables declared inside functions are visible only inside that function, including in nested functions.</li><li><strong>Declare variables with </strong>let or const <strong>inside a code block</strong>. Such declarations are only visible inside the block.</li><li><strong>Create a </strong>catch <strong>block</strong>. Believe it or not, this actually <em>does</em> create a new scope!</li></ol><p><em>“use strict”;<br>var mr_global = “Mr Global”;</em><br> <br><em>function foo () {<br> var mrs_local = “Mrs Local”;<br> console.log(“I can see “ + mr_global + “ and “ + mrs_local + “.”);<br> function bar () {<br> console.log(“I can also see “ + mr_global + “ and “ + mrs_local + “.”);<br> }<br>} <br>foo(); // Works as expected</em><br> <br><em>try {<br> console.log(“But /I/ can’t see “ + mrs_local + “.”); <br>} catch (err) {<br> console.log(“You just got a “ + err + “.”);<br>} <br>{<br> let foo = “foo”;<br> const bar = “bar”;<br> console.log(“I can use “ + foo + bar + “ in its block…”);</em><br><em>} <br>try {<br> console.log(“But not outside of it.”); <br>} catch (err) {<br> console.log(“You just got another “ + err + “.”);<br>}<br>// Throws ReferenceError!<br>console.log(“Note that “ + err + “ doesn’t exist outside of ‘catch’!”)</em></p><p>The snippet above demonstrates all three scope mechanisms. You can run it in Node or Firefox, but Chrome doesn’t play nice with let, yet.</p><p>We’ll talk about each of these in exquisite detail. Let’s start with a detailed look at how <a href="https://codequs.com/a/B1diIGBj">JavaScript</a> figures out what variables belong to what scope.</p><h3>The Compilation Process: A Bird’s Eye View</h3><p>When you run a piece of JavaScript, two things happen to make it work.</p><ol><li>First, your source gets compiled.</li><li>Then, the compiled code gets executed.</li></ol><p>During the <em>compilation step</em>, the JavaScript engine:</p><ol><li>takes note of all of your variable names</li><li>registers them in the appropriate scope</li><li>reserves space for their values</li></ol><p>It’s only during <em>execution</em> that the <a href="https://codequs.com/a/BJgqRypu">JavaScript</a> engine actually sets the value of variable references equal to their assignment values. Until then, they’re undefined.</p><h3>Step 1: Compilation</h3><p>// I can use first_name anywhere in this program <br><em>var first_name = “Peleke”;<br> <br>function popup (first_name) {<br> // I can only use last_name inside of this function<br> var last_name = “Sengstacke”;<br> alert(first_name + ‘ ‘ + last_name);<br>}</em><br> <br>popup(first_name);</p><p>Let’s step through what the compiler does.</p><p>First, it reads the line var first_name = “Peleke”. Next, it determines what <em>scope</em> to save the variable to. Because we’re at the top level of the script, it realizes we’re in the <em>global scope</em>. Then, it saves the variable first_name to the global scope and initializes its value to undefined.</p><p>Second, the compiler reads the line with function popup (first_name). Because the <em>function</em> keyword is the first thing on the line, it creates a new scope for the function, registers the function’s definition to the global scope, and peeks inside to find variable declarations.</p><p>Sure enough, the compiler finds one. Since we have var last_name = “Sengstacke” in the first line of our function, the compiler saves the variable last_name to the scope of popup — <em>not</em> to the global scope — and sets its value to undefined.</p><p>Since there are no more variable declarations inside the function, the compiler steps back into the global scope. And since there are no more variable declarations <em>there</em>, this phase is done.</p><p>Note that we haven’t actually <em>run</em> anything yet. The compiler’s job at this point is just to make sure it knows everyone’s name; it doesn’t care <em>what</em> they do.</p><p>At this point, our program knows that:</p><ol><li>There’s a variable called first_name in the global scope.</li><li>There’s a function called popup in the global scope.</li><li>There’s a variable called last_name in the scope of popup.</li><li>The values of both first_name and last_name are undefined.</li></ol><p>It doesn’t care that we’ve assigned those variables values elsewhere in our code. The engine takes care of that in <em>execution</em>.</p><h3>Step 2: Execution</h3><p>During the next step, the engine reads our code again, but this time, <em>executes</em> it.</p><p>First, it reads the line, var first_name = “Peleke”. To do this, the engine looks up the variable called first_name. Since the compiler has already registered a variable by that name, the engine finds it, and sets its value to “Peleke”.</p><p>Next, it reads the line, function popup (first_name). Since we’re not <em>executing</em> the function here, the engine isn’t interested and skips on over it.</p><p>Finally, it reads the line popup(first_name). Since we <em>are</em> executing a function here, the engine:</p><ol><li>looks up the value of popup</li><li>looks up the value of first_name</li><li>executes popup as a function, passing the value of first_name as a parameter</li></ol><p>When it executes popup, it goes through this same process, but this time inside the function popup. It:</p><ol><li>looks up the variable named last_name</li><li>sets last_name’s value equal to “Sengstacke”</li><li>looks up alert, executing it as a function with “Peleke Sengstacke” as its parameter</li></ol><p>Turns out there’s a lot more going on under the hood than we might have thought!</p><p>Now that you understand how <a href="https://codequs.com/a/SJOOCdEO">JavaScript</a> reads and runs the code you write, we’re ready to tackle something a little closer to home: how hoisting works.</p><h3>Hoisting Under the Microscope</h3><p>Let’s start with some code.</p><p><em>bar();<br> <br>function bar () {<br> if (!foo) {<br> alert(foo + “? This is strange…”);<br> }<br> var foo = “bar”;<br>}<br> <br>broken(); // TypeError!<br>var broken = function () {<br> alert(“This alert won’t show up!”);<br>}</em></p><p>If you run this code, you’ll notice three things:</p><ol><li>You <em>can</em> refer to foo before you assign to it, but its value is undefined.</li><li>You <em>can</em> call broken before you define it, but you’ll get a TypeError.</li><li>You <em>can</em> call bar before you define it, and it works as desired.</li></ol><p><strong>Hoisting </strong>refers to the fact that <a href="https://codequs.com/a/B10zpuEd">JavaScript</a> makes all of our declared variable names available<em>everywhere</em> in their scopes — including <em>before</em> we assign to them.</p><p>The three cases in the snippet are the three you’ll need to be aware of in your own code, so we’ll step through each of them one by one.</p><h3>Hoisting Variable Declarations</h3><p>Remember, when the <a href="https://codequs.com/a/HJwal_Ws">JavaScript</a> compiler reads a line like var foo = “bar”, it:</p><ol><li>registers the name foo to the nearest scope</li><li>sets the value of foo to undefined</li></ol><p>The reason we can use foo before we assign to it is because, when the engine looks up the variable with that name, it <em>does</em> exist. This is why it doesn’t throw a ReferenceError.</p><p>Instead, it gets the value undefined, and tries to use that to do whatever you asked of it. Usually, that’s a bug.</p><p>Keeping that in mind, we might imagine that what JavaScript sees in our function bar is more like this:</p><p><em>function bar () {<br> var foo; // undefined<br> if (!foo) {<br> // !undefined is true, so alert<br> alert(foo + “? This is strange…”);<br> }<br> foo = “bar”;<br>}</em></p><p>This is the <strong>First Rule of Hoisting</strong>, if you will: Variables are available <em>throughout their scope</em>, but have the value undefined until your code assigns to them.</p><p>A common JavaScript idiom is to write all of your var declarations <a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/single-var-pattern.html">at the top of their scope</a>, instead of where you first use them. To paraphrase Doug Crockford, this helps your code <em>read</em> more like it <em>runs</em>.</p><p>When you think about it, that makes sense. It’s pretty clear why bar behaves the way that it does when we write our code the way JavaScript reads it, isn’t it? So why not just write like that <em>all</em> the time?</p><h3>Hoisting Function Expressions</h3><p>The fact that we got a TypeError when we tried to execute broken before we defined it is just a special case of the First Rule of Hoisting.</p><p>We defined a variable, called broken, which the compiler registers in the global scope and sets equal to undefined. When we try to run it, the engine looks up the value of broken, finds that it’s undefined, and tries to execute undefined as a function.</p><p>Obviously, undefined <em>isn’t</em> a function — that’s why we get a TypeError!</p><h3>Hoisting Function Declarations</h3><p>Finally, recall that we were able to call bar before we defined it. This is due to the <strong>Second Rule of Hoisting</strong>: When the JavaScript compiler finds a function declaration, it makes both its name <em>and</em> definition available at the top of its scope. Rewriting our code yet again:</p><p><em>function bar () {<br> if (!foo) {<br> alert(foo + “? This is strange…”);<br> }<br> var foo = “bar”;<br>}<br> </em><br><em>var broken; // undefined<br> <br>bar(); // bar is already defined, executes fine<br> <br>broken(); // Can’t execute undefined!<br> <br>broken = function () {<br> alert(“This alert won’t show up!”);</em><br><em>}</em></p><p>Again, it makes much more sense when you <em>write</em> as JavaScript <em>reads</em>, don’t you think?</p><p>To review:</p><ol><li>The names of both variable declarations and function expressions are available throughout their scope, but their <em>values </em>are undefined until assignment.</li><li>The names <em>and</em> definitions of function declarations are available throughout their scope, <em>even beforetheir definitions.</em></li></ol><p>Now let’s take a look at two new tools that work a bit differently: let and const.</p><h3>let, const, &amp; the Temporal Dead Zone</h3><p>Unlike var declarations, variables declared with let and const <em>don’t</em> get hoisted by the compiler.</p><p>At least, not exactly.</p><p>Remember how we were able to call broken, but got a TypeError because we tried to execute undefined? If we’d defined broken with let, we’d have gotten a ReferenceError, instead:</p><p><em>“use strict”; <br>// You have to “use strict” to try this in Node<br>broken(); // ReferenceError!<br>let broken = function () {<br> alert(“This alert won’t show up!”);<br>}</em></p><p>When the JavaScript compiler registers variables to their scopes in its first pass, it treats letand const differently than it does var.</p><p>When it finds a var declaration, we register the name of the variable to its scope and immediately initialize its value to undefined.</p><p>With let, however, the compiler <em>does</em> register the variable to its scope, but <em>does not </em>initialize its value to undefined. Instead, it leaves the variable uninitialized, <em>until </em>the engine executes your assignment statement. Accessing the value of an uninitialized variable throws a ReferenceError, which explains why the snippet above throws when we run it.</p><p>The space between the beginning of top of the scope of a let declaration and the assignment statement is called the <em>Temporal Dead Zone</em>. The name comes from the fact that, even though the engine<em>knows</em> about a variable called foo at the top of the scope of bar, the variable is “dead”, because it doesn’t have a value.</p><p>… Also because it’ll kill your program if you try to use it early.</p><p>The const keyword works the same way as let, with two key differences:</p><ol><li>You <em>must</em> assign a value when you declare with const.</li><li>You <em>cannot</em> reassign values to a variable declared with const.</li></ol><p>This guarantees that const will <em>always </em>have the value that you initially assigned to it.</p><p><em>// This is legal<br>const React = require(‘react’);<br> <br>// This is totally not legal<br>const crypto;<br>crypto = require(‘crypto’);</em></p><h3>Block Scope</h3><p>let and const are different from var in one other way: the size of their scopes.</p><p>When you declare a variable with var, it’s visible as high up on the scope chain as possible — typically, at the top of the nearest function declaration, or in the global scope, if you declare it in the top level.</p><p>When you declare a variable with let or const, however, it’s visible as <em>locally</em> as possible — <em>only</em> within the nearest block.</p><p>A <em>block</em> is a section of code set off by curly braces, as you see with if/else blocks, for loops, and in explicitly “blocked” chunks of code, like in this snippet.</p><p><em>“use strict”;<br> <br>{<br> let foo = “foo”;<br> if (foo) {<br> const bar = “bar”;<br> var foobar = foo + bar;<br> <br> console.log(“I can see “ + bar + “ in this bloc.”);<br> }<br> <br> try {<br> console.log(“I can see “ + foo + “ in this block, but not “ + bar + “.”);<br> } catch (err) {<br> console.log(“You got a “ + err + “.”);<br> }<br>}<br> <br>try {<br> console.log( foo + bar ); // Throws because of ‘foo’, but both are undefined<br>} catch (err) {<br> console.log( “You just got a “ + err + “.”);<br>}<br> <br>console.log( foobar ); // Works fine</em></p><p>If you declare a variable with const or let inside a block, it’s <em>only</em> visible inside the block, and <em>only</em> after you’ve assigned it.</p><p>A variable declared with var, however, is visible <em>as far away as possible</em> — in this case, in the global scope.</p><p>If you’re interested in the nitty-gritty details of let and const, check out what Dr Rauschmayer has to say about them in <a href="http://exploringjs.com/es6/ch_variables.html">Exploring ES6: Variables and Scoping</a>, and take a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">MDN documentation on them</a>.</p><h3>Lexical this &amp; Arrow Functions</h3><p>On the surface, this doesn’t seem to have a whole lot to do with scope. And, in fact, JavaScript does <em>not</em>resolve the meaning of this according to the rules of scope we’ve talked about here.</p><p>At least, not usually. JavaScript, notoriously, does <em>not</em> resolve the meaning of the this keyword based on where you used it:</p><p><em>var foo = {<br> name: ‘Foo’,<br> languages: [‘Spanish’, ‘French’, ‘Italian’],<br> speak : function speak () {<br> this.languages.forEach(function(language) {<br> console.log(this.name + “ speaks “ + language + “.”);<br> })<br> }<br>};<br> <br>foo.speak();</em></p><p>Most of us would expect this to mean foo inside the forEach loop, because that’s what it meant right outside it. In other words, we’d expect JavaScript to resolve the meaning of this <em>lexically</em>.</p><p>But it doesn’t.</p><p>Instead, it creates a <em>new</em> this inside every function you define, and decides what it means based on <em>how</em>you call the function — not <em>where</em> you defined it.</p><p>That first point is similar to the case of redefining <em>any</em> variable in a child scope:</p><p><em>function foo () {<br> var bar = “bar”;<br> function baz () {<br> // Reusing variable names like this is called “shadowing” <br> var bar = “BAR”;<br> console.log(bar); // BAR<br> }<br> baz();<br>}<br> <br>foo(); //</em> <em>BAR</em></p><p>Replace bar with this, and the whole thing should clear up instantly!</p><p>Traditionally, getting this to work as we expect plain old lexically-scoped variables to work requires one of two workarounds:</p><p><em>var foo = {<br> name: ‘Foo’,<br> languages: [‘Spanish’, ‘French’, ‘Italian’],<br> speak_self : function speak_s () {<br> var self = this;<br> self.languages.forEach(function(language) {<br> console.log(self.name + “ speaks “ + language + “.”);<br> })<br> },<br> speak_bound : function speak_b () {<br> this.languages.forEach(function(language) {<br> console.log(this.name + “ speaks “ + language + “.”);<br> }.bind(foo)); // More commonly:.bind(this);<br> }<br>};</em></p><p>In speak_self, we save the meaning of this to the variable self, and use <em>that </em>variable to get the reference we want. In speak_bound, we use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a> to <em>permanently</em> point this to a given object.</p><p>ES2015 brings us a new alternative: arrow functions.</p><p>Unlike “normal” functions, arrow functions do <em>not</em> shadow their parent scope’s this value by setting their own. Rather, they resolve its meaning <em>lexically.</em></p><p>In other words, if you use this in an arrow function, JavaScript looks up its value as it would any other variable.</p><p>First, it checks the local scope for a this value. Since arrow functions don’t set one, it won’t find one. Next, it checks the <em>parent</em> scope for a this value. If it finds one, it’ll use that, instead.</p><p>This lets us rewrite the code above like this:</p><p><em>var foo = {<br> name: ‘Foo’,<br> languages: [‘Spanish’, ‘French’, ‘Italian’],<br> speak : function speak () {<br> this.languages.forEach((language) =&gt; {<br> console.log(this.name + “ speaks “ + language + “.”);<br> })<br> }<br>};</em></p><p>If you want more details on arrow functions, take a look at Envato Tuts+ Instructor Dan Wellman’s excellent course on JavaScript ES6 Fundamentals, as well as the MDN documentation on arrow functions.</p><h3>Conclusion</h3><p>We’ve covered a lot of ground so far! In this article, you’ve learned that:</p><ul><li>Variables are registered to their scopes during <em>compilation</em>, and associated with their assignment values during <em>execution</em>.</li><li>Referring to variables declared with<strong> </strong>let or const before assignment throws a ReferenceError, and that such variables are scoped to the nearest block.</li><li>Arrow functions<strong> </strong>allow us to achieve lexical binding of this, and bypass traditional dynamic binding.</li></ul><p>You’ve also seen the two rules of hoisting:</p><ul><li>The <strong>First Rule of Hoisting</strong>: That function expressions and var declarations are available throughout the scopes where they’re defined, but have the value undefined until your assignment statements execute.</li><li>The <strong>Second Rule of Hoisting</strong>: That the names of function declarations <em>and</em> their bodies are available throughout the scopes where they’re defined.<br><strong>Written by Peleke Sengstacke</strong></li></ul><p><strong>Did you find this article helpful? Don’t forget to drop your feedback in the comments section below. Suggest for you:</strong></p><p>☞<a href="https://codequs.com/a/HJqC6dN_">JavaScript the Basics — JavaScript for Beginners</a></p><p>☞<a href="https://codequs.com/a/ryMLq9dd">JavaScript for Absolute Beginners</a></p><p>☞<a href="https://codequs.com/a/HJI8wa3h">JavaScript: JavaScript Awesomeness</a></p><p>☞<a href="https://codequs.com/a/SybdL0aO">JavaScript For Beginners — Learn JavaScript From Scratch</a></p><p>☞<a href="https://codequs.com/a/ByYBy37j">Javascript Intermediate level 1 — Mastering the DOM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bacebadc66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why React.JS is Preferable for Web Application Development?]]></title>
            <link>https://medium.com/@cassycassy/why-react-js-is-preferable-for-web-application-development-997113a6e9c3?source=rss-3a908956a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/997113a6e9c3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Cassy Cassy]]></dc:creator>
            <pubDate>Mon, 25 Jul 2016 06:54:37 GMT</pubDate>
            <atom:updated>2016-07-25T06:54:37.567Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes, you rightly ended up here to know about technology that makes your way! Increasing tremendous number of web application may take the future of web development in a way, which involved new technology and tools to discover upon. Being able to develop large scale websites and application is not a big deal now! Speed of new technologies and tools invention makes task easier like never before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSgqZYyI58C-fLNjs_hGHA.jpeg" /><figcaption><a href="https://school.codequs.com/">React.js</a></figcaption></figure><p>Front end development is a crucial part of web app development. We tend to keep our point of any particular website emphasizing design and structure. That is what makes front end more significant in web development. Java script is pretty much good in front end development when dynamic web pages take place. So, here is one more adaptable way for that has arrived! React.js comes into picture to help with the easier front-end development.</p><p>So, let’s get started and figure out what it is.</p><p>What is React.JS?</p><p>React.JS is an Open-source JavaScript library maintained by world’s top most community such as Facebook, Instagram and community of individual developers. Its aims to develop reusable UI components and can be represented as view ‘V’ in MVC model in web development. It focuses on efficiency and flexibility to create user interfaces. Now, design can be uncomplicated as React.JS allows creating simple view for each state and rendering when needed.</p><p>React Component:</p><p>React.JS is independent in nature as it becomes easy to maintain and reuse the component. Encapsulated components manage their own states and glued all of them to build Interactive UIs. The strongest point of React.JS is that it does not perform only on client side, but it can be rendered on server side too. Basically React Component is what you can say a class, a function which performs custom operation. Work of React.JS is not only about templates in UI, but it has sound mechanism to pass the data through application.</p><p>Virtual DOM and React.js:</p><p>One of the profound concept of React.js is Virtual DOM. Virtual DOM is refer to abstract version of DOM. It reduce the overhead of DOM manipulation by re-rendering (changing) what should be changed rather than reflecting directly in DOM. As it helped a lot to least DOM tree and renders accordingly when changed.</p><p>React Elements and Instances:</p><p>According to a community, a React Element is “An element is a plain object describing component instance or DOM node and its desired properties.” React Element is just representation of what you want to show on the screen. It is not an actual instance. It contains the information of component and its properties inside it. Each component instance has to maintain reference to its DOM nodes. React elements are lighter and no need to parse!</p><p>Main Aspect:</p><p>One noticeable characteristic of React.JS is its data flow. React.JS has one way data model data flow model unlike other framework having two-way data flow such as Angular js. The flow has been defined from parent to child. And, it really helps to make data flow smoother and easier. Developing a website efficiently with this one way data binding is agreeable way one can think.</p><p>Conclusion:<br>React.JS development facilitates front end development with the inclusion of exciting features. Hence, more flexible and efficient aspect has appeared in web application development. So, figure out what React.JS and its features will help you through development to meet your expectations! Good Luck!</p><p>Source: brainvire</p><p>For information you can read :</p><h3><a href="http://url.viraldeal.net/N1QrBjRDb">React.js Quickly: Developing Scalable Web User Interfaces</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=997113a6e9c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>