JavaScript First

Posted 2014-11-06 07:15 PM GMT

About 3 years ago I was interviewing at various companies for web development jobs. I kind of like interviews. You get to work on bite-sized problems that can usually be solved in an hour or less. There is almost always a "right" answer, no matter what the interviewer says. You just have to figure out how they want you to answer (I like standardized tests for the same reason, but that's another, even more boring story).

My intention today is not to write about interviews, though. I want to write about one interview question that I got "right", and how wrong I really was. The questions was:

When starting a new project or page, what do you build first? HTML, CSS, or JavaScript?
The "correct" answer was HTML, because HTML gives the page a structure upon which you can build the visual appearance (CSS) and interaction (JavaScript). I think this answer was valid when JavaScript was used primarily to add whiz bang to a static web page. But, we have moved on from those days, and JavaScript has grown up. Today when you are starting a new project, build JavaScript first.

The Console Test

At the most recent LinkedIn Hackday, I worked with a few other developers and a designer to build a JavaScript version of Minesweeper. Due to the time constraints of hackday, we all needed to be writing code as quickly as possible. We identified the different modules of a Minesweeper game, and we all started working. Because there wasn't a pre-built UI, the JavaScript in our modules had to be written without any DOM interaction. When all of these modules were complete, we had a complete working version of Minesweeper without a UI. You could, in theory, play an entire game directly from the JavaScript console. With all of that in place, building and updating the UI was a piece of cake.

The idea of playing a game of minesweeper from the JavaScript console got me thinking about a concept that I call "The Console Test". Everything that your Web Application does, you should be able to do it in the console. If your application is a todo app, you should be able to create new todo items and makr items complete from the console. If your app is an email client, you should be able to send, flag, archive, and delete messages from the console.

The UI Layer

If your JavaScript passes the Console Test, building the UI layer will be relatively simple. Event listeners just call the methods that you have already been using in the console. The DOM is just a reflection of the JavaScript. Because the UI is independent of the application logic, changes to one do not affect the other.

The idea of keeping UI and application logic separate is not new (whether you call it MVC, MVVM, or something else). However, the Console Test provides an interesting measure of how independent the application logic really is.