OMBD#16: JavaScript Developers: You Can’t Predict the Result of These 4 Lines

Or how Static Code Analysis Tools make your life and prevent headaches

Jon Portella
ITNEXT

--

Welcome to issue #16 of One Minute Better Developer, where you become a more successful software developer by reading short nuggets of knowledge, one minute at a time.

⏮️ 🔛 ⏭️

Art by my buddy Loor Nicolas

THE PROBLEM

Take a moment to look at this snippet and try to figure out what it does.

Don’t scroll to the solution yet!

Really try to figure out the result, It’s not as easy as it seems…

What will be logged in line 4?

.

.

.

.

Don’t scroll anymore until you know the solution!

.

.

.

.

.

.

OK, ready?

.

.

.

.

Now, I bet you thought the result was:

'Swapped: 2,1'

WRONG.

This code throws an error. You can try it yourself on your browser’s console:

Uncaught TypeError: Cannot set property '2' of undefined

But, why?

This error happened to one of my students and I was puzzled for a while until I discovered the culprit. The code is missing semicolons. Usually, this is not a problem, since JavaScript’s Automatic Semicolon Insertion takes good care of it.

However, in this case, the code is run as:

How the example program is actually run.

How can we avoid this kind of headache?

A SOLUTION

Use static code analysis tools.

Even if it’s a small script that I’m working on, I always install, at least, eslint. Because:

  1. It will point out this kind of problem and others.
  2. It will solve those problems and format your code automatically on save, as that’s what the configuration on your IDE should do. In the end, that task should be the work of robots, not humans!

So even if it takes a couple of minutes to set up static code analysis tools, it is always a big win. Moreover, the more times you set them up, the faster you can get it done the next time.

--

--

Writer for

Software Engineer @ Pinterest - Teacher, maker, and general things do-er. - https://www.linkedin.com/in/jonportella/ - Toronto, Canada