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!

If you liked this article, you might be interested in my Twitter feed as well.
 
  • beatgammit

    This isn't a trick, it's the comma operator. The comma operator ignores the output of all but the last statement in the series.

    For example:

    var a = 5,3; console.log(a)

    Will yield 3. The comma operator is considered very bad style and I've spent hours tracking down a stupid mistake where some code I was debugging used the comma operator instead of splitting it into two lines. Think of something really complicated (tons of parenthesis) and then a comma instead of a semi-colon.

    End result, less readable and error prone, not to mention hard to debug.

    Please people of the internet, don't use this style. It may be hip and cool these days, but it's not worth it. I've had to debug Issac Schlueter's code, and it's annoying to say the least. Leave this kind of micro-optimization (one character in very few cases) to code compactors and obfuscators.

    http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/
    https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comma_Operator

  • Guest

    Reminds me of Erlang 🙂

  • Nobody

    Why are people tempted to do such stupid things?

    You can also punch yourself in the face, but I'm not about to do it just because you can.

  • guest

    Even though using python-like style in JS is possible, that doesn't mean it's a good idea. And this is coming from a web developer whose two main languages are python and javascript. They are different languages and should be treated differently to get the best results with each.

  • http://bsdhosting.co.za/index.html Jay

    Yay, more let's make every language look like shitty python. Why not apply this 'trick' to C/C++ or Perl?

  • Nux

    You should NEVER use local variables without the var keyword! This makes you pollute memory with global variables. You need to remember, that variables without var keyword are global.

    Further more it's not only causing memory/performance issues, but also it might cause bugs almost impossible to debug (e.g. when you change the same variable from other function).

  • Pingback: Neues ist nicht immer gut » Bananas Development Blog()

  • Nux

    BTW. Python indentation serves a purpouse of making programmers always use good style - always use proper identation for more readable code. Comma-style is quite oposite so it's even more evil to compare this with python ;-).

  • http://jaykanakiya.com// Jay Kanakiya

    Thanks for this trick,

    I have used this trick to help integrate grunt-usemin and grunt-remove-logging-statements.

    So the end result is that by just using a single global DEBUG variable you can control enable and disable logging easily.

    Blog post link: http://grunt-tasks.com/grunt-remove-logging-calls/

 

Related Posts

  • September 25, 2011 Javascript Object Difference (5)
    This article is about a difference algorithm. It extracts changes from one version of an object to another. It helps storing a smaller amount of information. Template In a project, I have a template object with all the default settings for a widget. var template = { […]
  • October 12, 2011 Intercept and alter <script> include (2)
    For a project, I want to transparently be able to intercept all the included javascript files, edit the AST and eval it. This way I can manipulate all the code of an application just by inserting a custom script. Hook the <script> tag insertion. Download the Javascript file […]
  • August 19, 2011 Javascript – Stupid Idea: Hoisting at the end (0)
    JSLint imposes us to do manual hoisting of variables. What if we did it but at the end of the function? :P How you write function print_array (array) { var length = array.length; for (var i = 0; i < length; ++i) { var elem = array[i]; console.log(elem); […]
  • August 23, 2011 Javascript – Hook Technique (5)
    Let's go back 5 years ago during the World of Warcraft beta. I was working on Cosmos UI, a projects that aimed to improve the World of Warcraft interface. As interface modification was not officially supported by Blizzard, we went ahead and directly modify the game files written in […]
  • August 29, 2011 Javascript: Improve Cache Performance: Reduce Lookups (2)
    In my Binary Decision Diagram Library, the performance bottleneck was the uniqueness cache. By reducing the number of cache lookup, it is possible to greatly improve the performances. Common pattern In order to test if the key is already in the cache, the usual pattern is to use key […]