Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active November 2, 2024 12:22
Show Gist options
  • Save revolunet/537a3448cff850231a74 to your computer and use it in GitHub Desktop.
Save revolunet/537a3448cff850231a74 to your computer and use it in GitHub Desktop.
# Python VS JavaScript ES6 syntax comparison

Python VS ES6 syntax comparison

Python syntax here : 2.7 - online REPL

Javascript ES6 via Babel transpilation - online REPL

Imports

import math
print math.log(42)

from math import log
print log(42)

# not a good practice (pollutes local scope) :
from math import *
print log(42)
import math from 'math';
console.log(math.log(42));

import { log } from 'math';
console.log(log(42));

import * from 'math';
console.log(log(42));

Range

print range(5)
# 0, 1, 2, 3, 4
console.log(Array.from(new Array(5), (x,i) => i));
// 0, 1, 2, 3, 4

Generators

def foo():
    yield 1
    yield 2
    yield 3
function *foo() {
    yield 1;
    yield 2;
    yield 3;
}

Lambdas

lambda a: a * 2
a => a * 2

Destructuring

status, data = getResult()
var [status, data] = getResult();

Spread

search_db(**parameters)
searchDb(...parameters);

Iterators

def fibonacci():
    pre, cur = 0, 1
    while True:
        pre, cur = cur, pre + cur
        yield cur

for x in fibonacci():
    if (x > 1000):
        break
    print x,
var fibonacci = {
  [Symbol.iterator]: function*() {
    var pre = 0, cur = 1;
    for (;;) {
      var temp = pre;
      pre = cur;
      cur += temp;
      yield cur;
    }
  }
}
for (var n of fibonacci) {
  if (n > 1000)
    break;
  console.log(n);
}

Classes

(Python has builtin support for multiple inheritance)

class SpiderMan(Human, SuperHero):
    def __init__(self, age):
        super(SpiderMan, self).__init__(age)
        self.age = age
    def attack(self):
        print 'launch web'
class SpiderMan extends SuperHero {
    constructor(age) {
        super();
        this.age = age;
    }
    attack() {
        console.log('launch web')
    }
}

Comprehensions

names = [c.name for c in customers if c.admin]

(Experimental in Babel)

var names = [for (c of customers) if (c.admin) c.name];

Map

map(lambda: x*2, [1,2,3,4])
[1,2,3,4].map(x => x*2)

length

 len([])
[].length

What's better in Python

  • help(anything) : get docstring for any module/method/function
  • list comprehensions, class magic methods !
  • very powerful OOP
  • huge and coherent standard library, ex : string has 38 useful methods
  • built-in strings and array slicing.

What's better in Javascript

  • Builtin JSON support
  • NPM packaging is a killer-feature : simple and fast, light-years ahead pip+virtualenv.
  • Works in the browser :)
@Hattshire
Copy link

Hi bro, does Python have something equivalent to:

let {
  name,
  age,
} = person

No syntax support yet. You can use some workaround, for example:

from operator import itemgetter
dct = dict(name='sam', age=88)
name, age = itemgetter('name', 'age')(dct)

I feel better using
name, age = (person['name'], person['age'])
as "workaround". Also, the first time I seen that JS syntax I got a lot confused (the thing has got many fields with only 2 extractions), didn't even knew how to search for it lmao

if someday itemgetter gets into builtins then maybe I would start using it, it's a bit more syntactic sugar but the import feels a bit nasty 'cuz it's not like you want to extract a dict like that many times, or at least I don't do it 😁

@vschoener
Copy link

from operator import itemgetter

That's really a killer feature I miss the most in python. Destructuring data is so conveniant and useful.

I'd to add that also working with object is more handy with nodejs (ES6) than python. In Python you have

  • To declare a dict and use quote/double quote to create key value
  • You have to use .get method to access a value.. We can easily access key and value in ES6 object.value.
  • Destructing object missing (of course)
  • Convert json to dict and vice versa take more effort. It's fluent in ES6 and transparent.

Enum is also an overload of no need code. Like if you want to use a value of an enum, you must use the .value of the attribue. in TS we don't need that, just access the Enum.KEY and you have access to the value.

I stop here, there are a lot of stuff I miss a lot from ES6 and a few I like in python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment