While coming across the release notes of Javascript 1.7 & 1.8, I noticed Javascript has gained some really Pythonesque features. I'm not saying these features originated from Python, it just happens to be the language I'm most familiar with and the syntax seems strikingly similar to me.

Generators

Like Python, Javascript acquired the yield statement, turning a function into a generator.

function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    var t = i;
    i = j;
    j += t;
  }
}

Javascript's generator object also implements the .next(), .send() methods, as well as using the StopIteration exception to signal the end of the iteration.

Generator Expressions

Along with generators, also came Generator expressions, again sporting similar syntax to it's Python equivalent.

var it = (i + 3 for (i in someArr));

Array Comprehensions

This is Javascript's equivalent of Python's list comprehensions, including conditionals.

var evens = [i for each (i in range(0, 21)) if (i % 2 == 0)];

Destructuring assignment

Also known as Python's sequence unpacking, allowing for multiple assignment and multiple returns.

function swap(a, b) {
  [a, b] = [b, a];
  return [a, b];
}

A more structured kind of unpacking, which isn't possible in Python as far as I know, is also possible.

for each (let {name: n, family: { father: f } } in people) {
  document.write ("Name: " + n + ", Father: " + f + "\n");
}

Expression closures

Similar to Python's Lamba functions.

function(x) x * x

Conclusion

I like Javascript. When you look beyond it's relationship with the browser, you find it's quite a pleasant language to work with. Therefore as a Python guy, I welcome these new features. I think they're great additions to an already wonderful language.

Finally, 2 versions of the same Fibonacci generator function, in which you'll see that Javascript is just Python with braces!

// javascript version
function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    [i, j] = [j, i + j];
  }
}

function takewhile(predicate, iterable) {
  // python's itertools.takewhile, implemented as
  // a Javascript generator

  for (x in iterable) {
    if (predicate(x)) {
      yield x;
    } else {
      break;
    }
  }
}

// fibonacci sequence < 400
f = [i for each(takewhile(function(x) x<400, fib()))];
# python version
def fib():
  i, j = 0, 1
  while True:
    yield i
    i, j = j, i + j

from itertools import takewhile

# fibonacci sequence < 400
f = [i for i in takewhile(lambda x: x<400, fib())]
blog comments powered by Disqus