The Ultimate List of Equivalents in Python and JavaScript by @DjangoTricks
Time-honored Python JavaScript (ECMAScript 5)
Parse integer number = int(text) number = parseInt(text, 10);
Conditional assignment value = 'ADULT' if age >= 18 else 'CHILD' value = age >= 18? 'ADULT': 'CHILD';
Object attribute value by attribute = 'color' attribute = 'color';
value = getattr(obj, attribute, 'GREEN') value = obj[attribute] || 'GREEN';
name setattr(obj, attribute, value) obj[attribute] = value;
Dictionary value by key key = 'color' key = 'color';
value = dictionary.get(key, 'GREEN') value = dictionary[key] || 'GREEN';
dictionary[key] = value dictionary[key] = value;
List slices items = [1, 2, 3, 4, 5] items = [1, 2, 3, 4, 5];
first_two = items[:2] # [1, 2] first_two = items.slice(0, 2); // [1, 2]
last_two = items[-2:] # [4, 5] last_two = items.slice(-2); // [4, 5]
middle_three = items[1:4] # [2, 3, 4] middle_three = items.slice(1, 4); // [2, 3, 4]
String slices text = 'ABCDE' text = 'ABCDE';
first_two = text[:2] # 'AB' first_two = text.slice(0, 2); // 'AB'
last_two = text[-2:] # 'DE' last_two = text.slice(-2); // 'DE'
middle_three = text[1:4] # 'BCD' middle_three = text.slice(1, 4); // 'BCD'
List operations items1 = ['A'] items1 = ['A'];
items2 = ['B'] items2 = ['B'];
items = items1 + items2 # items == ['A', 'B'] items = items1.concat(items2); // items === ['A', 'B']
items.append('C') # ['A', 'B', 'C'] items.push('C'); // ['A', 'B', 'C']
items.insert(0, 'D') # ['D', 'A', 'B', 'C'] items.unshift('D'); // ['D', 'A', 'B', 'C']
first = items.pop(0) # ['A', 'B', 'C'] first = items.shift(); // ['A', 'B', 'C']
last = items.pop() # ['A', 'B'] last = items.pop(); // ['A', 'B']
items.delete(0) # ['B'] items.splice(0, 1); // ['B']
Joining lists of strings items = ['A', 'B', 'C'] items = ['A', 'B', 'C'];
text = ', '.join(items) # 'A, B, C' text = items.join(', '); // 'A, B, C'
JSON import json
json_data = json.dumps(dictionary, indent=4) json_data = JSON.stringify(dictionary, null, 4);
dictionary = json.loads(json_data) dictionary = JSON.parse(json_data);
Splitting strings by regular import re
# One or more of "!?." followed by whitespace // One or more of "!?." followed by whitespace
expressions delimiter = re.compile(r'[!?\.]+\s*') delimiter = /[!?\.]+\s*/;
text = "Hello!!! What's new? Follow me." text = "Hello!!! What's new? Follow me.";
sentences = delimiter.split(text) sentences = text.split(delimiter);
# sentences == ['Hello', "What's new", 'Follow me', // sentences == ["Hello", "What's new", "Follow me", ""]
'']
Matching regular import re
# name, "@", and domain // name, "@", and domain
expression patterns in pattern = re.compile( pattern = /([\w.+\-]+)@([\w\-]+\.[\w\-.]+)/;
strings r'([\w.+\-]+)@([\w\-]+\.[\w\-.]+)'
)
match = pattern.match('
[email protected]') match = '
[email protected]'.match(pattern);
# match.group(0) == '
[email protected]' // match[0] === '
[email protected]'
# match.group(1) == 'hi' // match[1] === 'hi'
# match.group(2) == 'example.com' // match[2] === 'example.com'
first_match = pattern.search(text) first_match = text.search(pattern);
if first_match: if (first_match > -1) {
start = first_match.start() # start == 10 start = first_match; // start === 10
}
Replacing patterns in import re
# name, "@", and domain // name, "@", and domain
strings using regular pattern = re.compile( pattern = /([\w.+\-]+)@([\w\-]+\.[\w\-.]+)/;
expressions r'([\w.+\-]+)@([\w\-]+\.[\w\-.]+)'
) html = 'Say hi at
[email protected]'.replace(
pattern,
html = pattern.sub( '<a href="mailto:$&">$&</a>',
r'<a href="mailto:\g<0>">\g<0></a>', );
'Say hi at
[email protected]', // html === 'Say hi at <a
) href="mailto:
[email protected]">
[email protected]</a>'
# html == 'Say hi at <a
href="mailto:
[email protected]">
[email protected]</a>' text = 'Say hi at
[email protected]'.replace(
pattern,
text = pattern.sub( function(match, p1, p2) {
lambda match: match.group(0).upper(), return match.toUpperCase();
'Say hi at
[email protected]', }
) );
# text == 'Say hi at
[email protected]' // text === 'Say hi at
[email protected]'
Error handling class MyException(Exception): function MyException(message) {
def __init__(self, message): this.message = message;
self.message = message this.toString = function() {
return this.message;
def __str__(self): }
return self.message }
def proceed(): function proceed() {
raise MyException('Error happened!') throw new MyException('Error happened!');
}
try: try {
proceed() proceed();
except MyException as err: } catch (err) {
print('Sorry! {}'.format(err)) if (err instanceof MyException) {
finally: console.log('Sorry! ' + err);
print('Finishing') }
} finally {
console.log('Finishing');
}
Revision 12 March 2019 More details: http://bit.ly/2tXLoXq
The Ultimate List of Equivalents in Python and JavaScript by @DjangoTricks
Future-proof Python JavaScript (ECMAScript 6)
Variables in strings name = 'World' name = 'World';
value = f"""Hello, {name}! value = `Hello, ${name}!
Welcome!""" # Python 3.6 Welcome!`;
price = 14.9 price = 14.9;
value = f'Price: {price:.2f} €' # 'Price: 14.90 €' value = `Price ${price.toFixed(2)} €`; // 'Price: 14.90 €'
Unpacking lists a = 1 a = 1;
b = 2 b = 2;
a, b = b, a # swap values [a, b] = [b, a]; // swap values
first, second, *the_rest = [1, 2, 3, 4] # Python 3.6 [first, second, ...the_rest] = [1, 2, 3, 4];
# first == 1, second == 2, the_rest == [3, 4] // first === 1, second === 2, the_rest === [3, 4]
Lambda functions sum = lambda x, y: x + y sum = (x, y) => x + y;
square = lambda x: x ** 2 square = x => Math.pow(x, 2);
Iteration for item in ['A', 'B', 'C']: for (let item of ['A', 'B', 'C']) {
print(item) console.log(item);
}
Generators def countdown(counter): function* countdown(counter) {
while counter > 0: while (counter > 0) {
yield counter yield counter;
counter -= 1 counter--;
}
}
for counter in countdown(10): for (let counter of countdown(10)) {
print(counter) console.log(counter);
}
Sets s = set(['A']) s = new Set(['A']);
s.add('B'); s.add('C') s.add('B').add('C');
'A' in s s.has('A') === true;
len(s) == 3 s.size === 3;
for elem in s: for (let elem of s.values()) {
print(elem) console.log(elem);
}
s.remove('C') s.delete('C');
Function arguments from pprint import pprint
function create_post(options) {
def create_post(**options): console.log(options);
pprint(options) }
function report(post_id, reason='not-relevant') {
def report(post_id, reason='not-relevant'): console.log({post_id: post_id, reason: reason});
pprint({'post_id': post_id, 'reason': reason}) }
def add_tags(post_id, *tags): function add_tags(post_id, ...tags) {
pprint({'post_id': post_id, 'tags': tags}) console.log({post_id: post_id, tags: tags});
}
create_post(title='Hello, World!', content='')
report(42) create_post({title: 'Hello, World!', content': ''});
report(post_id=24, reason='spam') report(42);
add_tags(42, 'python', 'javascript', 'django') report(post_id=24, reason='spam');
add_tags(42, 'python', 'javascript', 'django');
Classes and inheritance class Post(object): class Post {
def __init__(self, id, title): constructor (id, title) {
self.id = id this.id = id;
self.title = title this.title = title;
}
def __str__(self): toString() {
return self.title return this.title;
}
}
class Article(Post):
def __init__(self, id, title, content): class Article extends Post {
super(Article, self).__init__(id, title) constructor (id, title, content) {
self.content = content super(id, title);
this.content = content;
}
class Link(Post): }
def __init__(self, id, title, url):
super(Link, self).__init__(id, title) class Link extends Post {
self.url = url constructor (id, title, url) {
super(id, title);
def __str__(self): this.url = url;
return '{} ({})'.format( }
super(Link, self).__str__(), toString() {
self.url, return super.toString() + ' (' + this.url + ')';
) }
}
article = Article(1, 'Hello, World!', article = new Article(1, 'Hello, World!',
'This is my first article.' 'This is my first article.'
) );
link = Link(2, 'The Example', 'http://example.com') link = new Link(2, 'The Example', 'http://example.com');
# isinstance(article, Post) == True // article instanceof Post === true
# isinstance(link, Post) == True // link instanceof Post === true
print(link) console.log(link.toString());
# The Example (http://example.com) // The Example (http://example.com)
Class properties: getters class Post(object): class Post {
def __init__(self, id, title): constructor (id, title) {
and setters self.id = id this.id = id;
self.title = title this.title = title;
self._slug = '' this._slug = '';
}
@property
def slug(self): set slug(value) {
return self._slug this._slug = value;
}
@slug.setter
def slug(self, value): get slug() {
self._slug = value return this._slug;
}
}
post = Post(1, 'Hello, World!') post = new Post(1, 'Hello, World!');
post.slug = 'hello-world' post.slug = 'hello-world';
print(post.slug) console.log(post.slug);
Revision 12 March 2019 More details: http://bit.ly/2tXLoXq
The Ultimate List of Equivalents in Python and JavaScript by @DjangoTricks
Bonus Python JavaScript (ECMAScript 6)
All truthful elements items = [1, 2, 3] items = [1, 2, 3];
all_truthy = all(items) all_truthy = items.every(Boolean);
# True // true
Any truthful elements items = [0, 1, 2, 3] items = [0, 1, 2, 3];
some_truthy = any(items) some_truthy = items.some(Boolean);
# True // true
Iterate through each items = ['a', 'b', 'c', 'd'] items = ['a', 'b', 'c', 'd'];
element and its index for index, element in enumerate(items): items.forEach(function(element, index) {
print(f'{index}: {element};') console.log(`${index}: ${element};`);
});
Map elements to the items = [0, 1, 2, 3] items = [0, 1, 2, 3];
results of a function all_doubled = list( all_doubled = items.map(
map(lambda x: 2 * x, items) x => 2 * x
) );
# [0, 2, 4, 6] // [0, 2, 4, 6]
Filter elements by a items = [0, 1, 2, 3] items = [0, 1, 2, 3];
function only_even = list( only_even = items.filter(
filter(lambda x: x % 2 == 0, items) x => x % 2 === 0
) );
# [0, 2] // [0, 2]
Reduce elements by a from functools import reduce
function to a single value items = [1, 2, 3, 4] items = [1, 2, 3, 4];
total = reduce( total = items.reduce(
lambda total, current: total + current, (total, current) => total + current
items, );
) // 10
# 10
Merge dictionaries d1 = {'a': 'A', 'b': 'B'} d1 = {a: 'A', b: 'B'}
d2 = {'a': 'AAA', 'c': 'CCC'} d2 = {a: 'AAA', c: 'CCC'}
merged = {**d1, **d2} # since Python 3.5 merged = {...d1, ...d2};
# {'a': 'AAA', 'b': 'B', 'c': 'CCC'} // {a: 'AAA', b: 'B', c: 'CCC'}
Revision 12 March 2019 More details: http://bit.ly/2tXLoXq