Take a look at this:
var string = '42'; var foo = +string;
Do you know what that second line does? Do you know what
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
string variable to a number. Thus,
foo now contains the number
42 instead of the string
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);
Here’s another example:
var string = 'hello'; var foo = !!string;
This code casts the value of the
string variable as a boolean and sets
Examine this alternative:
var string = 'hello'; var foo = string ? true : false;
This reads almost like a sentence. If
string is truthy, set
true, otherwise set
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.