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 = [Link](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 = [Link](0, 2); // [1, 2]
last_two = items[-2:] # [4, 5] last_two = [Link](-2); // [4, 5]
middle_three = items[1:4] # [2, 3, 4] middle_three = [Link](1, 4); // [2, 3, 4]
String slices text = 'ABCDE' text = 'ABCDE';
first_two = text[:2] # 'AB' first_two = [Link](0, 2); // 'AB'
last_two = text[-2:] # 'DE' last_two = [Link](-2); // 'DE'
middle_three = text[1:4] # 'BCD' middle_three = [Link](1, 4); // 'BCD'
List operations items1 = ['A'] items1 = ['A'];
items2 = ['B'] items2 = ['B'];
items = items1 + items2 # items == ['A', 'B'] items = [Link](items2); // items === ['A', 'B']
[Link]('C') # ['A', 'B', 'C'] [Link]('C'); // ['A', 'B', 'C']
[Link](0, 'D') # ['D', 'A', 'B', 'C'] [Link]('D'); // ['D', 'A', 'B', 'C']
first = [Link](0) # ['A', 'B', 'C'] first = [Link](); // ['A', 'B', 'C']
last = [Link]() # ['A', 'B'] last = [Link](); // ['A', 'B']
[Link](0) # ['B'] [Link](0, 1); // ['B']
Joining lists of strings items = ['A', 'B', 'C'] items = ['A', 'B', 'C'];
text = ', '.join(items) # 'A, B, C' text = [Link](', '); // 'A, B, C'
JSON import json
json_data = [Link](dictionary, indent=4) json_data = [Link](dictionary, null, 4);
dictionary = [Link](json_data) dictionary = [Link](json_data);
Splitting strings by regular import re
# One or more of "!?." followed by whitespace // One or more of "!?." followed by whitespace
expressions delimiter = [Link](r'[!?\.]+\s*') delimiter = /[!?\.]+\s*/;
text = "Hello!!! What's new? Follow me." text = "Hello!!! What's new? Follow me.";
sentences = [Link](text) sentences = [Link](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 = [Link]( pattern = /([\w.+\-]+)@([\w\-]+\.[\w\-.]+)/;
strings r'([\w.+\-]+)@([\w\-]+\.[\w\-.]+)'
)
match = [Link]('hi@[Link]') match = 'hi@[Link]'.match(pattern);
# [Link](0) == 'hi@[Link]' // match[0] === 'hi@[Link]'
# [Link](1) == 'hi' // match[1] === 'hi'
# [Link](2) == '[Link]' // match[2] === '[Link]'
text = 'Say hi at hi@[Link]' text = 'Say hi at hi@[Link]';
first_match = [Link](text) first_match = [Link](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 = [Link]( pattern = /([\w.+\-]+)@([\w\-]+\.[\w\-.]+)/;
expressions r'([\w.+\-]+)@([\w\-]+\.[\w\-.]+)'
) html = 'Say hi at hi@[Link]'.replace(
pattern,
html = [Link]( '<a href="[Link]
r'<a href="[Link] );
'Say hi at hi@[Link]', // html === 'Say hi at <a
) href="[Link]
# html == 'Say hi at <a
href="[Link] text = 'Say hi at hi@[Link]'.replace(
pattern,
text = [Link]( function(match, p1, p2) {
lambda match: [Link](0).upper(), return [Link]();
'Say hi at hi@[Link]', }
) );
# text == 'Say hi at HI@[Link]' // text === 'Say hi at HI@[Link]'
Error handling class MyException(Exception): function MyException(message) {
def __init__(self, message): [Link] = message;
[Link] = message [Link] = function() {
return [Link];
def __str__(self): }
return [Link] }
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: [Link]('Sorry! ' + err);
print('Finishing') }
} finally {
[Link]('Finishing');
}
Revision 12 March 2019 More details: [Link]
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 ${[Link](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 => [Link](x, 2);
Iteration for item in ['A', 'B', 'C']: for (let item of ['A', 'B', 'C']) {
print(item) [Link](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) [Link](counter);
}
Sets s = set(['A']) s = new Set(['A']);
[Link]('B'); [Link]('C') [Link]('B').add('C');
'A' in s [Link]('A') === true;
len(s) == 3 [Link] === 3;
for elem in s: for (let elem of [Link]()) {
print(elem) [Link](elem);
}
[Link]('C') [Link]('C');
Function arguments from pprint import pprint
function create_post(options) {
def create_post(**options): [Link](options);
pprint(options) }
function report(post_id, reason='not-relevant') {
def report(post_id, reason='not-relevant'): [Link]({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}) [Link]({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) {
[Link] = id [Link] = id;
[Link] = title [Link] = title;
}
def __str__(self): toString() {
return [Link] return [Link];
}
}
class Article(Post):
def __init__(self, id, title, content): class Article extends Post {
super(Article, self).__init__(id, title) constructor (id, title, content) {
[Link] = content super(id, title);
[Link] = content;
}
class Link(Post): }
def __init__(self, id, title, url):
super(Link, self).__init__(id, title) class Link extends Post {
[Link] = url constructor (id, title, url) {
super(id, title);
def __str__(self): [Link] = url;
return '{} ({})'.format( }
super(Link, self).__str__(), toString() {
[Link], return [Link]() + ' (' + [Link] + ')';
) }
}
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', '[Link] link = new Link(2, 'The Example', '[Link]
# isinstance(article, Post) == True // article instanceof Post === true
# isinstance(link, Post) == True // link instanceof Post === true
print(link) [Link]([Link]());
# The Example ([Link] // The Example ([Link]
Class properties: getters class Post(object): class Post {
def __init__(self, id, title): constructor (id, title) {
and setters [Link] = id [Link] = id;
[Link] = title [Link] = title;
self._slug = '' this._slug = '';
}
@property
def slug(self): set slug(value) {
return self._slug this._slug = value;
}
@[Link]
def slug(self, value): get slug() {
self._slug = value return this._slug;
}
}
post = Post(1, 'Hello, World!') post = new Post(1, 'Hello, World!');
[Link] = 'hello-world' [Link] = 'hello-world';
print([Link]) [Link]([Link]);
Revision 12 March 2019 More details: [Link]
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 = [Link](Boolean);
# True // true
Any truthful elements items = [0, 1, 2, 3] items = [0, 1, 2, 3];
some_truthy = any(items) some_truthy = [Link](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): [Link](function(element, index) {
print(f'{index}: {element};') [Link](`${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 = [Link](
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 = [Link](
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 = [Link](
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: [Link]