Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Python VS 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 :)
@sametmax

This comment has been minimized.

Copy link

sametmax commented Jul 22, 2015

Fixing my own comment (strangely I can't edit, I got an error from github):

Python has built-in JSON support :

    import json
    json.loads(data) # import from JSON
    json.dumps(data) # export to JSON

You also a syntax error here:

class SpiderMan(Human, SuperHero):
    def __init__(self, age):
        super(SpiderMan, self).__init__(**kwargs)
        self.age = age
    def attack(self):
        print 'launch web'

It should read:

class SpiderMan(Human, SuperHero):
    def __init__(self, age):
        super(SpiderMan, self).__init__(age)
        self.age = age
    def attack(self):
        print 'launch web'

Also, you use an old Python version (2.7) while the current is 3.4. Granted, the 3.4 is less used, but at least it's production ready while ES6 is not even completely implemented in any browser. In 3.4 case it would read:

class SpiderMan(Human, SuperHero):
    def __init__(self, age):
        super().__init__(age)
        self.age = age
    def attack(self):
        print('launch web')
@revolunet

This comment has been minimized.

Copy link
Owner Author

revolunet commented Aug 3, 2015

typo fixed, thanks :)

Yes ES6 needs a babel transformation to be usable in browsers (but this has some advantages : code validation, optimisations...) and its piece of cake with browserify (which is another JS killer-feature)

@serkanyersen

This comment has been minimized.

Copy link

serkanyersen commented Dec 24, 2015

I feel like SpiderMan should inherit from Human and Spider :) Awesome list btw

@ghost

This comment has been minimized.

Copy link

ghost commented Jan 7, 2016

so you recommend a non-programmer to learn python? I mean easiest,easiest to understand the concepts

@petri

This comment has been minimized.

Copy link

petri commented Feb 15, 2016

Please elaborate; how exactly is NPM packaging better than pip + virtualenv? I have used both and off my head fail to see how NPM packaging is "lightyears" ahead? What I do see is that there are annoyances in both...

@adregan

This comment has been minimized.

Copy link

adregan commented Mar 8, 2016

@petri I think they both have their problems, but NPM installing locally by default, saving the use of a virtualenv, continues to be a welcome feature.

@adrianfalleiro

This comment has been minimized.

Copy link

adrianfalleiro commented Mar 8, 2016

Haven't array comprehensions been dropped out of the ECMAScript spec?

@jedwards1211

This comment has been minimized.

Copy link

jedwards1211 commented Apr 25, 2016

Other things that are better in JS/ES6 with Stage 1:

  • Object destructuring
  • Array concatenation with ... operator
  • Object prop assignment with ... operator
  • Full closures (you can assign to an outer-scope variable)
  • Prototypical inheritance (proves useful at times, for instance decorating an object instance):
const decorated = Object.assign(Object.create(base), {
  newMethod() {
    ...
  }
});
@jedwards1211

This comment has been minimized.

Copy link

jedwards1211 commented Apr 25, 2016

Also a more fair comparison for range would use lodash since it's widely used:

import {range} from 'lodash';
console.log(range(5));
@jedwards1211

This comment has been minimized.

Copy link

jedwards1211 commented Apr 25, 2016

Also possible in ES6:

const fibonacci = function*(max) {
  let pre = 0, cur = 1;
  while (true) {
    let temp = pre;
    pre = cur;
    cur += temp;
    if (cur > max) break;
    yield cur;
  }
};
console.log(...fibonacci(1000));
@dvf

This comment has been minimized.

Copy link

dvf commented Jun 5, 2016

How is npm "lightyears" ahead of pip and virtualenv? Please provide facts if making sweeping statements. Here are some issues I have with npm:

  1. Recursive dependencies literally break the Windows FS which require an extra module to fix.
  2. npm is plagued by gaping security holes, with new ones popping up after almost every major version release.
  3. Unreadable and unfriendly error messages. (ENOENT, etc.)
  4. Complicated and unpredictable release cycles in conjunction with node lead to inconsistencies and problems across different versions and different OS's.

Lastly, virtualenv solves a broader problem than npm does from a local point of view: it supports multiple python interpreters with fresh installations—making it compatible across different systems and versions of Python. This has the added benefit that a testing framework can easily run your code against multiple versions and interpreters which ensures your code runs hands-free on literally any remote instance.

@pixelgrid

This comment has been minimized.

Copy link

pixelgrid commented Jul 14, 2016

on the fibonacci example the es6 way you can use object destructuring to avoid allocating a temp variable

var fibonacci = {
  [Symbol.iterator]: function*() {
    var pre = 0, cur = 1;
    for (;;) {
      [pre, cur] = [cur, pre + cur];
      yield cur;
    }
  }
}
@JonahTurnquist

This comment has been minimized.

Copy link

JonahTurnquist commented Dec 7, 2016

Would be good to add map and reduce to this list.

#Python:
map(lambda: x*2, [1,2,3,4])

//JS
[1,2,3,4].map(x => x*2)

Also len([]) vs [].length.

#Python
len([1,2])

//JS
[1,2].length

And dictionary creation:

#Python
x = 1
y = 1
dictionary = {'x': x, 'y':y}

//JS
let x = 1,
  y = 1;
let obj = {x, y}

IMO JavaScripts wins for these.

@Aprillion

This comment has been minimized.

Copy link

Aprillion commented Mar 15, 2017

good work, but not sure why comparing the ancient Python 2.7 with bleeding edge ES6/7 features..

e.g. async/await in Pyton 3.6 vs ES7 would be nice to compare :) none of the forks seem to be Python 3, so I might make my own fork if you don't plan to update any time this year :)

@revolunet

This comment has been minimized.

Copy link
Owner Author

revolunet commented May 22, 2017

sorry for late reply, i dont have comment notifs anymore...

Btw, updated with some of your comments

About why i prefer to work with npm :

  • incredible package ecosystem (variable quality)
  • built-in scripts management + API
  • git clone xxx; cd xxx;npm i;npm start is all you need to start hacking
  • github integration
  • basically quite painless compared to my experience with virtualenv
@schmaluk

This comment has been minimized.

Copy link

schmaluk commented Jul 7, 2017

yarn ftw ;) Same as npm but dont need to wait so long.
Can you pass in values in Python back into a generator like in ES6?

function* gen() {
   const a = yield 99;
   console.log(a)
}

const generator = gen()
generator.next()
generator.next("special value")

This is essential for redus-sagas, which I prefer rather than Reactive Programming or Promises for all the async stuff.
Also has Python Promises-based or async-wait-like libraries?

@codeocelot

This comment has been minimized.

Copy link

codeocelot commented Aug 24, 2017

Is there a python2.7 equivalent of spread? This seems like a very important functional tool for using with comprehensions.

@AllencxWang

This comment has been minimized.

Copy link

AllencxWang commented Sep 2, 2017

There's 1 argument missing in the lambda expression of the Map part
#Python:
map(lambda: x*2, [1,2,3,4]) # should be lambda x: x*2
//JS
[1,2,3,4].map(x => x*2)

@MaximeCheramy

This comment has been minimized.

Copy link

MaximeCheramy commented Sep 15, 2017

@mlukasch sure, why not?

def gen():
   a = yield 99
   print(a)

generator = gen()
next(generator)
generator.send("special value")

You can also find async-await in Python 3.

@piranna

This comment has been minimized.

Copy link

piranna commented Dec 13, 2017

This should be updated to compare ES6 with Python3, Python2 is close to its end of cycle.

@c6401

This comment has been minimized.

Copy link

c6401 commented Apr 14, 2018

Just randomly found this gist, I like js but the comments are not super factually correct IMHO

Array concatenation with ... operator

[*[1, 2], *[3, 4]]

Object prop assignment with ... operator

{**{'a': 1}, **{'b': 2}}

Full closures (you can assign to an outer-scope variable)

python uses nonlocal statement for safety

Prototypical inheritance (proves useful at times, for instance decorating an object instance):

vars(MyClass()).update({ ... })

but nobody would use that in a language that supports multiple inheritance, also js don't have a native decoration syntax sugar

Also possible in ES6:

not sure what is the feature, if it's yield syntax then python has it since 2001, but now I'm gladly using it in js ~15 years later.

def fibonacci(maximum):
    pre, cur = 0, 1
    while True:
        pre, cur = cur, pre + cur
        if cur > maximum:
            break
        yield cur
[*fibonacci(1000)]

IMO JavaScripts wins for these.

len in python is not a list property it's a protocol __len__ that is supported by practically everything that has length (dicts, orm queries, scientific data-structures).
also don't forget the JS specific quirks

>> a = [1, 2, 3, 4]
Array [ 1, 2, 3, 4 ]
>> a.length = 8
8
>> a
Array [ 1, 2, 3, 4, <4 empty slots> ]

python map also can be used for any iterable object which is most of python data structures, sets, dicts, tuples, not just list, like fibonacci in the last example
map(lambda x: x*2, fibonacci(1000))

Can you pass in values in Python back into a generator like in ES6?

yeah like since 2006
I'm pretty much sure that js generator features were modeled after python because of how much they're similar

That being said js is a nice language (but with some abysmal old flaws like all numbers are floats by default or you define a variable in a global scope by default, or you need to actually learn how to correctly iterate over various things).

@ndaidong

This comment has been minimized.

Copy link

ndaidong commented Apr 16, 2018

Hi bro, does Python have something equivalent to:

let {
  name,
  age,
} = person
@j8jacobs

This comment has been minimized.

Copy link

j8jacobs commented May 3, 2018

This is fantastic. Came here for the Python spread operator, left with that AND the Array.from :) and excitement for the JS list comprehension.

Great Post!

@ryan-allen

This comment has been minimized.

Copy link

ryan-allen commented Jun 28, 2018

<3 nice one

@tenthirtyone

This comment has been minimized.

Copy link

tenthirtyone commented Jul 12, 2018

var is not part of ES6

@conghungypbn

This comment has been minimized.

Copy link

conghungypbn commented Sep 21, 2018

Having a lot of pain switching from JS to Python. I'm trying to get used to. For Example: JSON in Js will be Object, Dict in Python and the Dict is not quite good. JSON is actually Javascript Object Notation, so it's Object, why made it Dict

Found a lot of good stuff here. Thanks, guys

@dawidgarus

This comment has been minimized.

Copy link

dawidgarus commented Sep 23, 2018

Getters and setters

class Foo:
  @property
  def x(self):
    return self.__x
  @x.setter
  def x(self, x):
    self.__x = x
class Foo {
  get x() {
    return this.__x
  }
  set x(x) {
    this.__x = x
  }
}

Anonymous functions

def fn(outer)
  def anonymous(inner):
    print('Hello')
    return outer + inner
  return anonymous
function fn(outer) {
  return inner => {
    console.log('Hello')
    return outer + inner
  }
}

Iterators

iterator = get_iterator()
try:
  while True:
    next = next(iterator)
    print(next)
except StopIteration:
  pass
const iterator = getIterator()
let next = iterator.next()
while (!next.done) {
  console.log(next)
  next = iterator.next()
}

Slices

arr_slice = arr[start:end]
str_slice = str[start:end]
const arrSlice = arr.slice(start, end)
const strSlice = str.substring(start, end)
@vatshat

This comment has been minimized.

Copy link

vatshat commented Sep 25, 2018

This gist is a LIFE-SAVER for those of us who are more inclined to JS thanks! awesome!

@cuongtb-ibl

This comment has been minimized.

Copy link

cuongtb-ibl commented Nov 20, 2018

it's useful for me, thanks

@edersonbadeca

This comment has been minimized.

Copy link

edersonbadeca commented Dec 6, 2018

Obrigado mano!

It will help me a lot!

Cheers!!

@bel7aG

This comment has been minimized.

Copy link

bel7aG commented Dec 10, 2018

JS:
let up = (x, y = 12) => x + y
up('WebAlwaysWin') // WORK
Py:
up = lambda x: x + 2
up('ok') #OOOPS

@inVisement

This comment has been minimized.

Copy link

inVisement commented Jan 25, 2019

[...Array(5)].map((i,v) => i)
// [0,1,2,3,4,5]

@inVisement

This comment has been minimized.

Copy link

inVisement commented Jan 25, 2019

one of my favorite new syntax in JS: Array and Object deconstructing
a =1
b = 2
c = {a,b}
// {a:1, b:2}
d = {...c, e:4}
it also works as function arguments. quite cool. js catching up with python.

@dhkatz

This comment has been minimized.

Copy link

dhkatz commented Feb 22, 2019

I'd argue that Python does a little better than before in terms of package management with stuff like pipenv. Basically local NPM-like management that is super easy.

@dhkatz

This comment has been minimized.

Copy link

dhkatz commented Feb 23, 2019

I've put together something that goes over a more modern feature set of Python 3.7+ and ES2018+

@gpfreitas

This comment has been minimized.

Copy link

gpfreitas commented Feb 27, 2019

iterator = get_iterator()
try:
  while True:
    next = next(iterator)
    print(next)
except StopIteration:
  pass

No. Instead:

iterator = get_iterator()
for x in iterator:
    print(x)

:)

@pawk

This comment has been minimized.

Copy link

pawk commented Mar 7, 2019

What I like about JS is the functional part of it. With a lot of iteration methods being a part of a prototype chain, one can nicely chain any iterable processing and easily shuffle between complex types while doing it

let reversed = Object.entries({ a: 1, b: 2 })
    .map(([key, val]) => ({ [val]: key }))
    .reduce((acc, o) => ({ ...acc, ...o }), {})
console.log(reversed)

Also anonymous functions with fat arrow syntax makes it so much nicer to write functional code with, higher order functions and function composition is a joy.

In JS you can do things like bind functions to different contexts, borrow methods from other objects and so on.

I really miss object destructuring in Python. On the other hand, things like comprehensions make up for it a ton :)

Fun fact, both Javascript and Python leverage prototypal inheritance model under the covers, but JS is the one to expose it as public API.

@kutyel

This comment has been minimized.

Copy link

kutyel commented Apr 4, 2019

@revolunet could you possibly add ternaries to the comparison? 😉 thanks!

@erik4github

This comment has been minimized.

Copy link

erik4github commented May 17, 2019

@bhch It only leads to inconsistent code if you aren't using something like ESLint.

In your simple example, yes they all do the same thing, because there's only one parameter and it's only one line. Braces are for code blocks.

// fine and dandy
const foo = (x, y) => x * y;

// Returns undefined because we're in a block now
const foobar = (x, y) => { x * y }

// fine and dandy
const bar = (x, y) => { return x * y }

It's not really an inconsistency. Code inside braces is a sequence of statements.

@bijoythomas

This comment has been minimized.

Copy link

bijoythomas commented May 20, 2019

If you are used to writing functional code in JS with either Ramda or Sanctuary etc, it looks like funcy is a good counterpart in Python. I haven't seen any support for higher kinded types or ADT's but it has some very useful utility functions for composition and partial application.

@AdiYElisha

This comment has been minimized.

Copy link

AdiYElisha commented May 28, 2019

Great gist!
would add to the spread section a way for python to spread arrays:

Spread

[*array1, *array2]

search_db(**parameters)
[...array1, ...array2]

searchDb(...parameters);
@xxleyi

This comment has been minimized.

Copy link

xxleyi commented Jun 16, 2019

# map

map of python version missed one arg in lambda expression.

@xxleyi

This comment has been minimized.

Copy link

xxleyi commented Jun 16, 2019

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)
@Hattshire

This comment has been minimized.

Copy link

Hattshire commented Oct 26, 2019

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 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.