Moving Up: Upgrading From Pathogen to Vundle

When I first started in earnest with Vim, Vundle didn’t exist. Tim Pope’s Pathogen was the only game in town. Pathogen worked fantastically well and did exactly as advertised. But since that time, new philosophies regarding dependency management have emerged, spearheaded by projects like Bundle. Vundle takes Bundle’s philosophy and applies it to Vim bundles.

While Pathogen does what it does well, it leaves a fairly significant hole, especially in the case of versioning Vim configuration with Git. Git doesn’t version the contents of a “nested” Git repository, so cloning a bundle becomes problematic.

You’re left with three options. One, leaving the .git directory, preserving Git functionality on the bundle but being unable to add that content to the vim configuration repository. Two, removing the .git directory, committing the contents to the vim configuration repository, but losing the ability to easily update via git pull.

And three, submodules.

Interim solutions: git submodules (yikes!)

I decided to use an interim solution, git submodules. These technically gave me the flexibility I needed, but the general consensus is git modules should not be used. Using git submodules in this way highlighted for me why people strongly discourage their use.

For one, checking out a repository that contains submodules requires a special command. Did you just run git clone? Sorry, none of the submodules have actually been downloaded; a “special” command is needed to properly pull the contents of the submodules.

Upgrading submodules is even more problematic. It’s almost a witches brew of options. You could try git submodule foreach git pull, but you may need to go with git submodule foreach git pull origin master. But then again, you may just want to go with git submodule update --recursive, which is faster these days. Or, you might want to go with git submodule foreach "(git checkout master; git pull)&", or you could try git submodule update --init. Who knows? The fact that the command you need to use changes (dramatically) based on the version of Git installed on the machine you’re using at the time is nothing short of a programmers nightmare. And this is just for updating.

Enter Vundle

Vundle, like Bundle, handles the management of bundles. Rather than copying and committing each repository into bundles/, merely specify bundles within .vimrc, much like stating application dependencies within a Gemfile.

Here’s an excerpt from my vimrc file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
" Bundles
Bundle 'vim-scripts/Align'
Bundle 'Raimondi/delimitMate'
Bundle 'tpope/vim-ragtag'
Bundle 'Lokaltog/vim-powerline'
Bundle 'airblade/vim-rooter'
Bundle 'tpope/vim-surround'
Bundle 'scrooloose/syntastic'
Bundle 'tpope/vim-commentary'
Bundle 'kien/ctrlp.vim'
Bundle 'ervandew/supertab'

" Syntax plugins
Bundle 'hail2u/vim-css3-syntax'
Bundle 'othree/html5-syntax.vim'
Bundle 'tpope/vim-markdown'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'tpope/vim-haml'
Bundle 'jQuery'

I cannot overstate how simple this has made my vim configuration repository. What once was a large collection of numerous repositories or submodules is now nothing more than almost a single file. The only thing left in the repository are my colorschemes and a useful .gitignore!

My installation on a new machine is a simple three step process today:

  1. Git clone the repository
  2. Symlink ~/.vimrc to ~/.vim/vimrc
  3. Open Vim and run the Ex command :BundleInstall

Simple, consistent, and reliable. In the future I can run :BundleInstall! (note the exclamation mark) to download the latest updates to my bundles.

A useful .gitignore with Vundle

With Vundle, the only bundle you really want to include in your git repository is Vundle itself. However, other bundles will be downloaded into that directory, causing your Git repo to prompt you to try (note: try) to add these files. Rather than worrying about the noise, I simply added this to my .gitignore:

1
2
bundle/**
~bundle/vundle

This informs git to ignore everything within the bundle directory, but to specifically not ignore the Vundle directory. You can update bundles, Vundle itself can be updated, and Git only ever prompt you if Vundle’s own files have been udpated. It’s fantastic and really rounds off the use of Vundle.

Lessons Learned: I should have done this sooner

Sorry Tim Pope, but I should have looked into Vundle earlier. If anything my experience with Pathogen and Git Submodles gave me the experience necessary to tell cautionary tales regarding submodules. There’s nothing inherently wrong with Pathogen, but Vundle offers a much better ease of use when paired with Git.

My Password Practices as a Programmer and User

Arstechnica recently ran an article on password cracking. A passerby might be struck with a little fear, considering this article might lead you to believe that, once the database is compromised, it is only a matter of a short time until your password is decrypted.

The article fails to mention, however, that the setup they used is about as close to ideal as possible for the crackers, or as close to naive as possible for the programmer who made the encryption layer in the first place. Encrypting passwords with MD5 is a grave mistake, MD5 being one of the weakest and fastest encryption algorithms available today. Secondly, the passwords were entirely unsalted. There already exist full rainbow tables and online lookup tables with nearly every possible MD5 value for unsalted alphanumeric strings. Theoretically anyone worth their salt (har) would be able to decrypt 100% of those passwords within a single day.

There are two sides to the password discussion, the programmer and the user. Each need to take their own precautions, but there’s a lot that can be done to combat the issue of databases being stolen, which seems to happen with alarming regularity these days.

Never use the same password twice

I’m guilty as anyone for establishing a “universal password”. Back about 10 years ago, having a good, strong, alphanumeric password was our best approach to password theory. Because we started requiring strange permutations like capital letters, numbers and symbols in passwords, it took a significant amount of time to completely memorize your complicated string. It was best to establish one complex password to be regularly reused.

10 years ago, having a good, strong, alphanumeric password was our best approach to password theory

However, this lead to an interesting phenomenon - cross-site (or service) account hijacking. As the industry switched over to email addresses being used as a username (not a terrible idea), and as passwords from less secured sites had their databases lifted, hackers would use the credentials from unsecured Site A to hack secure Site B. We saw this spring up extensively within the gaming industry, where a hijacked account could be turned into real world money.

…hackers would use the credentials from unsecured Site A to hack secure Site B

Players in an MMO would potentially use the same email (expected) and password (bad!) to sign up for both the game and, for example, their guild’s forum. Said forum’s server would be hacked, its database hijacked, and decrypted credentials sold. It was possible then to log into those user’s accounts, liquidate their characters, and resell that gold for real money. This has become a huge liability for online games as, while their own services were not hacked, a user logging in to find their characters liquidated would clearly rest the blame with the game itself. The thought wouldn’t even cross their minds that the hack had more to do with some remote forum or website.

Rather than establishing a universal password, its best to establish a universal password paradigm. This paradigm would cause the password itself to change from site to site.

I’ve heard of some people using the second or third letter in their password as the first letter in the name of the service they are logging into - that’s fine. But I think we can do better.

Why not devise a standard, easy to remember phrase which incorporates the name of the service you’re logging into? For example, you may have a phrase like, “ireallylike[servicename]” as your password, which would turn into “ireallylikefacebook” or “ireallylikeamazon”. Exceedingly simple to remember, a large number of characters to make password cracking rather difficult (the amount of time it takes to crack a password increases exponentially with each character), multiple words as to not be vulnerable to dictionary attacks, and becomes automatically different for each site/service. I’ve incorporated something like this into my password habits and I love it.

…devise a standard, easy to remember phrase which incorporates the name of the service you’re logging into

An interesting benefit is, on mobile devices, it actually makes typing these in quite a bit easier. No longer am I constantly toggling caps, numeric or symbol keyboards, and I’m actually more secure.

The downside are sites which have less-informed password requirements, requiring capitals, numbers and/or symbols to be present. I find these sites incredibly annoying, as they’re actually enforcing an anti-pattern for password management. Even worse are sites which restrict the password length to an arbitrarily low number. For those, I typically turn around and never sign up, as it demonstrates a very poor password storage policy in the backend.

Password storage best practices

When LinkedIn was famously compromised, it was revealed they used SHA1, no salt. Decrypting the database only was a matter of time. Without a salt, any standard SHA1 rainbow table was already well equipped to decrypt the passwords. What a disaster.

Salting your passwords is a good first step, but the best practice is to use a different salt for each user. By using the same salt for all users, a potential hacker could create a rainbow table using that single salt, and that table is good for your entire database. There would be an initial investment of the rainbow table’s creation, but it would only need to be done once. You want those rainbow tables to be as un-reusable as possible.

…use a different salt for each user.

Whenever I write a login script, my table will contain something similar to:

username | password | salt

The salt can be generated from anything; I usually go with a MD5 value of the timestamp of the password creation. Append their username if you want to ensure absolutely no one can have the same salt, incase two people register at the exact same microsecond (I’m not overly worried about that, personally). Some people may be initially surprised, “Exposing the salt! Gasp!” However, there’s realistically no problem with this. If you’re only using a single salt for a database, the concept of keeping it “secret” (and I quote “secret”, as any hack is going to inevitably reveal the salt, anyhow) seems to be important at face value. But when each user has their own, its secrecy is no longer critical for security.

And secondly, use bcrypt. The merits of bcrypt are fantastically outlined here. Simply put, bcrypt is designed from the ground up to be used with passwords in mind. It’s the best choice today for encrypting your passwords.

Password requirement prompts

If you enforce anything outside of length to your users, you’re doing them a tremendous disservice. XKCD has a fantastic comic on passwords. Simply requiring numbers or uppercase letters, honestly, does nothing to increase security. As a password cracker generating rainbow tables, of course you’re going to opt to use lowercase, uppercase, numbers and symbols. The english alphabet contains 26 characters, and you’re absolutely going to use uppercase letters as well, so you have a default starting point of running through 52 characters. Adding in numbers and symbols will add, optimistically, around 30 more characters. Whoopee. You could have a 6 character password full of numbers, uppercase characters in a completely random manner, and any password cracker will have it unlocked within minutes.

However, if users are allowed to simply have long passwords, the entropy increase is incredible. Each additional character adds an exponential amount of time to the cracking process. Getting up to 20 or even 40 characters produces passwords that would literally take decades to crack, accounting for Moore’s law. That being said, bcrypt does have a maximum limit of 55 characters. Considering we’re used to 6 or 8 character passwords, 55 seems more than abundant. Our earlier examples of “ireallylikeamazon”, for example, clock in at 17 characters - nearly triple that of the standard minimum of 6 character passwords, but not even close to the upper limit of 55.

Wrapping it all up

Protect yourself personally, and protect your users. Hacks happen to the best institutions. As a programmer, ensure that a hack is exceedingly difficult for crackers to benefit from, and as a user, limit potential hacks to only affecting a single site or service.

Super Simple Web Server for Testing in Seconds With Python

Sometimes you want to test things locally but you don’t want to access your HTML page just via the file browser. Perhaps you’re looking at code which uses relative URLs to the root directory, or perhaps you’re trying to access some local AJAX and you’re getting the inevitable access control origin problem.

Do you build up another Apache virtual host? That can be both heavy and annoying. Even with tools like VirtualHostX, it’s still cumbersome to create yet another virtual host for something which may just be temporary. What is a developer to do? Well, Python has come to the rescue.

Change to the directory you’d like to run your files from and run:

python -m SimpleHTTPServer

This will run a (you guessed it!) simple HTTP server based right out of that directory. Killing the server is as simple as a Ctrl+D. The server will default to port 8000, but you can change that by simply appending a port number:

python -m SimpleHTTPServer 8080

Simple, fast and effective. I love it.

Why I Use VIM as My Editor of Choice for Front End Development

I’ve been using VIM for years, and I just can’t get away from it. While many people like to use Sublime Text 2, and I can’t help but absolutely encourage that, if you’d like to use an editor that can scale with your knowledge, VIM should be your editor of choice.

Easily edit content within tags

As FED’s, we’re constantly editing content within tags. VIM makes this easy with its “tag” text object - t. Here’s a common scenario, you have source code that looks like:

<div>Some content within here</div>.

In VIM, to replace the content within that tag, you merely need to press cit. This will change the inner tag and you’ll be left with this:

<div></div>.

Easily replace HTML attributes

Similar to the above, we deal with content within quotes all the time, often as attributes within our HTML. You may have something that looks like:

<aside class="one-third author box">

In this scenario, just hit ci". Perhaps the neatest part about this trick, if this was the only content on that line, you don’t even need your cursor anywhere near the quote itself! VIM is intelligent enough to simply empty out the content of the quote regardless of its position in the line, and you’ll be left with:

<aside class="">

Jump back and fourth between where you’ve edited

As FEDs, we are constantly jumping back and fourth between places we’ve previously edited. VIM maintains a “jump list” which is easily navigated by Ctr+O (jumping to previous locations) and Ctr+I (forward). This makes our routine of editing many files simultaneously incredibly painless.

More information on jumps

On a mac? In VIM, you’ve got a proper delete key again

Mac keyboards don’t come with a normal “delete” key - we essentially have a backspace key but it’s labelled delete. Sure, you could reach for funcdelete, but that function key is sure out the the way. Instead, hit x!

Move CSS like a master

Often I’ll need to refactor some CSS and move properties between selectors. With VIM, I can move content from various lines to my cursor position with a simple:

:<linenumber>,<linenumber>m.

Common operations like these are made laughably easy with VIM.

Jump to the end or beginning of a line

This is unusually common in my workflow - needing to jump to the end of a line. Perhaps I forgot a semicolon at the end of a CSS property or line of Javascript. To jump to the end of the line, simply hit A and you’re in insert mode at the end of the line. Need to edit at the beginning (not counting tabbing)? Use I.

Edit at the speed of thought

One of the staple concepts of VIM is to prevent needing to reach for your mouse. When I’m in my flow, I never reach for the mouse unless its to interact with a web page I’m working on. Getting good at VIM means your ability to edit and manipulate text nearly approaches how fast you can think of the problem. Because of the concept of text objects, thinking “I want to delete this line” becomes a trivial dd, or deleting a word with daw. As you think about the problem, you more often then not have a easy command to describe to the editor. The ability to get into your flow with VIM is, in my opinion, higher than most other editors.

Easy split windows

Something that completely changed how I developed was learning how to really leverage split windows in VIM. Yes, VIM has split windows, and they’re amazing! Some editors come with this functionality, but it can be cumbersome to use, or difficult to remember to use.

Spits are powerful because we’re often addressing the same item in a number of places. If you’re addressing an element, you’ll often want the HTML file up. If you’re applying styling to it, you’ll want the CSS up, and if you’re applying behaviors, you’ll want the Javascript up as well. Seeing them all at the same time has saved me literally countless headaches in editing. The flow feels very “natural”, not to mention just how awesome your editor will look. Often I’ll have at least 4 splits going at any one time.

A great way to get started is by typing :Vex. This opens a Vertical exploration window. From here you can browse to whatever file you want to, and that file will appear in the split. There’s also the always salacious :Sex command, which will open a horizontal split explorer window.

More information on splits

More information on the file explorer

Your setup, anywhere

Perhaps one of the most compelling features is the ability to have your customized setup very quickly. I keep my VIM configuration in a GitHub repo, meaning regardless of what machine I’m on, I’m about 2 commands away from having my complete setup ready to go.

…even on remote machines

Front end developers will inevitably work on a remote server at some point. Heck, many of us have local linux boxes in a VM replicating our server environments. You’re going to need an editor, and rather than either fumble around in VIM due to not knowing how to actually make it dance, or using a basic and underpowered editor like nano, getting good at VIM client-side means you’re going to be a master server-side.

Final thoughts

VIM is an amazing editor, and although you may think it’s old, it’s actually more than up to the task for today’s editing. No matter what new editor hits the market, I may try them out to see what innovations are out there, but in the end, I always come back to VIM for all my editing, and I love it.

Sending JSON as Your AJAX Request Data With jQuery

Just a little tip if you’re looking to send JSON to the server as your request using jQuery:

1
2
3
4
5
6
7
8
$.ajax({
  url: '',
  contentType: 'application/json',
  processData: false,
  data: JSON.stringify({
      // Your data here
  })
});

There are three key elements in here:

  • contentType must be sent as application/json. This informs the server what kind of data it should be prepared to receive, and helps it understand it’s not going to receive the standard key/value pair.
  • processData must be set to false, otherwise jQuery will attempt to automatically set your object to a key/value representation
  • Your data must be safely escaped using JSON.stringify, otherwise there’s a very real chance a number of problems will occur.

Special note: if you’re planning to always do this (not a terrible idea if you’re already doing it once), it may be prudent to simply establish the contentType and processData values listed here as defaults using $.ajaxSetup() rather than declaring it for each $.ajax request.

On Underscores, Hyphens and Camel Case in CSS and Javascript

The debate whether to use hyphens, underscores or camel case is a constantly recurring one. I know I’ve personally mixed up what I use on the same project, and often code can become riddled in an unholy mess of the three. I’ve seen arguments that ID’s should be camelCase and classes underscore, or ID’s should be capitalized and a classes lower case, and I’ve never heard any compelling argument for why these rules should exist. Even worse, they’re not self revealing.

However, I think I’ve stumbled upon the answer. At least for myself. And it’s pretty simple, too:

Match the language.

So what does this mean? Let’s take a look at CSS. We have selectors like background-image, border-radius, and z-index. Thus, I match the language and use hyphenation when I’m making CSS selectors. There’s a certain elegance to this, and probably one of the better points: it’s no longer personal preference, and you don’t have to form a committee to discuss what convention you’re going to use for a new language.

Let’s take a look at Javascript. We work with functions like toUpperCase(), indexOf(), and getDate(). Thus, when I work with Javascript, I’ll write in camel case. Interestingly enough, the DOM also uses camel case for style properties, making a even stronger case for camel case within your Javascript.

There’s a minor side benefit with CSS as well to use hyphens. I wouldn’t go so far as to suggest that this would be a hint we were “meant” to use hyphens in our class names, but within the specification there’s this little tidbit:

E[lang|=”en”] Matches any E element whose “lang” attribute has a hyphen-separated list of values beginning (from the left) with “en”.

This is very specific to hyphenation within your CSS, and there isn’t a means to do the same thing using underscores or camel case. Granted, a selector using this might perform quite poorly, but I believe there’s a hint here we can recognize.

Debugging Javascript

Javascript has an incredibly powerful suite of debugging tools available, but you won’t find them in an IDE. Rather, Javascript’s debugging tools exist where your code is (typically) run - right in the browser.

With the increase of Javascript’s prominence in today’s web application oriented architecture, browser vendors have been quick to respond with robust debugging tools. The earliest incarnation of this was Firebug for Firefox. Since then, browsers like Safari and Chrome added their own tools, and they have become increasingly more powerful. Even Microsoft added Developer Tools with IE9 (although it does tend to lack more of the advanced features included with other browsers).

Open your Inspector

I’m going to call everything, from here on out, the inspector. Each browser has a different name, in Chrome its called the Web Inspector, Safari calls it the “Safari Developer Tools”, Firefox has Firebug, and even Internet Explorer has a kind of “Developer Tools”. The majority of these techniques, as one would expect, are found on Chrome, Safari and Firefox, but Internet Explorer 9 at the moment has only just started to catch up after being dormant on the inspector front for, well, forever.

The inspector is usually opened by right-clicking on a “blank” area of the screen and selecting Inspect Element or something along those lines based on your browser. In IE, press F12.

Chrome

Firefox

Safari

Internet Explorer

Using the console

One of the most fundamental tools to debug your Javascript is through the console. The console is the hammer to the inspector’s toolkit.

The console is essentially an environment to run your Javascript. While your first experience with it may be basic, you’ll soon find it is absolutely invaluable. With it, and depending where you are in the code, you can view the values of elements as your code is being run, make changes, and most importantly, test sample code.

If you get only a single takeaway throughout this entire article, let this discussion on the console be it. You can run any and all Javascript through the console; it is the foundation to Javascript debugging.

Let’s take a look at something we can do in console right here on this site. This site uses jQuery, so I’m going to run a through commands and we can see the results:

I’ve run some basic commands to demonstrate what the console is about: running Javascript. Anything you would put into your Javascript file you can put into the console, even multi-line items (use option/alt + enter to make a new line). It’s excellent for testing selectors, normal Javascript, or even trigging events. For example, let’s pretend you had a custom event listern on your document, if you simply wanted to fire it, you could enter $(document).trigger('customevent') within the console.

Using debugger

While the console offers some powerful tools, creating breakpoints through the use of the debugger statement actually turns your browser into a powerful IDE for Javascript debugging. Let’s take a look into how that works and how to leverage the (many) available features. We’ll start by making a basic HTML page which will include our Javascript.

index.html
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
  <title>Debugging Javascript</title>
  <script src="scripts.js"></script>
</head>

<body>

</body>
</html>
scripts.js
1
2
3
4
var foo = 'a';
debugger;
foo = 'b';
debugger;

Open index.html in your browser. Initially, you should notice if you don’t have your web inspector open that nothing happened. Most inspectors will ignore things like debugger statments unless the inspector is open. However, if you open your inspector and hit Refresh on your browser, you likely will get something which appears like this:

Let’s take a look at our surroundings.

The browser is telling us the execution is paused. The page has stopped “working” until we tell it to continue on. Under the Sources panel we can see which line of code we’ve paused on, which, when using debugger, is always on the debugger line itself. While this alone is partially interesting, there’s a lot more power to extract here. We want to use the console and play around. While you could switch to the console tab itself, wouldn’t it be better to have the console right here? Press Esc to get the console to appear.

Now we’re cooking with fire! With the console we can do anything to the current state. We could rewrite foo, delete it, create a new variable, inspect other variables, etc. For now, let’s take a look at the value of foo.

Viewing the value of variables mid-way through execution is an incredibly powerful for debugging. As mentioned earlier, we can anything we normally could in Javascript here. Let’s change foo’s value for fun and profit:

Here we set foo to c. Not exactly mind blowing, but we’re just getting our feet wet. But what if we’re done fooling around and want the rest of the code to execute? For that, we’ll want to take a look at the debugging tools.

  1. Resume script execution Resumes your script if it has been paused due to a debugger statement or breakpoint.
  2. Step over next function call Steps to the next line of code, attempting to remain in the same current scope if possible.
  3. Step into next function call Dive into the next function we encounter. Where as the previous button will attempt to remain in the same scope, this function will bring us into the next function we encounter.
  4. Step out of the current function If you’re inspecting a function you’re not concerned about, this will escape you out to its parent scope.
  5. Deactivate all breakpoints Removes all breakpoints, though not debugger statements. Especially useful once you’re finished debugging and want to get on with your life.

In this case, let’s hit Resume script execution to move on. Because we have two debugger statements in our code, we expect to get halted again on the second statement.

This time around we see that our foo = 'b' code has been executed, and if we inspect foo we see it is currently set to b.

You can either press the Resume Script Execution button or close the web inspector to have the page finish out.

Breakpoints

Similar to the debugger statement, the inspector supports breakpoints. Breakpoints have a few advantages:

  1. They do not pollute your code with dangerous debugger statements which could accidentially be committed.
  2. They support conditional breaking.
  3. They allow you to debug code that perhaps isn’t even yours to edit.

However, breakpoints have one minor disadvantage: you need to find the line to break on using the Source panel, which can sometimes be inconvenient and counterintuitive, especially if you’re already editing the code in question with your editor.

There is no right or wrong way in this case, they’re two sides of the same coin. It’s best to understand both methods.

The setup

Let’s edit our scripts.js file to make it look like this:

scripts.js
1
2
3
4
5
6
7
8
var
  i,
  length,
  names = ['Bill', 'Frank', 'James', 'John'];

for(i = 0, length = names.length; i <= length; i++) {
  console.log(names[i]);
}

With your inspector open, open index.html again and let’s take a look at the console.

This looks fantastic, but we’re getting that nasty undefined output. Why is that? Well, let’s start by putting in a breakpoint.

Creating a breakpoint

Under the Sources tab, click the line number where we want to create a breakpoint (breakpoints are essentially identical to debugger statements). You should see something identical to the image below:

Refresh the page and let’s see what happens.

We can see that our execution has paused on our breakpoint. We can play around in the console as well (remember to bring it up when you’re under the Sources tab by pressing Esc on your keyboard). If you test our i value we can see it is currently o, and names[i] is properly set to Bill.

We can continue the script by pressing the Pause script execution button, which will be triggered each iteration throughout the loop. You’ll notice that the script outputs John, then goes on one more time. There’s our problem!

Conditional Breakpoints

However, if we knew the problem was with the value being undefined, wouldn’t it have been better to only break when names[i] was undefined? It would have sure saved us a lot of clicking, and imagine if this was a much larger array!

Create a conditional breakpoint by right-clicking the breakpoint and selecting Edit Breakpoint…. You will be presented with this dialog:

Here we can enter in whatever condition that needs to evaluate to true for this breakpoint to be fired, and here we have the single biggest advantage breakpoints have over debugger statments.

Enter your condition like so and press Enter:

A conditional breakpoint appears as an orange flag:

Note: I sometimes find the browser can be extremely flakey in accepting the statement. If you are finding the orange flag denoting the breaking is a conditional breakpoint is not appearing, try to remove the breakpoint entirely and recreate it. Don’t click “outside” the dialog box to confirm - that never seems to work. Always press enter.

Refresh the page again and let’s see what happens.

The script has run, and we can see in the console the breakpoint has been skipped for all counts with the exception of when our statement returned true, when our names[i] was undefined. That’s a lot cleaner and easier to debug!

Examining the interface

Of course the main script area and console are not the only visible items on the Sources tab. There’s also the area off to the right which contains some extremely powerful tools.

I guarantee if you’re not using these at the moment, they’re about to fundamentally alter the techniques you will use to debug.

Watch Expressions

Create a watch expression when you find yourself debugging and constantly wanting to know the value of a variable. Using the same code above, you could add a names[i] watch expression and, by setting a normal breakpoint on the console log, watch each value as it ticks by (useful if you were not already logging the value to the console.)

Adding the expression:

Refresh the page with the breakpoint set to easily see the content of the variable:

TL;DR Use watch expressions when you find yourself investigating the same variable over and over again while debugging.

Call Stack

The call stack will be very familiar to anyone who has worked in compiled languages equipped with IDEs. The call stack is essentially the functions or methods the browser has executed to get to the current line of code.

The call stack answers the question of, “How did this line of code get executed?” Even better, you can hop back through to the parent function(s) and view their current state(s) as well.

Let’s set up an example:

scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var
  i,
  length,
  names = ['Peter', 'Bruce', 'Tony', 'Clark', 'Hal'],
  lastNames = ['Parker', 'Kent', 'Stark', 'Wayne', 'Jordan'];

function concatenateName(firstName, lastName) {
  return firstName + ' ' + lastName;
}

function processNames() {
  for(i = 0, length = names.length; i < length; i++) {
      var random = Math.floor(Math.random() * lastNames.length);
      var name = concatenateName(names[i], lastNames[random]);
      console.log(name);
  }
}

processNames();

This script will output first names with random last names to our console. Nothing special, but it gives us a tiny example to play with.

Let’s start by putting a breakpoint on line 8.

Refresh the page and look at the call stack item to the right.

What we have here is a list of functions we had to run through to get to this item, the top most being the most recently run function. In this case, we find ourselves in the function concatenateName from line 8 of scripts.js, which was called by processNames from scripts.js line 14, which itself was called by an anonymous function (in this case, nothing) in scripts.js on line 19.

First, this gives us an immediate understanding of the order of execution and what happened to get us to where we are. This alone is invaluable, but there’s more.

If you actually click on one of the other stacks, in this case processNames there in the Call Stack window, your scope will be brought to that point in time. You can actually inspect and view which variables are currently set.

This tool can be immensely powerful for debugging complicated Javascript applications and is fundamental in compiled languages. One additional nice benefit is by traversing the various items within the call stack, is the scope variable window will be automatically updated.

Scope Variables

The scope variable window shows exactly what variables exist within the current scope. While it doesn’t add any additional functionality, it can be nice to simply glance over at the scope variable window to quickly view the value of a variable.

Using the previous example with execution being paused at line 8, we can quickly see the firstName is set to Peter and lastName is being set to Jordan.

DOM Breakpoints

DOM breakpoints are a powerful tool if you’re not sure what piece of code is modifying an element. Let’s set up an example:

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
  <title>Debugging Javascript</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="scripts.js"></script>
</head>

<body>

  <div class="content">
      <p>Loading...</p>
  </div>
  <button name="toggle">Load Content</button>

</body>
</html>
scripts.js
1
2
3
4
5
$(document).ready(function() {
  $("[name=toggle]").on("click", function() {
      $(".content").html('<p>Finished loading</p>');
  });
});

Next, we’ll create our DOM breakpoint. To do this, find the container element which encapsulates the element(s) you’d like to monitor for changes. In our example, since our code is going to remove the <p>Loading...</p> item, we’ll want to assign the DOM breakpoint to the .content element by specifying we want to break on Subtree Modifications:

Next, click on the Load Content button, and let’s see what happens:

Script execution has been paused and the browser will display the Sources tab. The most interesting thing to us, at this point, is the call stack. We can see from the call stack there are a number of jQuery functions which are being run to begin DOM modification. But what line of ours actually triggered the change?

Looking at the call stack, we can see there is a reference to scripts.js on line 3. Click on that.

Here’s the line that we wrote which is triggering the call to modify that DOM element! This can be a highly useful tool if you’re unsure what line of code is making modifications to your DOM.

Conclusion

With these tools in your toolbelt, your Javascript debugging experience should be significantly easier and more enjoyable. Personally, I love sniping out issues in code and addressing issues knowing exactly what is going on without the need for modifying the existing code, and I hope now you will too!

Good (bug) hunting!