Brendan Eich’s dream for the next version of JavaScript

[2011-01-19] esnext, dev, javascript
(Ad, please don’t block)
Harmony is the code name of the next version of JavaScript that is currently being worked on. Brendan Eich (the creator of JavaScript) outlines what his ideal Harmony would look like.

Highlights:

  • let as block-scoped var. A variable declaration with var is always handled as if it had been made at the beginning of a function, even if it is inside a for loop or an if statement. That will change with let and remove a frequent source of errors.
  • const for constant variable declarations
  • Compact function syntax: function(x) { return x * x } becomes #(x) { x * x } (including an implicit return)
  • arguments is replaced by rest parameters and default arguments (see below).
  • Records: read-only objects (no Object.freeze()). #{x: 10, y: 20}
  • Tuples: read-only arrays with slicing and negative indices that access elements at the end. #[1, 2, 3][-1] → 3
  • Paren-free syntax for if.
  • Modules: The simple modules proposal will probably make it into Harmony.
  • Iteration: Lots of cool stuff, inspired by Python.
        for k in keys(o) { append(o[k]) }
        for v in values(o) { append(v) }
        for [k,v] in items(o) { append(k, v) }
        for x in o { append(x) }
        #sqgen(n) { for i in range(n) yield i*i } // a function
        return [i * i for i in range(n)]
        return (i * i for i in range(n))
    
  • Rest parameters: function printf(format, ...args) { ... }
  • Default parameter values: function add(left, right=1) {...}
  • Spread: the opposite of rest parameters. f(...myArray)
  • Destructuring assignments for arrays and objects. The latter takes some getting used to, the variables one assigns to must have the same names as the object keys.
        let [first, second] = sequence
        const {name, address, ...misc} = person		
    
My own wishes:
  • Self-style full prototypal inheritance (not much different from how JS is now).
  • Handle this like Lua: obj.method(a,b) should be syntactic sugar for m(obj, a, b) (where m is the function stored in obj.method).
  • Python-style keyword arguments (but I do agree with a comment made by Eich that destructuring makes them less urgent).
  • Turn “class methods” such as Object.keys() into instance methods: Instead of Object.keys(foo), I’d like to use foo.keys().
  • if statement: I would make braces mandatory and introduce an elsif keyword (could also be named else if)
  • Implicit returns: It would be nice if the same could be done for if-then-else (i.e., it becomes an expression). No more ternary if operator!
  • I’ve critiqued CoffeeScript’s syntax and compared it to JS without parens.
Updates: