This gist is meant to outline differences in syntax and performing common operations in both Python and Javascript (ES2018). This gist may not cover absolutely everything, so a quick double check with Google or StackOverflow can be a big help.
This gist will not cover the extreme basics of the language (i.e. array indexing) because many of these things are intuitive or just common across most languages.
Many of these newer ES2018+ language features might not be available in all browsers. It’s best to use a transpiler/compiler like Babel or Typescript to generate browser compatible code.
Very similar package management between Python and ES2018 when using pipenv to mimic much of the ease of use of npm. Both of the these solutions support using git repositories as well.
Using pipenv, you can easily create virtual (local) environments that supports a more advanced dependency system. This uses a Pipfile
and Pipfile.lock
similar to npm’s own package.json
and package-lock.json
files.
pipenv install # Install from existing Pipfile or create local environment
pipenv install requests # Install a package locally
pipenv uninstall requests # Uninstall
pipenv install git+https://github.com/user/repo@branch#egg=package # Git
Javascript has NPM which, in recent years, has gotten better than it already was. NPM by default installs packages locally, which is much preferred by most developers. Many of the security issues with packages and npm itself have been fixed. NPM uses a package.json
and package-lock.json
for project dependencies.
npm init # Create new local node environment
npm install # Install from existing package.json
npm install request # Install a package locally
npm uninstall request # Uninstall
npm install user/repo#branch # Git support
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));
def foo():
pass
def bar(a, b = 1):
return a * b
function foo() {
}
function bar(a, b = 1) {
return a * b;
}
def foo(outer):
def bar(inner):
return outer + inner
return bar
function foo(outer) {
return (inner) => {
return outer + inner;
}
}
Python does not support top-level await
async def foo():
return await bar()
# Calling the function
result = await foo()
ECMAScript does not currently support top-level await but most likely will
async function foo() {
return await bar();
}
// Calling the function
const result = await foo(); // or foo().then(callback)
def foo():
yield 1
yield 2
yield 3
function *foo() {
yield 1;
yield 2;
yield 3;
}
lambda x: x * 2
x => x * 2
def fibonacci():
pre, cur = 0, 1
while True:
pre, cur = cur, pre + cur
yield cur
for n in fibonacci():
if (n > 1000):
break
print(n)
const fibonacci = {
[Symbol.iterator]: function *() {
let pre = 0, cur = 1;
while (true) {
[pre, cur] = [cur, cur + pre];
yield cur;
}
}
};
for (const n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
Supports multiple inheritance
class SpiderMan(Human, Superhero):
def __init__(self, age):
super(SpiderMan, self).__init__(age)
self.age = age
def attack(self):
print('Spider web!')
class Spiderman extends Superhero {
constructor(age) {
super(age);
this.age = age;
}
attack() {
console.log('Spider web!');
}
}
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;
}
}
# Array Comprehension
names = [c.name for c in customers if c.admin]
# Dictionary Comprehension
letters = { key: val for key, val in enumerable('ABCD') if val not in 'CB' }
# { 0: 'A', 3: 'D' }
Through supported transpilers/compilers like Babel
// Array Comprehension, not natively supported
const names = [for (c of customers) if (c.admin) c.name];
// Something similar can be acheived natively with generators
const names = [...function *() {
for (const c of customers) if (c.admin) yield c.name;
}()];
Note that Python’s range() method must be turned into a new list
print(range(5))
# range(0, 5)
print(list(range(5)))
# [0, 1, 2, 3, 4]
console.log(Array.from(Array(5).keys()));
// [0, 1, 2, 3, 4]
Python does not support object destructuring.
# Array Destructuring
head, *tail = [1, 2, 3, 4] # head = 1, tail = [2, 3, 4]
a, b = (1, 2) # a = 1, b = 2
# Object "destructuring"
a, b, c = [{ 'a': 1, 'b': 2, 'c': 'Hello!' }[k] for k in ('a', 'b', 'c')]
# a = 1, b = 2, c = 'Hello!'
// Array Destructuring
const [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4]
const [a, b] = [1, 2]; // a = 1, b = 2
// Object Destructuring
const { bar } = { bar: 2 }; // bar = 2
const { a, b, c } = { a: 1, b: 2, c: 'Hello!' }; // a = 1, b = 2, c = 'Hello!'
# Positional Spread
array = [1, 2, 3]
print(*array) # 1, 2, 3
# Object Spread
obj = { 'a': 2, 'b': 3}
def foo(b, a):
print(b, a)
foo(**obj) # 3, 2
obj2 = { **obj, 'c': 4 }
ECMAScript does not support keyword arguments
// Positional Spread
const array = [1, 2, 3];
console.log(...array); // 1, 2, 3
// Object Spread
const obj = { a: 2, b: 3 };
const obj2 = { ...obj, c: 4 };
Swapping is easy by knowing how tuples work in Python
a, b = 1, 2
a, b = b,a
Swapping is easy through array destructuring
const a = 1, b = 2;
[a, b] = [b, a];
Many of Python’s built-in iterative functions return iterators and must explicitly be turned into lists
doubles = list(map(lambda x: x * 2, [1, 2, 3, 4])) # [2, 4, 6, 8]
odds = list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4])) # [1, 3]
length = len([1, 2, 3, 4]) # 4
concat = [*[1, 2, 3], *[4, 5, 6]] # [1, 2, 3, 4, 5, 6]
const doubles = [1, 2, 3, 4].map(x => x * 2); // [2, 4, 6, 8]
const odds = [1, 2, 3, 4].filter(x => x % 2 == 1); // [1, 3]
const length = [1, 2, 3, 4].length; // 4
const concat = [...[1, 2, 3], ...[4, 5, 6]]; // [1, 2, 3, 4, 5, 6]
Python supports the f-string syntax since 3.7+
string = 'Hello'
length = len(string) # 5
template = f'{string} World!' # Hello World!
const string = 'Hello';
const length = string.length; // 5
const template = `${string} World!`; // Hello World!
dict = { 'a': 1, 'b': 2, 'c': 3}
keys = dict.keys() # ['a', 'b', 'c']
values = dict.values() # [1, 2, 3]
pairs = dict.items() # [('a', 1), ('b', 2), ('c', 3)]
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj); // ['a', 'b', 'c']
const values = Object.values(obj); // [1, 2, 3]
const pairs = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]]