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 :)
@schmaluk
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
Copy link

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

@AllencxWang
Copy link

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
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
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
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
Copy link

Hi bro, does Python have something equivalent to:

let {
  name,
  age,
} = person

@j8jacobs
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
Copy link

<3 nice one

@tenthirtyone
Copy link

var is not part of ES6

@conghungypbn
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
Copy link

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
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
Copy link

it's useful for me, thanks

@edersonbadeca
Copy link

Obrigado mano!

It will help me a lot!

Cheers!!

@bel7aG
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-old
Copy link

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

@invisement-old
Copy link

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
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
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
Copy link

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
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
Copy link

kutyel commented Apr 4, 2019

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

@erik4github
Copy link

@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
Copy link

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
Copy link

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
Copy link

xxleyi commented Jun 16, 2019

# map

map of python version missed one arg in lambda expression.

@xxleyi
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
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