Javascript Linters

What’s a ‘linter’?

In 1979, at Bell Labs, Stephen C. Johnson wrote a source code analysis tool for the C langauge called lint. It looked through the source files and flagged suspicious looking bits of code that were likely to be errors. Supposedly named lint because these bits of code were much like the unwanted bits of fluff you might find on your sweater. Nowadays the terms ‘lint’ and ‘linter’ are generic terms for programs that run this sort of analysis on source code.

Why Use a Linter?

There are lots of benefits to checking your code with a linter.

Spot subtle coding issues.

Linters will alert you to weird code and hard-to-spot mistakes that won’t necessarily cause your program to crash, but can be a sign of subtle errors in your problem logic.

If you create a variable and then never use it, a linter will warn you. If you try to declare the same variable name twice in the same scope, a linter will warn you. Here’s a more detailed example. If you have the following code:

function testNumber(n) {
    if (n == 0)
    console.log("number is zero");
}
testNumber();

A linter will warn you:

line 2, col 11, Use '===' to compare with '0'.

In this case, it looks like you’re trying to compare a value to see if it’s 0. And when you use == to compare here, your comparison will also return true for other falsy values like "" or undefined, which may not be what you intended. So, the linter recommends you always use === to check if values equal 0. Catching things like this early can prevent hard-to-find bugs later.

Spot obvious syntax errors.

Linters will also catch a lot of obvious syntax errors for you before you even try to run your code. This too will save you time debugging.

Enforce common coding conventions within a team.

If your project has a linter configuration included with its source, it can help keep all your developers or contributors on the same page as far as coding style. When all the code in your codebase plays by the same rules it’s much easier to read and more straightforward to work with.

JSLint

JSLint is a tool written by Douglas Crockford. You can try it online at jslint.com. It scans through your Javascript and will print out a list of dangerous code and style problems it finds with your code.

For example:

'use strict';
function helloWorld (greeting) {
    var hi = "Hello world!";
    console.log(hi)
}
helloWorld();

will result in:

line 2 column 20, Unexpected space between 'helloWorld' and '('.
`function helloWorld (greeting) {`

line 2 column 21, Unused 'greeting'.
`function helloWorld (greeting) {`

line 4 column 19, Expected ';' and instead saw '}'.
 `console.log(hi)`

Douglas Crockford is author of Javascript: the Good Parts, has given some great talks on Javascript, and in general spends a lot of time thinking, writing, and talking about Javascript. He has very strong opinions on what good Javascript code should look like, and as a result so does JSLint. The official instructions include the warning “JSLint will hurt your feelings.” Some of the warnings it gives can be difficult to understand, especially when you are just beginning. Sometimes these rules can seem dogmatic, difficult to adhere to, and arbitrary. Arbitrary they are not. Crockford has thought very carefully on these issues and often explains his reasoning in blog posts and lectures. Even when you don’t agree, it’s always interesting and informative to learn the reasoning behind Crockford’s decisions with JSLint.

JSHint

As knowledgable as he may be, there’s still plenty of room for legitimate disagreement with Crockford. JSHint is a fork of JSLint by Anton Kovalyov. One of the problems many people have with JSLint is that there are very few configuration options for rules you disagree with. JSHint was designed with flags and config options for nearly every rule. It also has more lenient defaults than JSLint. You can set it up to help you enforce your own team’s specific coding conventions. Great for when you have your own strong opinions on what Javascript should look like, or when you think Crockford’s opinions are too strong and would prefer a more community concensus based approach.

ESLint

Another notable Javascript linter is ESLint, created by Nicholas C. Zakas. The main advantage of ESLint is that not only are are rules configurable, but you can actually write your own custom linting rules as plugins. And the default bundled rules are written in the same format as any other plugin. Great when you have very specific needs for enforcing your team’s code style.

SublimeLinter

Pasting your code into a website is fine for one-off code checks, but what if you want to do it more often? What if you want to keep track of how your code looks all the time?

SublimeLinter is a Sublime Text 3 plugin that can run a wide variety of linters including JSLint, JSHint, or ESLint on your code and display the results instantly in your editor.

You should really read the docs and configure your linter to meet your specific needs but these basic steps should get you started.

  1. Install SublimeLinter.
  2. Install your preferred javascript linter plugin. (There are also lots of plugins available for different langauges.)

Lint Tips

  • Remember, linter warnings are suggestions, not laws. If you know what you’re doing feel free to ignore or disable them. But at least try to understand why the linter rule exists.
  • A lot of the errors can be hard to understand. JSLint Error Explanations is a great site which explains what many common errors mean for JSLint, JSHint, and ESLint.
  • If you choose JSLint as your linter, first of all you’re very brave. Secondly, you can often find reasoning for its suggestions (and many heated debates) by typing, Crockford [linter-warning-youre-dealing-with] into Google.

Have fun picking those bits of unwanted fluff out of your programs!

Dragon Tax Return Simulator 2015 Post-Jam Update

So I’ve been hard at work polishing the game and adding some things I wanted to add that I didn’t have time to add before.

You might not know if you only played it once, but all the paperwork in the game is randomly generated. Right down to the specifics of the tax rules in the instructions. I wasn’t really happy with how some of the notes looked but I had to release. And now I’ve finally spent some time working on nice letterheads.

Here are what complaint notes from nobles and shopkeepers looked like in the jam version.

Old Noble Complaint Notes Old Shopkeeper Complaint Notes

Here’s what they look like in the update.

New Noble Complaint Notes New Shopkeeper Complaint Notes

I think it’s a big improvement. Also, the shops all have cool generated names now.

Other improvements:

  • Bugs fixed.
  • Typos untypoed.
  • Added a load screen to preload all the webfonts I use.
  • More sentences for the letter generators to choose from.
  • Other text and UI polishing.

But the coolest new thing is Print and Play Mode! You can print out the game and play on your own desk or table! Print right from the browser.

Print and Play

How to print and play

  1. Open the game.
  2. (optional) In your browser, go to your print settings and turn off headers and footers.
  3. (optional) Do a print preview to make sure everything looks good. Should be around 20 pages.
  4. From your browser menu, select print. Or try Ctrl+P or Command+P.
  5. Wait for all the paper to come out.
  6. Put aside the Answer Checker Table to remove temptation.
  7. With scissors, cut out the appraisal reports and small complaint notes.
  8. (optional) Set a timer.
  9. Lay out all the papers and fill out the D-1045 form as usual. This is the game!
  10. When you’re done, use the Answer Checker Table to check your answers and see how you did!

Other ways to play

  • Try to finish the form together with a friend.
  • Print multiple copies and race against a friend or friends.
  • Make up your own rules, there’s no wrong way to play!

Print and Play

Play Now!

(Originally posted here)

Dragon Tax Return Simulator 2015 - Post Mortem

Dragon Tax Return Simulator 2015 is my first Ludum Dare entry. Once the theme was announced I brainstormed a list of about a dozen ideas, and then narrowed them down based on whether they were 1. doable, 2. interesting. Somehow this dragon tax game idea came out on top. While I was originally trying for a compo entry, when I realized I wasn’t finishing on day 2, I adjusted trajectory toward the jam.

Tools

Javascript - This is a mostly from scratch (libraries used below) HTML5 game. So if it looks bad or doesn’t work for you then I probably didn’t test in your browser/os.

Google Fonts - A great resource and allowed me to take full advantage of the “Fonts are allowed.” exception. I doubt I’d have even tried this idea if I didn’t know about Google Fonts.

Handlebars.js - I’d never used it before but it was great for making templates for all the various forms that got created.

jQuery - jQueryUI made it super simple to make all the paper draggable.

The Good

I feel like I really got a lot of value out of simple randomization.

The instructions use random values for most of the ‘rules’ so you can’t just learn the tax code.

The random name generator was really fun to make even though all it does is stick some random syllables together (about half the time it just picks a ‘normal’ firstname from a list). I decided this was not the time to try and figure out markov chains or anything fancy like that. I think this simple randomizer still came out fine.

Names

I’m also happy with how well the random note generation worked out with its simple templates.

For example here’s the farmer complaint template (with the HTML stripped out):


Hey {{dragonEpithet}}!

{{exasperatedComplaint}}
You burnt up {{value}} gold worth of my crops!
{{farmerAppeal}}
{{peasantNotice}}
{{partingShot}}

{{randomName}}, {{location}}

P.S. {{grovelling}}

And the results:

farmer complaint note

It was fun to write all the sentences that filled these templates, but I still want to add more since the notes can still get repetitive.

The Bad

Originally, the ‘time limit’ in the game was only going to be 5 minutes. On the second day I actually tried a test run. One thing I noticed was that 5 minutes was nowhere near enough time. I used that discovery as an opportunity to cut extra forms, simplify the main form, and increase the time limit to 10 minutes. I probably could have saved myself a lot of time if I’d tried playing the game earlier.

Also, I probably shouldn’t have waited until the third day to add all the logic that makes it “a game”. I mean stuff like the dialogs, finish state, endgame report, etc. I was kind of pushing my luck as I rushed to get those all in before the deadline.

Ideas That Didn’t Make It

I wanted to add more graphics. Just things like little official seals/stamps for some of the paperwork. Burnt edges on the papers. A little pixel art dragon claw cursor.

And I wanted some of the complaints from shopkeepers to be on shop letterheads with randomized shop names but I was running out of time and ended up just reusing the design from the peasant notes.

(Originally posted here)

Slicing and Splicing: Ruby and Javascript Gotchas

Ruby and Javascript both have a method called slice. They looks similar but they work differently. Let’s look at some examples.

Guess what the following Ruby code returns.

[1,2,3,4,5].slice(0,2)

And it returns…

[1,2]

It’s a new array containing the first 2 values of the calling array starting from index 0.

What about this Javascript?

[1,2,3,4,5].slice(0,2);

[1,2]

Javascript returns an array with the values starting from index 0 up to, but not including index 2.

I know. It looks the same. But don’t fall for it. Here’s another example that actually shows this difference.

Ruby

[1,2,3,4,5].slice(2,3)

[3, 4, 5]

Javascript

[1,2,3,4,5].slice(2,3);

[3]

In Ruby the method is slice(start, length) where start is the starting index, length is the number of values to take up to.

In Javascript the method is slice(begin, end) where begin is, again, the starting index, but end is the index to take up to, non-inclusive.

slice also has a single argument format

Ruby

[1,2,3,4,5].slice(2)

3

Javascript

[1,2,3,4,5].slice(2);

[3, 4, 5]

Here, Ruby’s slice(index) simply returns the value at index.

And Javascript’s slice(begin) returns a new array starting from the value at the index begin all the way through to end of the array.

Ruby and Javascript both also have String.slice that work the same as their respective array-based counterparts, but on characters in the string.

Ruby

"hello".slice(2)
"hello".slice(2,3)
"l"
"llo"

Javascript

"hello".slice(2);
"hello".slice(2,3);
"llo"
"l"

Javascript also has a splice method. It’s just like slice but it removes the selected values from the original array. It’s like Ruby’s slice! method.

Ruby

arr = [1,2,3,4,5]
arr.slice!(1,1)     # returns  [2]
arr                 # contains [1,3,4,5]

Javascript

arr = [1,2,3,4,5];
arr.splice(1,1);     // returns  [2]
arr;                 // contains [1,3,4,5]

Okay last example.

Ruby

str = "hello"
str.slice!(1,1)     # returns  "e"
str                 # contains "hllo"

Javascript

str = "hello";
str.splice(1,1);

TypeError: str.splice is not a function

Whoops! There’s no built-in String.splice method in Javascript. Arrays only!

If you have to switch between Ruby and Javascript a lot, be careful out there and always keep your methods straight.

And there are more differences than what I mentioned here. Ruby’s slice methods can take a range value as a parameter. Javascripts splice can be used to insert values. And more! Check out the docs for details.

References