Python 3.7
Javascript ES6
# single line comments
# multi line
# comments
// single line comments
/**
* multi line
* comments
*/
my_var = 123
my_var = 'abc'
let myVar = 123;
myVar = 'abc';
// use 'const' to prevent reassignment
const myOtherVar = 456;
myOtherVar = 'def'; // TypeError: Assignment to constant variable.
a_bool = True
an_inverse_bool = not a_bool
a_number = 123
a_string = "abc"
a_list = [1, 2, 3]
a_tuple = (1, 2, 3)
a_set = {1, 2, 3}
a_dict = {"a": 1, "b": 2, "c": 3} # access keys with indexers: a_dict["a"]
an_object = SomeClass() # access keys with dot-access: an_object.a
const aBool = true;
const anInverseBool = !aBool;
const aNumber = 123;
const aString = 'abc';
const anArray = [1, 2, 3];
// Arrays are used as tuples in Javascript
const aSet = new Set([1, 2, 3]);
// Javascript does not differentiate between a dictionary and an object
const anObject = {a: 1, b: 2, c: 3}; // access keys with dot-access: anObject.a
# DICTS
d = {"a": 1}
d['a'] # returns '1'
d.get('b') # returns None
d['b'] # raises KeyError: 'b'
if d.get('b'):
# does NOT execute
if d.get('a'):
# DOES execute
# LISTS
l1 = []
l2 = [1]
# Empty lists are falsey:
if l1:
# does NOT execute
if l2:
# DOES execute
// OBJECTS (dicts)
const d = { a: 1 };
d['a'] // returns '1'
d.a // returns '1'
d['b'] // returns 'undefined' (does NOT raise)
d.b // returns 'undefined' (does NOT raise)
if (d.b) {
// does NOT execute
}
if (d.a) {
// DOES execute
}
// ARRAYS (lists)
const l1 = [];
const l2 = [1];
// empty arrays ARE STILL TRUTHY!
if (l1) {
// THIS WILL EXECUTE
}
if (l2) {
// THIS ALSO WILL EXECECUTE
}
// use the .length property to check for empty lists:
if (l1.length) {
// does NOT execute
}
if (l2) {
// DOES execute
}
a = 1
b = 2
f"{a} + {b} = {a + b}"
const a = 1;
const b = 2;
`${a} + ${b} = ${a + b}`
import math
print(math.log(42))
from math import log
print(log(42))
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));
while True:
print('still true')
lst = [1, 2, 3, 4]
for x in lst:
print(x)
for i, x in enumerate(lst):
print(f"{i}: {x}")
while(true) {
console.log('still true');
}
const arr = [1, 2, 3, 4];
for (x of arr) {
console.log(x);
}
for (let i = 0, i < arr.length; i++) {
x = arr[i];
console.log(x);
}
// there is also a functional forEach available on most iterables:
arr.forEach(x => console.log(x));
if True:
print('still true')
elif not True:
print('this is rather odd')
else:
print('???')
# ternary operator:
1 if True else 0
if (true) {
console.log('still true');
} else if (!true) {
console.log('this is rather odd');
} else {
console.log('???');
}
// ternary operator:
true ? 1 : 0;
Python does not have a switch statement (😢)(Coming soon to a Python 3.10 near you!)
function greet(timeOfDay) {
let greeting = 'hello';
switch (timeOfDay) {
case 'morning':
greeting += ', good morning';
break;
case 'afternoon':
greeting += ', good afternoon';
break;
default:
greeting += ', good evening';
break;
}
console.log(greeting);
}
# defining
def add_numbers(a, b):
return a + b
# calling
add_numbers(1, 2)
add_numbers(a=1, b=2)
// defining
function addNumbers(a, b) {
return a + b;
}
// calling
addNumbers(1, 2);
// Javascript does not have named parameters
lambda a: a * 2
a => a * 2
=>
is often called a 'fat arrow'
- Python has multiple inheritance; Javascript does not
- Python refers to the instance as
self
; Javascript usesthis
- Python calls the initializer like a function; Javascript uses the
new
keyword to call constructors
# defining
class SpiderMan(Human, SuperHero):
# member variables
my_val
other_val = 123
# "name mangling" can be used to controll public/private access.
__cant_see_me = 456
# properties
@property
def see_me(self):
return self.__cant_see_me
@see_me.setter
def see_me(self, val):
self.__cant_see_me = val
# term: initializer
def __init__(self, age):
super().__init__(age)
self.age = age
# instance methods
def say_age(self):
print(self.age)
@classmethod
def hello(cls):
# can access the class itself with cls
print('world')
@staticmethod
def just_a_function():
print("nothing special, func assocated with a class")
# instantiating
spman = SpiderMan(123)
# accessing members
spman.my_val # None
spman.other_val # 123
spman.__cant_see_me # AttributeError: 'SpiderMan' object has no attribute '__cant_see_me'
# accessing/setting propertes
spman.see_me # 456
spman.see_me = 789
spman.see_me # 789
// defining
class SpiderMan extends SuperHero {
// member variables
myVal;
otherVal = 123;
// no private/mangling corollary in ES6, underscores are often used symbolically
_cantSeeMe = 456;
// properties
get seeMe() {
return this._cantSeeMe
}
set seeMe(val) {
this._cantSeeMe = val
}
// term: constructor
constructor(age) {
super();
this.age = age;
}
// instance methods
sayAge() {
console.log(this.age);
}
// class/static methods
hello() {
console.log('world');
}
justAFunction() {
console.log("nothing special, func assocated with a class")
}
}
// instantiating
const spman = new SpiderMan(123);
// accessing members
spman.myVal // undefined
spman.otherVal // 123
spman._cantSeeMe // 456 (note nothing functionally special about leading underscore)
// accessing/setting propertes
spman.seeMe // 456
spman.seeMe = 789
spman.seeMe // 789
parameters = { "a": 1, "b": 2, "c": 3 }
search_db(**parameters)
# above and below are identical:
# search_db(a=parameters['a'], b=parameters['b'], c=parameters['c'])
const parameters = { a: 1, b: 2, c:3 };
searchDb(...parameters);
// above and below are identical:
// searchDb(parameters.a, parameters.b, parameters.c);
status, data, message, headers = getResult()
const [status, data, message, headers] = getResult();
// the spread operator can be used when destructuring to discard unused values:
const [status, data, ...] = getResult();
// objects can also be destructured in Javascript:
const {status, data, message, headers} = getResultObject();
lst = [1, 2, 3, 4]
# length
len(lst)
# map
[x*2 for x in lst]
map(lambda x: x*2, lst)
# filter
[x for x in lst if x > 2]
filter(lambda x: x > 2, lst)
# sort
sorted(lst)
lst.sort()
# reduce
from functools import reduce
reduce(lambda acc, curr: acc + curr, lst, 0)
const arr = [1, 2, 3, 4];
// length
arr.length;
// map
arr.map(x => x * 2);
// filter
arr.filter(x => x > 2);
// sort
arr.sort();
// reduce
arr.reduce((acc, curr) => acc + curr, 0);