A More Readable (Pythonic) Javascript Syntax?

Advertisement:

POWERED by FUSION

While I’ve come to love Javascript, I miss the syntactic beauty of Python. The stark modern minimalism of the language causes the meaning of code to float on the syntax like a feather on water. There are no extra braces, brackets, or parenthesis to saturate your visual bandwidth. In comparison, Javascript’s syntax is like the cluttered boudoir of a Victorian house: elaborate, ornate, and unnecessary. You can be left with half a dozen trailing braces and parenthesis, with no clear owner; their balance in an unstable equilibrium.

Note that I am not arguing that Javascript isn’t a beautiful or powerful language, just that its syntax is a vestigial meme left over from a time when we didn’t know better.

I’ve often wanted to bring Javascript and modern minimalism together: to strip the language of parens, braces, and semicolons. So that’s what I’ve done. I wrote a little parser for a slight modification of Javascript. I call it Pyscript.

Here’s what it looks like:

// Example One
function triangle(a,b):
  function sqroot(x): return Math.pow(x,.5)
  return sqroot( a*a + b*b )
// Example Two
for var i=0; i<5; i++:
  var el = document.getElementById("el"+i)
  if count % 2 == 0:
    el.innerHTML = "Hello"
  else:
    el.innerHTML = "World"


Comparison

When you put normal Javascript and Pyscript side-by-side, you can see the large difference in readability the addition of Python-style syntax makes.

// Pyscript
function triangle(a,b):
  if a > 0 && b > 0:
    function sqroot(x):
      if x > 0:
        return Math.pow(x,.5)
      else:
        return 0
    return sqroot( a*a + b*b )
  else:
    return 0
// Javascript
function triangle(a,b){
  if(a > 0 && b > 0 ){
    function sqroot(x){
      if( x > 0 ){
        return Math.pow(x,.5);
      }
      else {
        return 0;
      }
    }
    return sqroot( a*a + b*b );
  }
  else {
    return 0;
  }
}


Pyscript is just a syntactic beautification of Javascript, where indents have meaning and braces are unnecessary. I’ve even shown it to Brendan Eich and he gave his nod of approval.

How Do I Get It?

Download it here or check out the demo page.

How Do I Use It?

Pyscript runs in all modern browsers. All you have to do is:
(1) Add <script src=”pyscript.js”/> to your <head> tag;
(2) Put your pyscript code in a <script type=”text/pyscript”> tag.

Everything else is taken care of for you. See the demo page for an example of it in action.

Help!

Pyscript is really just a proof of concept. It has a set of unit tests, and as you can see not all functionality is completed yet. Anonymous inline functions do not work, there is no robust handling of indentation, and a number of features (like switch) do not work. But, the whole thing is open source so you can get involved.

What other ways can we make Javascript syntax prettier and more readable?