Don’t Write Magic, Hard-to-Understand Code
Take a look at this:
var string = '42';
var foo = +string;
Do you know what that second line does? Do you know what foo
will contain when this code is run? Chances are you don’t, even if you’re a seasoned JavaScript developer.
This is an example of what many refer to as “a neat hack” or “a bit of magic.” I, on the other hand, refer to this as “hard to read and understand.”
That second line above takes advantage of how the +
operator works in JavaScript to cast the content of the string
variable to a number. Thus, foo
now contains the number 42
instead of the string '42'
.
Still find that code hard to understand even after I explained it? I don’t blame you.
Compare the code above to the following:
var string = '42';
var foo = Number(string);
This code does the exact same thing, but it omits confusion and embraces clarity. It doesn’t depend on the reader having obscure knowledge of the esoteric behaviors of JavaScript. It’s readable and understandable.
Here’s another example:
var string = 'hello';
var foo = !!string;
What? What’s foo
now?
This code casts the value of the string
variable as a boolean and sets foo
to true
. I’ve been using JavaScript for years and years, but if I came across this code I’d have no idea what it did without looking it up. This technique might be a fun intellectual curiosity, but it should never be used in practice.
Examine this alternative:
var string = 'hello';
var foo = string ? true : false;
This reads almost like a sentence. If string
is truthy, set foo
to true
, otherwise set foo
to false
. Easy to read, easy to understand; the hallmark of great code.
It can be tempting to show off a neat trick you just learned, or show how deep your knowledge of a programming language goes. Doing that, however, is just going to come back to haunt you. Future You is unlikely to remember this stuff unless you use it constantly, and the vast majority of other developers won’t appreciate it. Most will see an annoying hurdle standing between them and understanding the code, not a nifty trick that will save them a few keystrokes.
Avoid temptation. Write code that’s easy to read and easy to understand.