Talk: Building Pong in Native JavaScript

Aaron Krauss will be giving an introduction to game development using plain JavaScript, meaning no libraries or plugins. He’ll be coding out a single-player pong game, and discussing how to take it to the next level by turning it into a full-blown breakout game (often called brick-breaker).

This talk is very introductory – no previous experience necessary. We’ll discuss how core game mechanics work in the browser, collision detection, the game loop, and more! At the end, he’ll review some of the popular game libraries available today, and how you can start to get your feet wet with JavaScript game development too!

How WebSockets Work – With Socket.io Demo

As a developer you may have heard the term WebSockets thrown around in the past few years, without fully understanding what they are. At least I was in that boat for a long time before I started using them. WebSockets really aren’t too difficult to understand and implement, and they can lead to some really cool functionality in your app. Whether you agree or disagree that WebSockets have enhanced the current state of web development, it’s at least a good idea to understand how they actually work. Before I get into the nitty-gritty about how WebSockets function, I want to provide some real-life examples of how they could be used to make sure we all know what they are.

Imagine you’re using a browser-based instant messaging application and you’re chatting with a friend – how do those messages automatically appear in your browser without you having to refresh? While the app doesn’t necessarily have to be using WebSockets – there’s a good chance that it is. Same thing if you’re on a company’s homepage and you see a stock ticker changing regularly, or if you’re on a sports site keeping track of a game score that’s updating on its own. These are all examples of how WebSockets can be used in the wild. WebSockets create links, or “sockets,” between two parties and allow for two-way communication. Back to the instant message example, whenever you send a new instant message in a chatroom, your client would alert the server of the new message, then the server would immediately broadcast that message to all of the other clients, and finally those clients would immediately receive and render the message.

Traditional Web Sites

The way you traditionally interact with a web site is by issuing an HTTP request from your client (i.e. your browser) to the server and receiving all the necessary data to load the webpage as a response from the server. This can be HTML, CSS, Javascript, images, and more. You can even make asynchronous requests to load additional data (often in the form of JSON or XML) while you’re interacting with the web page, which is how single-page apps work. What you can’t do however is rely on the server to automatically send the client information on its own. Traditionally, there’s always a request from the client involved, and we can’t change how HTTP works to account for this (nor would we want to). We can build a semi-workaround for this by implementing polling – meaning we just issue asynchronous requests to the server every second or so to see if data has changed, in which case we would want to render it onto the screen (such as a new instant message) – but that means we’re issuing several needless requests over and over again. That impacts both the client and the server, and that’s not good.

It seems like it would be really helpful if we could establish an open connection between the server and the client so that they can communicate bi-directionally, but how would we do this? Enter WebSockets.

What are WebSockets

WebSockets represent a standard for bi-directional communication between a client and a server which involves creating a TCP connection that links them together. The TCP connection sits outside of HTTP, and thus runs a separate server to manage this communication. To initialize this connection, a handshake is performed between the client and the server; here’s the general process:

1) The client makes an HTTP request to the server with an upgrade header, indicating that the client wishes to establish a WebSocket connection. Notice the ws URI scheme (short for WebSocket). wss is also available for secure WebSocket communication.

2) If the server supports the WebSocket protocol, then it will agree to the upgrade and send a response back.

3) The handshake is complete, and all further communication will follow the WebSocket protocol and will use the same underlying TCP port. The returning status code is 101, which stands for Switching Protocols.

Demo with Socket.io

All this talk about WebSockets is great, but why don’t we build a small demo to really show off how they work? Socket.io is perhaps the most popular WebSocket library out there right now, and it’s built to work with node.js. We’re going to create a drop-dead simple instant messaging application that uses WebSockets. This app will allow clients to submit text through a form, which will in turn display that text in realtime on every client’s DOM. For starters, let’s start a new node project and install socket.io:

We also installed express in order to add some basic routing features later on. Now let’s add our first file called index.js, where we’ll write our server-side code. Starting off simple, it takes only three lines to build a working WebSocket server.

To run this server, we just execute the following command:

Using WebSockets can’t get any easier than this – we’re literally just opening a TCP connection and listening. Once you run this, you’ll see your terminal hang, showing that the server is working – but if you navigate to http://localhost:3000 in your browser, you won’t actually see any UI. That’s because we don’t have an HTTP server running to return anything to our browser – it’s strictly WebSockets for now. Let’s change that by rebuilding our code to instead attach our WebSocket server to an HTTP server, which will allow us to run both on the same port. For now, let’s just build a simple HTTP server, leaving out WebSockets. Baby steps.

As you can see on line 7, we’re routing our pages to the /public directory. That means before we run this server, we need to create and add an index HTML template in that directory with some basic structure. Something like this will do nicely:

Nothing too crazy here – just a header, an empty div, a simple form with an input and submit button, and a script call to grab jQuery from a CDN. Now run this server and visit http://localhost:3000, and you should see something that looks like this.

websocket-screenshot-1

Now the plan here is to allow the user to enter text and submit the form, and that text will automatically display beneath the WebSocket Demo heading on every client that’s currently viewing the page, without them having to do anything. It’ll be like magic.

In order to do that, we need to add back in and update the WebSocket portion of our server Javascript file; whenever a client emits a message to the WebSocket server, we want the server to broadcast that message to all the client browsers so they can update their own display in realtime.

Here’s our updated file, and this will actually be the last edit we have to make here. After making these changes, be sure to restart your server. The rest of the logic will be some simple client-side Javascript.

Let’s jump back to our HTML template and add in a link to another Javascript file (main.js) that we’ll build ourselves to handle the client-side WebSocket logic. Additionally, now that we have WebSockets working on the server, we need to link to the client-side socket.io library.

If you look at the socket.io.js file path, you might be thinking that we never put that file in our project – and you’d be correct. When we attach our WebSocket connection to our HTTP connection, that file is served automatically by our server. Now let’s create main.js in /public and start building our logic handlers. We’ll start off by wrapping all of our code in an IIFE and using jQuery to help build the callback for when the user submits the form. Then, we’ll render the message in our own browser and clear the input after it’s been submitted.

If you submit this form now, you should see your message appear beneath the WebSocket Demo header, and then your input will be cleared. Now let’s take this a step further; inside this callback, we can grab the submission data and use the socket.io library to emit a message to our WebSocket server (which is attached to our HTTP server). To do that, we just have to add in two lines:

Now reload the page and submit the form with “foobar” entered into the text input; you should see this output from your server:

This means you’ve been successful in sending a message via WebSockets to your server! Now if you were to open up your browser development tools and watch as you make this submission, you won’t see any sort of logging for the message. That’s because it’s not following the HTTP protocol – it’s following the WebSockets protocol. I want to make absolutely certain we’re all on the same page here. This isn’t a form of AJAX going on behind the scenes, it’s full on WebSockets. HTTP isn’t involved in the least bit after the initial handshake.

So our server is receiving our message, which is cool, but that’s not where we want it to end. We want the server to now broadcast that message to all of the clients so that they can render the message to the screen. Our server is already good to go, so all that’s left is to build the handlers on the client-side to receive the messages and render them to the screen.

At the bottom of /public/main.js, we’ll add a few lines of code to take care of this.

Boom – we’re done! This is our last bit of code to add; all it does is wait to receive a message from the server, and when it does, it will append the message to the DOM just like it would for the user who submits the form. One word of note here is that the client who sends the initial message will not receive any messages back from the server for that particular message. This is good, because the original client already knows when the action takes place without needing WebSockets.

To test everything out, open up multiple browser windows and navigate to http://localhost:3000. Now you’ll notice that when you submit the form from one client, the message will appear in all clients automatically! The power of WebSockets!

If you don’t want to build all of this out, feel free to check out the live demo instead; the code’s all on on GitHub too.

Concerns

In addition to being one of those cool new-ish technologies, WebSockets are nice because they make more efficient use of server and client resources and because data transmitted is truly realtime – but they’re not without their downfalls.

Browser support. WebSockets aren’t completely supported, especially in older browsers. Firefox 6, Safari 5, Chrome 14, IE 10, and Opera 12.10 all support WebSockets, but older versions of these browsers don’t – at least not fully. Most modern mobile browsers do support WebSockets, but not opera mini, which has a sizable market share of mobile browsing – especially in non-industrialized nations.

Potential for an extra server running. To use WebSockets, you have to open up a TCP connection which means maintaining another service for your application to fully function. Like we did in this demo, you can establish this connection on the same port as HTTP, but if you choose not to do this, then that’s another service to manage.

More complexity. Not only could you have another service running, but WebSockets almost always result in more code written (though often times it’s cleaner code). You’re at least usually depending on another library of code to help manage the connection, like socket.io.

You definitely need to weigh the pros and cons to see if WebSockets are right for you – but for me, the pros vastly outweigh cons. WebSockets open up the doors for countless possibilities in the realm of today’s web development.

Final Thoughts

There you have it – how WebSockets work and with a demo to show it all off. I personally think they’re really cool, and jump at the opportunity to implement them if they apply to a specific use case – but not everyone’s a fan. Depending on your app’s requirements, it may even be wiser to instead implement long polling or server-sent events. Whether you choose to use them regularly in your projects is up to you, but I do highly recommend using them at least one time to help you get a deeper understanding about how they really work. Even if they become obsolete within the next decade (which I strongly doubt will happen), they represent a fundamental type of communication which HTTP just can’t compete with – because it wasn’t designed to.

Now go forth and build!

Building ES6 Javascript for the Browser with Gulp, Babel, and More

ECMAScript 6 is the most recent update to Javascript, and with it has come a lot of new features to the language – some that the community has been begging for, and also some that are pretty controversial. But regardless of how you feel about ES6, you probably want to be using the most recent version of Javascript – because that’s just who you are. This works out pretty well if you’re working with node.js or another server-side framework since you can control your Javascript version on the server – but using ES6 is pretty difficult if you’re writing client-side Javascript, which includes anything from a complex angular or ember app all the way down to a simple static page with a few lines of jQuery.

But why is ES6 difficult to write in the browser? It’s because with client-side Javascript, you’re completely dependent on how well the browser you’re using can compile and execute that Javascript. Instead of you being in control, your browser is in control – and there are a lot of browsers out there in the wild that don’t support ES6. Even once the modern browsers finally do support ES6, we still have to account for the people who use older browsers. Basically, it will be a long time before we can safely write ES6 code directly for our browsers to execute.

So does that mean we’re out of luck? Are we destined to just accept that we’ll always have to use dated versions of Javascript for the browser? No, we don’t have to accept that! We have options – and the best option right now is write ES6 code and then transpile (or compile) it down into ES5 code – which all modern browsers (IE9+) can handle. Babel will be our main transpiling tool, and to make it easier we’re gonna automate this process so we don’t even have to think about it!

tl;dr

In case you just want a short description and the raw code that we’re going to go through in this post, here it is:

We’ll be building a gulpfile to watch for changes and automatically convert our ES6 code into CommonJS by using Babel, and then convert that CommonJS into valid ES5 by using Browserify. Then, we’ll be adding on some extra nice-to-haves such as UglifyJS (for minification), source maps, and livereload – because those tools are super helpful.

Without further ado, here’s the full gulpfile we’re about to build:

See – that’s not so bad! We’re doing a lot of different things here too, so if you’re interested in learning about them then I encourage you to continue reading to see how and why this is a solid way to build your ES6 code for the browser.

Starting Our Gulpfile

We’ll be using gulp for our build automation. If you’re unfamiliar, gulp is a Javascript-based tool which will run tasks for you and watch for changes in files – all based on a config file called gulpfile.js in your local project directory. There are other build automation tools out there (with grunt being the popular counter-tool), but gulp is definitely the fastest with its use of node streams.

To start off, let’s initialize our package.json and install gulp locally (install it globally too, if you haven’t already):

Then create a blank gulpfile.js with the following skeleton:

Nothing too crazy going on yet. We’re creating a blank build task, a watch task, and a default task. The build task is where we’ll be adding all of our logic to build our Javascript. The watch task is actually done – all it does is watch for changes in the src/js folder (the build files will eventually get placed in dist/js).

To run any of these tasks:

So far, so good, right? Let’s add the actual ES6-to-ES5 build process now.

Implementing Babel and Browserify

As discussed briefly in the tl;dr above, we’re going to use a combination of babel and browserify to build our ES6 code into ES5 code that the browser can understand. Babel will convert ES6 into CommonJS, which is a commonly used module pattern in modern day Javascript (especially with node.js) – but the browser still can’t understand CommonJS. So, we need to use browserify – which specifically converts CommonJS into valid ES5. With these two tools, we’ll be good to go.

We won’t be using babel directly however; instead, we’ll be using a library called babelify which is built as a transform for browserify – meaning it will preprocess Javascript before browserify compiles it. Let’s install some of these packages:

Now, we can update our gulpfile with these new tools in order to build our ES6:

And this is all we need to build our Javascript. We simply tell browserify the files we want to change (src/js/app.js in this case), and before our code gets browserified, it gets transpiled using babel according to the es2015 presets. Since v6.0.0, babel requires you to specify presets according to how you want to transpile your Javascript. While this probably seems like a hassle, it’s meant to give you as the developer more control over the whole process. We want to use the standard es2015 build process, which is why we had to install the NPM package babel-preset-es2015.

After the files are browserified, we bundle them together into a single file (in this case, it already was a single file). You’re probably also wondering what vinyl-source-stream is. See, gulp works with node streams, and more specifically, it works with vinyl streams, which is a virtual file format. Browserify returns a readable stream, but not a vinyl stream, so we have to convert the stream using vinyl-source-stream in order to continue with our gulp logic. It’s an extra plugin, but it’s tiny and only has one job.

We can now officially build ES6 code into valid ES5 code, in under 20 lines of a gulpfile. But let’s be serious here – if you’re writing production Javascript, you’re going to want to do some more with your code before it’s ready to ship. Enter uglify, source maps, and livereload.

Adding on Uglify, Source Maps, and LiveReload

Building our ES6 into valid ES5 is one thing, but we also want to make sure our code is minified and source mapped before it goes out into production. To add in all these features, we’re going to update our gulpfile with the following tools:

  • UglifyJS: to minify our Javascript and make it as small in size as possible.
  • Source Maps: these will help with debugging our minified scripts. Source maps are references in your minified files that link code in those files to where it exists in non-minified build files. This makes debugging production code way easier. On top of that, the source-mapped files only get downloaded if you have your dev console open – so normal users will never download them.
  • LiveReload: This tool is specifically helpful in development, and it will auto-reload your browser when changes occur in the files you’re listening on. A popular alternative to LiveReload is BrowserSync.

Let’s start off with adding in UglifyJS. We need to install a couple more packages:

And now we’ll edit our gulpfile like so:

We added in both gulp-uglify and vinyl-buffer. gulp-uglify is the gulp plugin which will minify our Javascript, but what’s vinyl-buffer? We need vinyl-buffer because gulp-uglify doesn’t support streams right now – but it supports buffers. vinyl-buffer just converts a stream into a buffer so that gulp-uglify can work its magic.

We’re on the home stretch now – let’s add source maps and livereload. As usual, let’s install some packages:

And now, for the last time, let’s update our gulpfile with these new tools:

Starting off with the source maps plugin, we initialize our source maps before we minify our Javascript. That’s how we know what to link to after our files get minified. Then, after minification, we’re saving out our source maps as individual files in the maps/ directory. Now, whenever you want to reference a line of code in your minified JS, the source maps will instead direct you to a line in the unminified files which will be much easier to read.

Finally, we’re instructing our livereload process to listen for when we make changes, and to reload the browser after each Javascript build iteration. The easiest way to make the most of livereload would be to tie it with its corresponding browser plugin – with Chrome’s plugin being my favorite.

And that’s it! We’re officially done with our gulpfile.

Final Thoughts

If you’ve followed all these steps (or just copied the full gulpfile at the beginning of the post), then you now have a fully-working automated build system that will transpile your ES6 code into ES5 code that all modern browsers can understand – with some niceties added on like minimization and source maps. Now I know some of this might seem complicated, and you certainly don’t have to go through any of it if you just want to keep writing normal ES5 in the browser, but even just understanding what all is going on here will make you a better developer because you’re now more familiar with some of the neat front-end build tools out there.

Still, I highly encourage you to check out the ES6 docs and see how some of the new features might benefit your workflow. For me personally, I have a big beef with the new class API (because Javascript is prototype-based, not class-based – you can read all about that in my post), but I’m extremely happy that they’ve added a module pattern system, and I plan to use that heavily. However you feel though, you should stay up to date with the most recent iteration of the language – and babel and gulp are here to help make it easier for you!

Prototypal Programming in Javascript

Javascript is an object-oriented programming language, but not like not like the ones you’re probably used to. Most programming languages that are object-oriented (C++, Java, C#, Ruby, Python, etc.) fall into the category of class-based object-oriented languages in which you define a class – a blueprint for attributes and methods – and you instantiate objects out of that class. All objects that come from the same class can access the same class-level (or static) methods and attributes; separate objects do typically have different instance variables (since that’s primarily what differs one object from another), but they all follow the same schema for their property names which is determined in the class definition – similar to how multiple rows in a SQL table will have different values, but they all follow a similar schema defined by the table.

So What Does That Make Javascript?

Javascript is not class-based. It is prototype-based, which defines a whole new set of rules for creating objects, accessing shared resources, and determining how to handle “inherited” properties. Javascript is by far the most popular prototypal language – in fact, if you’ve even heard of more than a couple of the other ones, then you’re a winner in my book. In a prototypal object-oriented language, you take the concept of classes completely out of the picture – they just don’t exist at all. Instead, you just have objects, and every object can have its own schema. I’ll repeat that – in Javascript, every object can define its own schema, and it’s perfect valid. They way you build relationships between objects is by creating direct object-to-object hierarchies; this means that you can create an object out of another object, and that child object automatically gets access to all the variables and methods of its parent object. Inheritance in the classical sense doesn’t exist in Javascript – instead, if the object doesn’t have the property you’re asking for, then you would delegate that call up to the parent object which is called a prototype; this is where prototypal programming gets its name.

Want to know a secret? Prototypal programming in Javascript is easy. People tend to make it significantly more complicated than it needs to be because many developers are unfamiliar with what it means to be prototypal, let alone the fact that Javascript itself is prototypal at its core. Let’s do some examples:

In this example, we create a simple object a that has an attribute and a method. Nothing new there – but look at that next line. We are using the Object.create() method to create a new object out of object abecause we passed it in as an argument. This is how behavior delegation works in Javascript; b now has access to all of its prototype’s properties and can call them at will. This link from child-to-parent objects is called the prototype chain. If a property is called but not found on the object in question, the look-up continues through the prototype chain until the property is found or the chain ends, in which case undefined is returned. In this example, b did not have the properties name or alertMe(), so it delegated those calls to its prototype a. This is different than class-based inheritance because no properties are copied to the objects; if a property doesn’t exist, it gets delegated up the prototype chain.

At the root of the chain, all objects inherit from Object.prototype. This is how objects in Javascript get their default methods such as hasOwnProperty(), valueOf(), and toString().

Back to our example. Can we add more attributes to b? You bet’cha:

You can see that b can access this new attribute, but a can’t because it’s the parent object. You can only delegate up the prototype chain from child to parent, and not the other way around. But, if we instead add an attribute on object a – the parent object – then b automatically can access it because a is its prototype. We don’t need to redeclare b to access this new property (as we may need to do in class-based inheritance) because the prototype chain only relies on links to prototypes instead of copying any behavior down the chain! Here’s an example:


Before moving on to the next section, I need to make sure we’re on the same page about behavior delegation. In Javascript, what we typically refer to as “inheritance” works via the prototype chain on an object-to-object level, not a class-to-class level (because classes don’t exist). No copies are made when creating children objects; instead, when a property is called that’s not found on an object, it is instead delegated to a parent object up the prototype chain – so feel free to swap out the phrase “inheritance” with “delegation” because that’s a much more accurate description of what’s happening.

Shadowing (or Polymorphism)

We touched on delegation a bit, but what about overriding methods – such as in polymorphism. With Javascript being a prototypal language, true polymorphism doesn’t happen. Remember – there are no classes (let alone abstract classes) and thus no required schema, so there’s not a real notion of an overriden method like in class-based languages. However, you can still simulate polymorphic behavior using shadowing – where an object will create a new property on itself even if a property in its prototype chain already exists:

The alertMe property on b is now a shadowed property that differs from its prototype, but you can see at the bottom of the above example that it’s still very easy to access the prototype and call its own properties.

Big Note: Shadowing like this will only work if a property is flagged as writable: true. By default, when you create a property through assignment (like we have so far), it is always set to writable – so shadowing can happen. If it is not writable, then not only will your child object be unable to create the property upon itself, but it will also be unable to modify the property up in the prototype chain. This may be confusing, so feel free to read more about property descriptors.

Because of the potential for undesired behavior in shadowing, it’s best to try to avoid it at all if possible.

Creating Objects and Adding Properties – All At Once

Whenever you create a new child object from a prototype using the Object.create() method, you can also pass in a second parameter representing the properties you would like to append to this child object. Let me show you an example:

Looks kind of weird, right? That’s because appending properties to an object like this follows a specific format – in fact, it’s the exact same format that the Object.defineProperties() method uses. Instead of setting value to a string, you can also set it to an integer, null, function, or any other data type in Javascript. In addition to setting the value attribute, you can also set a getter method, a setter method, and whether the attribute is writable after initially assigned – all in this single argument. Overall, you get a lot of power by defining properties this way – at the expense of some additional syntax. You can think of this second argument to the Object.create() method to be sort-of like a constructor (but not really – read on).

My Thoughts on Constructors in Prototypal Languages

In true prototypal programming, constructors don’t exist because classes don’t exist. You would never add a constructor onto an object because the purpose of an object is to actually use that object as a data structure – not solely to create other data structures (like a class). So, if your intention is to create multiple child objects that all have “instance variables” (relating back to class-based languages), then you would need to specify those extra child attributes each time you create a child object from a prototype. This might sound like extra work, but you can extract this second argument into a variable or use some other form of code reusability. You’re smart, so I believe in you. Or, you could let go of some of your class-based mentality and rebuild some of your data architecture to fit a prototypal mold – which is my preferred suggestion. At its core, Javascript is prototypal – don’t force it to act class-based.

How to NOT Do Prototypal Programming in Javascript

Note: A lot of you may disagree with me here because I’m going to share my thoughts over some development practices in Javascript that are pretty common. Practices which I don’t think are good. It’s not just me though; Kyle Simpson – author of You Don’t Know JS – also agrees with me here.

In Javascript, functions are first-class citizens – meaning they can be assigned to variables, passed as arguments to other functions, and more. It’s perfectly fine to extend the capabilities of functions in this way (and a necessity for functional programming), but sometimes I feel that developers use functions for things they’re not meant to be used for in Javascript. Things like declaring data structures that no longer act like functions, and act more like classes.

Poor Prototypal Javascript

If you google how to write prototypal Javascript, you’re bound to come across examples like this:

Let me describe what’s going on here. We create a function called Foo which, when called, sets attributes A and B of the calling object. Then, we add another attribute called C to the function object; because functions are first class citizens, we can call attributes and methods on them, and you call the .prototype attribute on functions to get their modifiable prototype object. We then create an object out of the Foo function, which is then also called and sets preliminary attributes on the created object (this is what some developers call “the constructor call” in Javascript). After all that, we have a normal object called bar – which has as its prototype the function Foo.

Let’s think about this – does anything in this process make sense for Javascript? This is significantly closer to class-based programming than prototypal programming. In fact, if you swap out the word function with class when we declare our Foo variable, it makes so much more sense semantically (even though it wouldn’t execute). Then you can see that Foo is just a class, A and B are instance variables, C is a static variable, and bar is an instance of class Foo.

That’s not how Javascript is supposed to work, and this seems like a hack to force Javascript to work as if it’s class-based – which it’s not. To get more detailed, here’s my beef with why I don’t like this:

  • A function serves a unique purpose of executing a code block and potentially returning a value. A function should never be the parent of an object (like a real Javascript object), because that just doesn’t make sense.
  • The new keyword is ridiculously convoluted in Javascript. It helps create new objects, but it only works if it’s preceding a function call (dubbed a “constructor call,” solely because it is preceded by the new keyword); this doesn’t make sense either because in pure prototypal languages there is no “blueprint” to create an object out of. You’re just creating an object which has the parent of another object – no functions needed. In the words of Kyle Simpson:

    We end up with two objects, linked to each other. That’s it. We didn’t instantiate a class. We certainly didn’t do any copying of behavior from a “class” into a concrete object. We just caused two objects to be linked to each other. – You Don’t Know JS

  • Foo itself is the prototype to object bar. Why do I need to call .prototype on it to access its object values? It already IS the prototype! The answer? Because it’s a function and not a normal object like it should be – that’s why.

Lastly, writing code like this might not seem difficult to read – but that’s because you’re probably used to class-based languages and that’s what you’re interpreting it as. Javascript doesn’t have classes – it’s just objects linking to other objects, and this code doesn’t make that very clear. If you think about Foo being an object which has a child object of bar, this code probably doesn’t make as much sense, does it? Time for some refactoring.

Good Prototypal Javascript

Let’s rebuild the code above to be proper prototypal code:

Look at how drastically simpler this is from our example up above. Even if we didn’t save many lines, it’s much easier to see what’s going on. Foo is an object now – a normal object – and bar is a child object out of Foo. Thus, Foo is the prototype of bar. We didn’t have to throw keywords like newfunction, or prototype in there to convolute anything – and best of all, we’re working WITH the core structure of Javascript’s prototypal design – not against it.

Now, one detriment you’ve probably realized is that for every child object created out of Foo, we need to define attributes A and B. As stated earlier, constructors don’t make much sense in prototypal design because every object is free to have its own schema – but we can still build this logic in while staying perfectly prototypal. Let’s redeclare bar as an example:

Now if we want objects to share a common base schema, we just need to pass in the properties variable as the second argument to the Object.create() method. This doesn’t bind any permanent schema to the Foo object or to any future objects created from Foo – it’s just a simple way to add common properties to objects of our choosing.

Note: When adding properties in this manner to an object, they are by default immutable, meaning they can’t be altered after assigned. You can easily change this behavior if you want – check out how to modify property descriptors for more info.

Conclusion

Javascript is a super powerful language with a lot of great features, but there’s one thing it’s not, and that’s class-based. You can’t – or should I say shouldn’t – write Javascript as if it were class-based because you’ll easily end up with code that’s unclear and doesn’t always work as expected. Javascript is a prototypal object-oriented language, and taking advantage of that design choice will allow you to write really powerful code.

With all the new cool-kid tools and frameworks coming out seemingly every day for Javascript, I wanted to look back at the core API that all libraries use – whether it’s WebGL, Angular, Ember, Backbone, Node, etc. – and help others to understand why Javascript is the way it is, and to help you use that knowledge to write powerful, semantically-correct code. Whether you agree or disagree with me on my points – I hope you found some of this information enlightening!

In an upcoming post, we’ll cover how you can write prototypal code when coming from a class-based language, and we’ll compare code examples between Java (class-based) and Javascript (prototypal) which accomplish the same thing.

Using GeoJSON files with Google Maps API

Some of you may be familiar with using the client-side Google Maps API in your site’s javascript. It’s easily the top-of-the-line API for rendering geographical images and data, and so easy to use. Google even provides you with a developer-friendly tool to style your maps – no prior CSS knowledge necessary. As web pages become more interactive, including these types of maps into your sites will become more and more ubiquitous (even for plain static sites).

To show you how simple it is, let’s just create a basic html page:

And wallah, we’ve built and are rendering a Google Map.

You can even add markers on to the map, which would allow you to indicate specific data points at certain geographic locations. These markers can be any shape too, and if you’re an artist, then you can specify SVG-like paths to get a really fancy marker. We won’t go into markers though, as that’s all well documented by Google.

While the Google Maps API is certainly awesome though, it has its limitations – specifically with coloring or highlighting plots of land that you would like to ‘stand out’ from the rest. Maybe you want to show which US states are more Republican vs Democratic, or maybe you want to show which countries in Europe you’ve visited, or perhaps you even want to show which provinces in China you purchase tea from (yes, I am guilty here). By just using the naked Google Maps API libraries, this is impossible. But we don’t like to accept the word ‘impossible,’ and lo and behold, there is in fact a way to do this using some vary fancy files dubbed as GeoJSON.

What are GeoJSON files?

I’m glad you asked. Per Wikipedia, GeoJSON is an open standard format for encoding collections of simple geographical features along with their non-spatial attributes using JSON. What this means is that you can specify collections of lat/long points in a JSON file that is representative of a plot of land. Since they’re usually written in lat/long values, you can be sure that you’ll get the same result no matter what map API you’re using. Here’s an example of a .geo.json file that diagrams the state of Arkansas:

Now you’re probably thinking “That’s cool, but what good does this do me?” While Google can’t specifically highlight plots of land on its own, it does have support for loading .geo.json files into your map and styling them however you want. This means that we can accomplish what we wanted to earlier: coloring in states, countries, or anything really. Here’s how we could include this arkansas.geo.json file into our existing map from above:

And that’s it! This will insert the data from our .geo.json file into our map’s data – you probably won’t notice anything though because we don’t have any fill color. Let’s add some highlighting to this data:

Perfect, now our map will specifically color in the state of Arkansas with a translucent blue. And that’s about all there is to it – now you can create Google Maps that highlight any plot of land you want. To see an example of everything we’ve discussed here, check out my demo down below.

Where to get GeoJSON files?

You may be left with a question right about now: “Where am I supposed to find the GeoJSON files I need?” And that’s a good question. Luckily, an awesome developer gathered GeoJSON files for every single country in the world, and if you’re wanting to map out the USA, he even gathered GeoJSON files for every single state AND its cities, all inside of a public GitHub repo.

Check it out here: https://github.com/johan/world.geo.json


Live Demo

Check out my demo of using GeoJSON with the Google Maps API.

The source code is freely available too.

Building Javascript with Grunt, Bower, Browserify

Note: This post has been updated as of October 23, 2015.

This post is continuation of a previous post covering bower and browserify; if you haven’t read it yet, I highly recommend you start off by reading Getting Familiar with Bower and Browserify before starting here. Let’s review our goals regarding javascript building that we landed upon at the end of the last post:

Goal: We want to automate the gathering actions of bower and javascript-building actions of browserify in our workflow to make for a seriously powerful javascript pipeline that we don’t have to continually maintain.

We’ve covered a brief intro into bower and browserify, and now we’re ready to get our hands dirty with them both by using them with grunt.

Installing Grunt

If you’re unfamiliar with what grunt.js is, or build automation in general, please check out the grunt.js homepage for an introduction. Despite the rising popularity of Gulp (another build automation tool), I am choosing to stick with grunt as it currently still has a larger plugin community.

Assuming you already have bower and browserify installed (if you don’t, see the last post), then all we need to install is the grunt CLI:

Now that we have the grunt CLI installed, we need to establish a package.json file for our project in order to install the rest of the grunt plugins we’ll use.

Installing Grunt Plugins

Create a new package.json at the root of your project folder, or update your existing one, to include the following devDependencies:

Let’s also create a bare bones bower.json file with some base libraries:

To install node modules:

This will install the bower and browserify grunt tasks, as well as verifying that you have the regular browserify module installed. Let’s hold off on installing our bower components yet, we’ll let grunt take care of that.

Now that we have everything set up, we can finally start our Gruntfile. Let’s start off with the basics:

Creating the Gruntfile

We don’t have anything exciting yet – just a basic Gruntfile skeleton. Let’s start off our workflow by automating our bower component installation:

These settings are customizable, but I’m a fan of dumping all my vendor packages into a /vendor directory. The layout attribute states that the package will be within its own folder (as opposed to default js/css/etc. folders that bower likes to use), and the cleanup option ensures that prior to the install command being run, the directory will be wiped out.

Now we can install our bower components like so:

We will now have jQuery and Modernizr installed in /vendor/bower_components. Perfect – now let’s get to using those files with the help of browserify. Let’s add this to our Gruntfile:

This will take a javascript source file (or many) and build it out into a browserify bundle that is browser friendly. So our end goal is to create a bundle from a file like this:

But can we do this? Alas, no, not yet. We have three problems:

  1. While we have jQuery and modernizr installed through bower, browserify has no idea where they’re located, so we can’t just require them like we are – we would need to require exact script locations.
  2. With modular programming, we would need to assign jQuery to the $ variable, and modernizr to the Modernizr variable before we could use them in that way.
  3. Browserify can only require CommonJS style scripts … so basically modules, and while the scripts we have for jQuery and modernizr may be built as modules, we can’t be sure. Plus, we still want to be able to require other vendor scripts even if they’re not modules.

So have we come this far for me to tell you we can’t do anything, and you can only use browserify for your own CommonJS style scripts? No, absolutely not! We can fix this with an awesome node module called browserify-shim.

Adding Browserify-Shim

Browserify-shim is a node module which allows you to include non-CommonJS style scripts into browserify’s require command, and to also assign them to aliases that you can use in your scripts. You can check out the GitHub repo to see all the features, but we’ll just go over installation and implementation here.

Install (as a devDependency here):

And then add this to your package.json:

In a nutshell, browserify-shim is exposing our jQuery and modernizr packages as a different name for browserify to look for (jquery and modernizr, respectively), and then we are aliasing the modules to the variables we’re used to using: $ and Modernizr. Lastly, we tell browserify to run browserify-shim prior to building out the files, which is what allows all of this to happen.

Browserify-shim can do even more than this, but that’s all we need it for. Now will this javascript work?

Yup, 100% as long as we’re using grunt to build our javascript.

Summary

I know we’ve covered a lot here, but if you can implement this workflow into your javascript pipeline, you’ll seriously boost your productivity. To review everything we’re doing here:

  • Using bower to simplify how we get our vendor scripts, as well as managing versions easily.
  • Using browserify-shim to turn all non-CommonJS scripts into browserify-compatible modules.
  • Using browserify to write modular javascript code, and build everything we want into a small amount of organized bundles.
  • Running everything through grunt to handle all the tedious work for us, so we can concentrate on the fun stuff.

While the big benefit here is that we have really improved our workflow to allow powerful services to do the work for us, another thing to consider is that now we can really true modular code. That’s a best practice in every language, and having that at our disposal allows us to write clean, beautiful javascript that is very readable and very debuggable.

You made it to the end, and now at least have some familiarity with using bower and browserify in your project. Give it a try and see how you feel about your new javascript build process. I promise you won’t be disappointed!