5 Tips to Become a Better JavaScript Developer

js_logoJavaScript is still a mystery to a lot of people. With it’s growing popularity with things like Node.js, Angular.js, and jQuery, people are wanting to know more and more about the language. With more beginners jumping in, there’s room to make mistakes that JavaScript will more than willing let you do. This list is composed of mistakes that I see people make that don’t quite grasp some of the more complicated aspects of JavaScript. Some of these you can implement right now, others take some additional learning. Let’s begin! Continue reading

Top Reads for July 2014

Here are the top reads of articles, libraries, and websites that I found cool or useful for the past month. Enjoy!



Minimal Angular module/syntax approach using an IIFE
Using AngularJS with the ESRI JavaScript API
ng-token-auth – Angular.js token authentication helper
8 Things I Wish I Knew About Angular.js


Farewell Node.js
Beer Locker: Building a RESTful API With Node – CRUD
Build Your Own App Specific REPL For Your NodeJS App
Error Handling in Node.js
Making Express.js Authentication Fun Again


JavaScript Tree View
Helmet – Add basic http headers to Express.js
deb.js – Enhanced front-end JavaScript debugging
7 Patterns to Refactor Your JavaScript
Node.js Performance Tip of the Week: Managing Garbage Collection
buddy.js – Find JavaScript magic numbers

View June 2014 Top Reads

Setting up Local Git Repository on Windows Server

I just had the experience of getting a local Git repository setup on a Windows Server. Since this is something that I know I’ll probably do in the future, I wanted to document my steps here, not only for myself, but for anyone else that doesn’t really know where to start on getting that up and running. I’ll assume you have some basic knowledge of Git, what it is and how it works.

Install Git

The first thing to do is install Git for Windows on the server. If you visit this link, Git will automatically start downloading. Most of the options when installing it can be left as the defaults. The only choice you have to make is on line endings which you will make on this step:

Git Line Endings

Git Line Endings

I usually select Checkout Windows-style, commit Unix-style line endings. This is usually the best choice if there’s a possibility this repository will be used cross platform. That way if a file is opened using Visual Studio or some Windows exclusive editor, your new lines will be retained. If the project is exclusively Windows based, then the third option will probably be fine.

Once the setup is complete, Git is now running on your server.

Setup Network Folder

The next step is to share a folder across the network so that different people can do pulls and pushes from the repository. I recommend creating a folder that can hold multiple repositories. This way you can create as remote repositories as you want under a single point of reference for people.

After the folder is shared, anyone who wants to use the repository in Windows will need to setup a network drive on their machine. You will need to do this also to start adding files to the repository as the server repository won’t hold a working copy of the project files. I’ll go more into detail about this when the repository is initialized in the next section.

Git Init

Now that you have a shared folder to store your repos and mapped it to a network drive on your machine, the next step is to create your project’s central repository. For this, my project will be called MyProject. In the shared folder on the server, create a folder called MyProject.git. The ‘.git’ is optional, as it’s more of an indicator that this folder is a central Git hub for the project. Next you will want to bring up Git Bash and inside this new directory, run the following command:

The ‘bare’ flag means that this repo won’t keep a working copy of the files. It will act as a hub of the change to those files. The ‘shared’ flag says this repository will be shared among many users. To be honest, I’m not entirely sure this flag is required, but it doesn’t hurt. If you want to read further on other flags, you can visit the git init documentation. After that finishes, this is what should in the directory.

Git Init

Git Init

Your central repository is now up and running. This repository will only accept pushes. Since it doesn’t have a copy of the files, edits cannot be done directly to them through that repository. Someone has to clone it first.

Local Git Repository

At this point you should have a mapped network drive that has MyProject.git in it. Now it’s time to start committing files to the repo. Create your project directory anywhere you like. In that directory, you would do the normal ‘git init’ command without the flags from above. Next thing is to add our newly created shared repository as a remote in our project. Using the drive letter of the network drive, run the following command:

There’s a lot of slashes but this will point our new local repository to have the remote point to the central repository.

Now you can develop as normal and push just like you would to Github, but now it pushes to your local network. It’s actually a lot easier than I had expected to get that up and running. Doing projects on Github, most of it just seems like magic. Hopefully this small guide helps you running Git on Windows Server.

JSHint Using Gulp

JSHint Using Gulp

A JavaScript task runner has become a main stay for almost any new project I start. Some people think that runners like Grunt and Gulp are limited to only Node.js projects, but any project can benefit from a simple task runner. I’ve started using Gulp to do tasks in .Net projects and Go projects I’ve been toying around with. When it comes to building CSS and JavaScript, specifically, it’s bliss.

Over time, I want to share some tasks I’ve created or tricks I’ve found using Gulp that hopefully could make your life easier. The first one, although simple, can be quite useful. I’m going to show how you can lint your JavaScript files with JSHint using Gulp. If you’ve never heard of JSHint, take a look at this quick article that explains what JSHint is. I’m assuming for this post that you have Node.js with NPM installed.

Install Packages

At the minimum, there’s only two Node packages that are needed to get this running, gulp itself, and gulp-jshint. To do that, just install them from NPM.

This should add gulp and gulp-jshint to your package.json as well as install them to the node_modules folder. Now you are ready to go.

Create Gulpfile

If you aren’t familiar with Gulp and don’t know what the Gulpfile is, it’s where you specify your tasks and how they behave. For our instance, we want to create a jshint task that we can run to lint our JavaScript files.  Create a file with the name gulpfile.js at the root of your project, or at the same level of your package.json.

The first thing to do is bring in our two packages.

 Create the Task

Now comes the meat and potatoes of Gulp, tasks. Tasks are segments of actions that you want to take on your project, whether it be linting, compressing, concatenation, or creating a build. I’ll just call this task ‘jshint‘.

We can now do gulp jshint from the command line to execute this task.

Next to is get JSHint up and running. With Gulp, you need to specify an array of source files to pull into its stream. Then those files are piped into the next operation you want to do. This is the defining difference between Gulp and Grunt, are streams. In this case, we will have our JavaScript files get piped through the JSHint plugin. Out will come some output to the console on how the files tested.

This is how it looks using code.

The src function uses the node-glob syntax of specifying file paths. It’s flexible allowing you to use wild cards as well as telling it to ignore paths.

And that’s all there is. Just update the array with the paths of the scripts you want to lint, run the gulp jshint command.


There’s other things that you can do to have more control over how the JSHint task runs. For starters, by default, the task won’t stop if there’s an error with one of your files. So if you had chained some tasks together, if the JSHint task encountered an issue with one of your files, it would still continue to run the other tasks. If you want it to quit if it does find a problem, just add the fail reporter to the end of the task, like so.

That will force it into an error and break the chain.

Secondly, if you are looking to control what JSHint checks for, you can using a .jshintrc file. By default, the Gulp JSHint package checks for the existence of this file and uses it as its ruleset. If it doesn’t find one, it uses a default ruleset specified by the plugin. This should get created alongside your Gulpfile. I suggest taking a look at Mean.io’s file in the Github project. I find their’s has a good set of rules and works with both Node.js and client side JavaScript pretty well.

Lastly, there are custom reporters that you can use to change the way it outputs the results. You can also create your own if you wanted. I usually use the jshint-stylish reporter. It only adds a little extra formatting and more color to the output. With that said, my JSHint task usually looks like this:

 Wrap Up

This is just the very tip of the iceberg of what can be done using Gulp, or any of the JavaScript task runners for that matter. If you have any questions or comments on JSHint using Gulp, let me know below or hit me up on Twitter.

JavaScript Tree View

A tree view is a fairly common UI component. There were lots of implementations of it that I found that relied on Angular, jQuery, or even Dojo. They all were good solutions, but felt heavy for what I wanted them to do. I just wanted a simple tree view without all the bells and whistles that many of them tacked on.

I decided to write my own JavaScript tree view. Meaning that it can be used with any library you decided to use. It also has a small snippet of CSS that comes along with it just to give it structure. I did not do much in the way of making it stylish. I’ll leave that up to you to get it to look how you want. I did that so it doesn’t clash with any theme you already have setup on your site.

I uploaded a sample page to the repo, but I’ll also outline it here.


Make sure to bring in the CSS and the JS file. Other than that, it only needs an element with an ID to load into.


Once the page is setup, creating the tree is simple. The constructor takes two arguments. The first one being a an object that represents the tree structure to create. I’ll go over the aspects of that. The second is the ID of the element to load the DOM into.

Here’s an example tree structure.

At least, each object needs a name and children property. The name is the text to be displayed for the node. Children is an another tree structure to add children to the node. Hopefully that makes sense.

Last to not least, we create an instance of the tree view, using the ID from the div in the HTML.

If you got everything setup correctly using the data I put here, you should get something that looks like this.

JavaScript Tree VIew

JavaScript TreeView


One thing I added to the tree view was the ability to attach some event handlers. There’s a collapse, expand, and select event. You can attach handlers using the on syntax.

There’s a third parameter that will specify what this will be in the callback. You can also detach handlers using off. Pass in the name and the same handler and it will remove it.


I’ve got a Github repo setup. I’m working on adding tests but if you have any issues or questions, hit me up on Twitter or create an issue on the Github page.

Github repo.

Top Reads for June 2014

I’ve been wanting to start this for a while. These will just be a collection of various posts, libraries, or projects that find interesting throughout the month to form a ‘Top Reads’ summary. Some of them I’ll share over Twitter, or bookmark for myself later. Figured it would be nice to share these with you guys as well in one central place.



Better logging in Node.js – Gary Chambers
ES6 Dependency Injection Container - Bence Dányi
Securing a JavaScript based web application - Erlend Oftedal
Node.js in Production – Jeff Dickey
Create a TV Show Tracker using AngularJS, Node.js and MongoDB – Sahat Yalkabov
AngularJS Token Authentication using ASP.NET Web API 2, Owin, and Identity - Taiseer Joudeh
Building with Gulp – Callum Macrae
Emulators Written in JavaScript – Frederic Cambus

Mock HttpContext using Moq

In a project I’ve been working on, I needed a way to be able to test Windows authentication to an ASP MVC app. Having that authentication rest at the controller level made sense, but from a testing perspective it made things somewhat difficult. One aspect that wasn’t clear to me was mocking the HttpContext on the controller that controls the authentication checks. Especially since getting that setup to run correctly without using mocking, makes the test more of an integration test, rather than a unit test. Even though controllers are meant to be lean from a logic sense, being able to test the actions respond with the correct response given a set of parameters can be useful.

I wanted to share the mocked context I came up with and how to use it so that if you need to unit test your controller using Windows authentication, it’s that much easier. I’ve seen numerous people asking about mocking the User.Identity in the controller. This will explain how to do that.

I’m using Moq for my mocking. I don’t have a solid reason as to why I use it, just that’s what we’ve been using for our projects at the city so it’s what I learned to use. If you are using a different mocking framework, I’d love to hear about it.

Let’s get to it.

MockWebContext Class

I’ll go over it piece by piece. First, the class definition and the public properties:

The properties match the properties an HttpContext has. This way if we need to mock other aspects of it, we can. The most important one is the HttpContextBase (highlighted above). This is where the User object comes from that handles authentication.

Next, we are going to create two constructors. The first being the default constructor that just instantiates all the mocked properties:

We are really just mocking the various pieces of the HttpContext so that if any of them are accessed they return an empty mocked object. This is just to be used to test normal controller operations where authentication is not needed. Another place where you can do some cool things is with the Request object when doing tests. You can make the request return what you want to test malicious requests, malformed parameters, or other things.

Mocking Authentication

We need another constructor that will setup some authentication pieces. To explain it a little better, when doing Windows authentication, normally there’s a list of Active Directory groups/users added to the Web.config to limit access to certain people. In an ASP MVC controller, we can check if a user is in that list by doing:

The other method of checking a user’s authentication is the IsInRole method. This allows you to pass in the name of an Active Directory group and check if the user is in the group or not:

With that in mind, we will create a constructor that will setup these methods to create a HttpContext that can do fake authentication:

This constructor calls the default constructor to set everything up, and then it mocks out the methods I mentioned above. I set it up to allow multiple groups to be passed in if there are multiple checks that are made. You can change it to only be a single group if you wanted.

That’s the basics of creating a fake HttpContext. There’s one more piece that I added that’s not necessary, but have become useful. I added two static methods to the class that creates a controller context.

Using the Mock

So let’s see how to use our fake HttpContext on a controller so that we can go about testing them with and without authentication. Obviously you’ll need to mock out any other dependencies the controller may have, but having a mock HttpContext, the controller can be tested in isolation.

Let’s say I want to create a test class for my Home controller. This is how I could setup the tests:

If you wanted for a few actions to have some authentication happen, just change it in your test:


That’s it. Mocking out that HttpContext is simple and I found it really useful to be able to test the authentication workflows that some of our controllers do.

If I did something wrong and you have a different method, I would love to hear about it.

Using AngularJS with the ESRI JavaScript API

I’ve been doing quite a bit of learning about AngularJS since it seems to be the current hot topic in JavaScript. Since I had to rework a map for the city (I’m currently employed with the City of Scottsdale), I decided to see if AngularJS could be used in partnership with the ESRI JavaScript API to make creating, structuring, and displaying data that much easier.

Being that the ESRI API is based on Dojo, we are duplicating some of that functionality by bringing Angular into the picture. I’ve built a full app using only Dojo with the ERSI API and I’ve had issues with doing it with pure Dojo. Those being:

  1. Dojo doesn’t do two-way binding. When developing a data-heavy map app, that starts to become quite useful.
  2. Dojo’s widgets don’t seem to integrate well with other widgets. They do have an event structure to communicate between modules, but that’s primarily the only way it can be done. This is somewhat of a by-product of Dojo being a toolkit, rather than a framework. An application structure is not implied by Dojo.
  3. Dojo’s unit testing support is something that I cannot understand. They have their own harness that is used for testing Dojo code but I cannot get it to work. That may just be how I was trying to use it, or how I structured the widgets in the app, but I was having a difficult time.

For those three reasons, Angular seemed like a good idea as it resolves those issues. Angular also does all three of them quite well. Angular is a framework built with MVC in mind, this implied structure makes communication and creating modules much easier. It was also built with unit testing in mind. Apart from the necessary map widgets, I’ve tried to avoid using Dojo to increase testability. Obviously, mocking the Dojo pieces could prove difficult but I’ll go more in depth about that in another post.

I figured I would share a simple example of creating a map with layers using Angular. This may not be the most efficient or best way but it works for what I’m doing for the city maps. Let me know if there’s any ways that it can be done better as I’m very much still learning Angular.

This post does assume a working knowledge of Angular. If you know nothing about it, I suggest going to their site, do some examples, and come back as the code will make much more sense. It also assumes a little knowledge of the ESRI API. I’ve got a couple posts on creating a map, drawing a point, and displaying data. That is a good starting point and is more than enough to get you going with this post.

Let’s get to the code.

Getting Going

To start, we need to bring in the ESRI API and Angular, obviously:

We also need to setup Dojo’s AMD, so that we can seperate our modules into seperate files, to be able to pull local modules. I’m just going to do this inline instead of creating a new file since we only need to setup our local package.

This line needs to be added before you bring the ESRI API. Update the location with where you’re local script files will be.

Create the Map Directive

We need to create a directive for the map container. This directive will instantiate the map and attach some events to the map that various scopes can tap into.

Let’s create the map module:

Next, we want to create the directive definition:

If you are not familiar with some of the options, I suggest looking through Angular’s guide on directives. One thing that may look a little different is attaching a different controller and passing the element to that controller. I got that structure from ui.bootstrap, which has a collection of directives based on Twitter Bootstrap. This article breaks down that method better than I could. They talk about controllers being easier to unit test than putting everything inside the directive. We can test the controller in isolation from the directive. Some say the controller should not have access to the DOM, but this way we can mock the DOM element when testing the controller as well.

Now for our map controller:

The createDiv function basically makes the container for the map to attach to, this way if there’s any directives inside the map directive, the ESRI map won’t remove whats in there. We also give support for changing some of the map options via HTML attributes (there’s an example of this at the end of the post). The only attribute that is made required is the id attribute as that’s the way the map attaches itself to the div. createMap is pretty self-explanatory; create the map and attach the events. We also check to see if there’s any layers to add that were created before the map was created.

We added an addLayer method to the scope so that layers inside the map can get added. We need to check if the map exists so we defer the adding of the layer. This is just to make sure layers won’t attempt to get added before the map is fully loaded. This will be used in the next section.


Adding Layers to the Map

What’s a map if you can’t add layers to display data on it? We will follow the same directive structure as we did with the map.

I’m going to only show creating feature layers in this post, which you can read more about in a previous post I made about displaying custom data using feature layers. I’ll be using a sample layer that ESRI uses through some of their samples. Other layers like the Tiled, or Map Service, will somewhat follow the same structure. I can go more in depth about those if needed in another post.

Module definition:

Now for the directive:

This is similar to how we setup the map directive with some small differences, one being the require attribute. This forces the directive to be inside our esriMap directive. Angular gives us a bunch of other benefits like being able to access esriMap‘s scope meaning we can get to the map if we need to, as well as other methods we allow access to, like the addLayers method. We also don’t need to pass in the element to the controller since we won’t be modifying the element itself at all.

Let’s create the controller:

The controller is simple. We just check some required attributes, instantiate the Feature Layer, then add it to the map. Here’s an example of the HTML with map and layer together:

That’s it. Now you have a simple structure to create a map and add feature layers to it using only HTML. With all that being said, you should get something like the following:

Angular ESRI Example

Angular ESRI Example

Wrap Up

This was meant to just be a ‘getting started’ post. I have plans to talk about clicking on features to display their attributes and creating custom map specific widgets like a toolbar or street/satellite selector. I also want to show how to write unit tests for the two directives created above. Also, if you’re an Angular master and can let me know how my code can be improved, let me know in the comments, or let me know if there’s any issue you have using Angular with the ESRI API.

Update 8/29/2014: Typo in the one of the code samples that would make it not run. Thanks for pointing that out Jeffry Houser!

Displaying Data Using Feature Layers

This is the third post in a series of posts regarding the ESRI JavaScript API and creating maps on the web. The first one I showed how to create a simple street map, and the second one was on how to draw a single point on the map. In this post, I’ll go a little more in depth on displaying some useful data on the map because that’s what makes maps useful.

What is a Feature Layer?

Feature layers in the ESRI JavaScript API are a special type of layer that can be added to the map. Tiled layersMap Service layers, and Graphics layers don’t have data, or attributes, attached to what gets put on the map. When tiled and map service layers are drawn, the server responds with just a PNG tile of what that area of the map looks like. Since we can’t attach data to specifics spots on a PNG, it makes sense that there needs to be a layer that supports that. Instead of being an array of images, a Feature layer is represented by a JSON object that contains an array of features as well as other properties needed by the layer. A feature being the object being represented on the map. A Feature layer does inherit from the Graphics layer since it as well needs geometry and a symbol to represent the feature’s location.

Feature layers can be created using two different methods. The first is that it’s pointed at a url which is served up by an ArcServer REST endpoint. This url is a specific layer inside a map service. This method I’ll cover in a later post. The second way is building the JSON object, which is called a Feature Collection, manually. This gives us the flexibility of serving up our own data as long as there’s a geometry attached to the data. There are advantages and disadvantages to both ways. The main disadvantage we get with doing it manually is that we lose the ability to use the built in functionality for editing and querying of the data. These would have to be handled manually as well. I’ll go over how to handle this.

Creating a Feature Collection

As I mentioned, the Feature Collection is just a large, predefined JSON object. Here’s an example of one from one of ESRI’s samples:

There’s much more than can be done but this shows a pretty simple example. It all starts with the Feature Collection base object:

  • layerDefinition: Pretty much what it’s called. It defines the map layer information.
    • geometryType: The feature geometry type (i.e. point, polyline, or polygon).
    • objectIdField: This will be the ID field that will get automatically assigned to each of the features. We will visit this in the next section.
    • drawingInfo: The renderer the layer will use when drawing the features on the map. An explanation of the renderer can be found here.
    • fields: The array of fields the features will have. More about the fields can be found here.
  • featureSet: The array of features and the geometry type is needed again.

Create a Feature Set

Feature sets are the array of features that will be drawn on the map. A feature set has a features property that is an array of graphics. Each graphic, as I’ve mentioned before, require two things, geometry (or location), and a symbol (for drawing). In a feature set, these graphics still need geometry in which the geometry type needs to match the geometry type of the layer you’re trying to create. The symbol is optional in that the layer has its own renderer defined so the feature can use that instead. The third piece a graphic can have are attributes. The list of fields defined by the layer definition tells the layer what attributes to expect from each graphic. Attributes for a graphic are set by using a simple JSON object.

Using our example definition above, here’s what an array of features might look like:

This is a really simple example, but there’s quite a bit of customization that you can do.

My Own Example


Feature Collection Example

Feature Collection Example

The points, as shown above, should mark New York City, Los Angeles, and Chicago. I used a png I found online for the marker, but you can use any image you want or you can swap it out with a color symbol.

Wrap Up

There’s more I want to go over, especially on editing, adding, and deleting features using the map. As well as show a read only popup of the data contained within a feature. Since this post is getting kind of lengthy, I’ll delegate that to a future post. So make sure to keep checking back. Any typos, corrections, or if anything can be done better, let me know in the comments or on Twitter.

Gulp vs Grunt

I’m working on a web side project using Node.js and Express.js. If you’re not familiar with either of those things, I’ve linked to both of their homepages. Express.js isn’t a requirement for what I’ll be talking about here, but having a working knowledge of Node.js would be helpful.

Gulp & Grunt

Gulp and Grunt are both task runners based on Node.js. I won’t go into the nitty-gritty on what can be accomplished with both of these toolsets. If you go to their respective sites, it will do a better job explaining that than I can. What I will be discussing is just a comparison of the two on how it relates to the their config files.

The Project

After starting the project, I initially went with Grunt as that was the easiest to setup and get the project going. At some point, I decided to get the same tasks using Gulp. After porting the tasks to Gulp, I wanted to share the two files because, 1: For anyone to point out what I’m doing wrong or can do better, but 2: as a sort of reference for task translation between the two.

I’ll show the files first, and then I’ll kind of break them down.




The jshint and less tasks are just for basic linting of JavaScript files and compiling LESS CSS. I know that Express will compile the LESS for me, but I want to add CSS linting at some point hence why I created the task to compile the LESS.

I did my unit tests using Mocha. I have two sets of tests, one for unit testing models and controllers, and one for doing full integration testing of the Express controllers. The unit tests just need for the app to set itself up to make sure models are registered along with other initialization steps. The integration tests actually spin up the Express serve to handle requests and interacting with the DOM.

The Grunt file has some maybe confusing pieces that I wanted to clear up. The first being thetime(grunt);. This shows how long a Grunt task takes to execute. Gulp already does that. The other piece is the loader. As seen at the bottom of other Grunt files, each plugin needs to be registered with Grunt before it can be run. The load-grunt-tasks package looks for Grunt plugins that you have installed and registers them for you. This saves many lines of repetitive code in the Grunt file.

Wrap Up

After switching everything to Gulp, I’m really happy with the result. As you can see, Gulp results in less code. One thing I also really like about Gulp is something fail to grasp is the fact that a lot of Gulp’s plugins don’t come from plugins at all. As long as a package implements the streaming standard, Gulp can use it in a task. I hope to go more into that in a future post. I more than welcome suggestions on how I can improve both of these files.