Reading An Open Letter to JavaScript Leaders Regarding Semicolons where Isaac Z. Schlueter explains his unorthodox coding style a line of code struck me.
if (!cb_ && typeof conf === "function") cb_ = conf , conf = {} |
He was able to execute more than one statement in a if
without the need of { }
. I have recently been working on python scripts for http://db.mmo-champion.com/ and this discovery made me want to imitate pythonic indentation in Javascript.
The comma trick
You can use the ,
separator to chain statement. This group them into only one block of code. Therefore you can execute all of them without the need of { }
. The rule is easy: put a ,
at the end of every line but a ;
on the last line of the block.
if (test) first_action(), // Note the important ',' second_action(); // Note the lack of ',' third_action(); |
For example, it is possible to write a little program that outputs the Fibonacci Numbers without the use of any { }
and therefore imitate python indentation style with no ending }
.
var curr = 0, next = 1, tmp; for (var i = 0; i < 10; ++i) tmp = curr + next, curr = next, next = tmp, console.log('Fibo', i, '=', curr); // ... // Fibo 5 = 8 // Fibo 6 = 13 // Fibo 7 = 21 // Fibo 8 = 34 // ... |
The issues
Sadly, the use of this is trick is extremely limited. You cannot use any of these keywords inside the "blocks": if
, for
, var
.
for (var i = 0; i < 3; ++i) k = i * 10 + 1, if (k % 2 == 0) console.log(i); // SyntaxError: Unexpected token if for (var i = 0; i < 3; ++i) var k = 10, console.log(k); // Firefox: SyntaxError: missing ; before statement // Chrome: SyntaxError: Unexpected token . |
Beginning with comma
If you don't fall into the use cases of these issues and you are a bit worried about the bugs resulting in the mix of the ,
and ;
, you can start your lines with commas.
var k; for (var i = 0; i < 10; ++i) , k = i * 10 , console.log(i) // SyntaxError: Unexpected token , |
But we need to add some empty statement before the first ,
so that it compiles. In python :
is used but it doesn't parse in Javascript. We can use $
for example, it is a valid statement: it reads the variable and does nothing with it.
var $; for (var i = 0; i < 10; ++i)$ // Use of $ instead of : in python , k = i * 10 , console.log(k) // 0 // 10 // ... |
Debugging purpose
The main use of this trick I can see is for debugging purpose. If there is code executed in a test without { }
and you want to log something when the program goes into this part of the code. Before you had to add { }
and then remove them which is really annoying. Now it's easier!
for (test) doSomething(); |
// Before for (test) { val = doSomething(); console.log('Executed!', val); } // After for (test) val = doSomething(), console.log('Executed!', val); |
Conclusion
Using the comma trick to do { }
-less indentation is far from viable. However this may still be useful for debugging and overall it is fun to try new coding styles!