Python and JavaScript are two of the most popular programming languages. If you're are Python programmer learning JavaScript, or a JavaScript programmer learning Python, this handy cheat sheet might help you.
This page is open sourced on GitHub. Pull requests are welcome!
abs
# 100
print(abs(-100))
# 50
print(abs(50))
abs
// 100
console.log(Math.abs(-100))
// 50
console.log(Math.abs(50))
if
some_number = 3
# Number is 3
if some_number == 1:
print("Number is 1")
elif some_number == 2:
print("Number is 2")
elif some_number == 3:
print("Number is 3")
else:
print("?")
if
const someNumber = 3
// Number is 3
if (someNumber === 1) {
console.log('Number is 1')
} else if (someNumber === 2) {
console.log('Number is 2')
} else if (someNumber === 3) {
console.log('Number is 3')
} else {
console.log('?')
}
x = 2
y = 3
# even
print("even" if x % 2 == 0 else "odd")
# odd
print("even" if y % 2 == 0 else "odd")
Conditional Operator
const x = 2
const y = 3
// even
console.log(x % 2 === 0 ? 'even' : 'odd')
// odd
console.log(y % 2 === 0 ? 'even' : 'odd')
# yes
if "abc" == "abc":
print("yes")
else:
print("no")
# yes
if "abc" != "def":
print("yes")
else:
print("no")
# no
if True and False:
print("yes")
else:
print("no")
# yes
if True or False:
print("yes")
else:
print("no")
# yes
if not False:
print("yes")
else:
print("no")
# no
if 0:
print("yes")
else:
print("no")
# no
if "":
print("yes")
else:
print("no")
# no
if []:
print("yes")
else:
print("no")
# no
if None:
print("yes")
else:
print("no")
# yes
if not not not None:
print("yes")
else:
print("no")
Falsy Values
// yes
if ('abc' === 'abc') {
console.log('yes')
} else {
console.log('no')
}
// yes
if ('abc' !== 'def') {
console.log('yes')
} else {
console.log('no')
}
// no
if (true && false) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (true || false) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (!false) {
console.log('yes')
} else {
console.log('no')
}
// no
if (0) {
console.log('yes')
} else {
console.log('no')
}
// no
if ('') {
console.log('yes')
} else {
console.log('no')
}
// no
if (undefined) {
console.log('yes')
} else {
console.log('no')
}
// no
if (null) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (!!!null) {
console.log('yes')
} else {
console.log('no')
}
Errors
# foo is not defined
try:
foo()
except NameError:
print("foo is not defined")
try...catch
// foo is not defined
try {
foo()
} catch (error) {
console.log('foo is not defined')
}
break/continue
# 1
# 2
# Fizz
# 4
# Buzz
for number in range(1, 101):
if number == 3:
print("Fizz")
continue
if number == 5:
print("Buzz")
break
print(number)
len
some_string = "abcd"
# 4
print(len(some_string))
length
const someString = 'abcd'
// 4
console.log(someString.length)
x = "Hello"
# Hello World
print(f"{x} World")
const x = 'Hello'
// Hello World
console.log(`${x} World`)
x = """------
Line 1
Line 2
Line 3
------"""
# ------
# Line 1
# Line 2
# Line 3
# ------
print(x)
Multiline Strings
const x = `------
Line 1
Line 2
Line 3
------`
// ------
// Line 1
// Line 2
// Line 3
// ------
console.log(x)
int
string_1 = "1"
number_1 = int(string_1)
# 3
print(number_1 + 2)
parseInt
const string1 = '1'
const number1 = parseInt(string1)
// 3
console.log(number1 + 2)
in
# 2 is in the string
if "2" in "123":
print("2 is in the string")
# 2 is not in the string
if "2" not in "456":
print("2 is not in the string")
includes
// 2 is in the string
if ('123'.includes('2')) {
console.log('2 is in the string')
}
// 2 is not in the string
if (!'456'.includes('2')) {
console.log('2 is not in the string')
}
[i:j]
some_string = "0123456"
# 234
print(some_string[2:5])
substring
const someString = '0123456'
// 234
console.log(someString.substring(2, 5))
join
some_list = ["a", "b", "c"]
# a,b,c
print(",".join(some_list))
join
const someList = ['a', 'b', 'c']
// a,b,c
console.log(someList.join(','))
strip
some_string = " abc "
# abc
print(some_string.strip())
trim
const someString = ' abc '
// abc
console.log(someString.trim())
split
some_string = "a,b,c"
some_string_split = some_string.split(",")
# a
print(some_string_split[0])
# b
print(some_string_split[1])
# c
print(some_string_split[2])
split
const someString = 'a,b,c'
const someStringSplit = someString.split(',')
// a
console.log(someStringSplit[0])
// b
console.log(someStringSplit[1])
// c
console.log(someStringSplit[2])
replace
some_string = "a b c d e"
# a,b,c,d,e
print(some_string.replace(" ", ","))
Regular Expressions
, replace
const someString = 'a b c d e'
// Only changes the first space
// a,b c d e
// console.log(someString.replace(' ', ','))
// Use / /g instead of ' ' to change every space
console.log(someString.replace(/ /g, ','))
search
import re
# Has a number
if re.search(r"\d", "iphone 8"):
print("Has a number")
# Doesn't have a number
if not re.search(r"\d", "iphone x"):
print("Doesn't have a number")
Regular Expressions
, match
// Has a number
if ('iphone 8'.match(/\d/g)) {
console.log('Has a number')
}
// Doesn't have a number
if (!'iphone x'.match(/\d/g)) {
console.log("Doesn't have a number")
}
some_list = [6, 3, 5]
# 6
# 3
# 5
for item in some_list:
print(item)
forEach
const someList = [6, 3, 5]
// 6
// 3
// 5
someList.forEach(element => {
console.log(element)
})
len
some_list = [1, 4, 9]
# 3
print(len(some_list))
length
const someList = [1, 4, 9]
// 3
console.log(someList.length)
in
# 2 is in the list
if 2 in [1, 2, 3]:
print("2 is in the list")
# 2 is not in the list
if 2 not in [4, 5, 6]:
print("2 is not in the list")
includes
// 2 is in the list
if ([1, 2, 3].includes(2)) {
console.log('2 is in the list')
}
// 2 is not in the list
if (![4, 5, 6].includes(2)) {
console.log('2 is not in the list')
}
reversed
, list
some_list = [1, 2, 3, 4]
# reversed(some_list) is just an iterable.
# To convert an iterable into a list, use list()
reversed_list = list(reversed(some_list))
# 4
# 3
# 2
# 1
for item in reversed_list:
print(item)
# You can use an iterable instead of a list in a for loop
# for item in reversed(some_list):
reverse
const someList = [1, 2, 3, 4]
someList.reverse()
// 4
// 3
// 2
// 1
someList.forEach(element => {
console.log(element)
})
range
# 0
# 1
# 2
# 3
for i in range(4):
print(i)
# 4
# 5
# 6
# 7
for i in range(4, 8):
print(i)
# 6
# 5
# 4
for i in range(6, 3, -1):
print(i)
// 0
// 1
// 2
// 3
for (let i = 0; i < 4; i++) {
console.log(i)
}
// 4
// 5
// 6
// 7
for (let i = 4; i < 8; i++) {
console.log(i)
}
// 6
// 5
// 4
for (let i = 6; i > 3; i--) {
console.log(i)
}
append
some_list = [1, 2]
some_list.append(3)
# 1
# 2
# 3
for x in some_list:
print(x)
push
const someList = [1, 2]
someList.push(3)
// 1
// 2
// 3
someList.forEach(element => {
console.log(element)
})
Unpacking
original_list = [1, 2]
# [original_list, 3] -> [[1, 2], 3]
# [*original_list, 3] -> [1, 2, 3]
new_list = [*original_list, 3]
original_list[0] = 5
# 1
# 2
# 3
for x in new_list:
print(x)
Spread
const originalList = [1, 2]
// [originalList, 3] -> [[1, 2], 3]
// [...originalList, 3] -> [1, 2, 3]
const newList = [...originalList, 3]
originalList[0] = 5
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
extend
some_list = [1]
some_list.extend([2, 3])
# 1
# 2
# 3
for x in some_list:
print(x)
Spread
const someList = [1]
someList.push(...[2, 3])
// 1
// 2
// 3
someList.forEach(element => {
console.log(element)
})
List addition
original_list = [1]
new_list = original_list + [2, 3]
original_list[0] = 5
# 1
# 2
# 3
for x in new_list:
print(x)
concat
const originalList = [1]
const newList = originalList.concat([2, 3])
originalList[0] = 5
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
insert
some_list = [4, 5]
some_list.insert(0, 3)
# 3
# 4
# 5
for x in some_list:
print(x)
unshift
const someList = [4, 5]
someList.unshift(3)
// 3
// 4
// 5
someList.forEach(element => {
console.log(element)
})
del
some_list = ["a", "b", "c"]
del some_list[1]
# a
# c
for x in some_list:
print(x)
splice
const someList = ['a', 'b', 'c']
someList.splice(1, 1)
// a
// c
someList.forEach(element => {
console.log(element)
})
pop
some_list = [1, 2, 3, 4]
# 4
print(some_list.pop())
# 1
print(some_list.pop(0))
# 2
# 3
for x in some_list:
print(x)
index
some_list = ["a", "b", "c", "d", "e"]
# 2
print(some_list.index("c"))
indexOf
const someList = ['a', 'b', 'c', 'd', 'e']
// 2
console.log(someList.indexOf('c'))
[i:j]
original_list = [1, 2, 3]
new_list = original_list[:] # or original_list.copy()
original_list[2] = 4
# 1
# 2
# 3
for x in new_list:
print(x)
Spread
const originalList = [1, 2, 3]
const newList = [...originalList]
originalList[2] = 4
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
List Comprehensions
original_list = [1, 2, 3]
new_list = [x * 2 for x in original_list]
# 2
# 4
# 6
for x in new_list:
print(x)
map
const originalList = [1, 2, 3]
// You can also do this:
// const newList = originalList.map(x => { return x * 2 })
const newList = originalList.map(x => x * 2)
// 2
// 4
// 6
newList.forEach(element => {
console.log(element)
})
List Comprehensions
first_list = [1, 3]
second_list = [3, 4]
combined_list = [[x + y for y in second_list] for x in first_list]
# 4
print(combined_list[0][0])
# 5
print(combined_list[0][1])
# 6
print(combined_list[1][0])
# 7
print(combined_list[1][1])
map
const firstList = [1, 3]
const secondList = [3, 4]
const conbinedList = firstList.map(x => {
return secondList.map(y => {
return x + y
})
})
// 4
console.log(conbinedList[0][0])
// 5
console.log(conbinedList[0][1])
// 6
console.log(conbinedList[1][0])
// 7
console.log(conbinedList[1][1])
List Comprehensions
original_list = [1, 2, 3, 4, 5, 6]
new_list = [x for x in original_list if x % 2 == 0]
# 2
# 4
# 6
for x in new_list:
print(x)
filter
const originalList = [1, 2, 3, 4, 5, 6]
const newList = originalList.filter(x => x % 2 == 0)
// 2
// 4
// 6
newList.forEach(element => {
console.log(element)
})
sum
some_list = [1, 2, 3]
# 6
print(sum(some_list))
reduce
const someList = [1, 2, 3]
const reducer = (accumulator, currentValue) => accumulator + currentValue
// 6
console.log(someList.reduce(reducer))
zip
list_1 = [1, 3, 5]
list_2 = [2, 4, 6]
# 1 2
# 3 4
# 5 6
for x, y in zip(list_1, list_2):
print(f"{x} {y}")
map
const list1 = [1, 3, 5]
const list2 = [2, 4, 6]
// [[1, 2], [3, 4], [5, 6]]
const zippedList = list1.map((x, y) => {
return [x, list2[y]]
})
zippedList.forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
[i:j]
original_list = ["a", "b", "c", "d", "e"]
new_list = original_list[1:3]
original_list[1] = "x"
# b
# c
for x in new_list:
print(x)
slice
const originalList = ['a', 'b', 'c', 'd', 'e']
const newList = originalList.slice(1, 3)
originalList[1] = 'x'
// b
// c
newList.forEach(element => {
console.log(element)
})
sorted
some_list = [4, 2, 1, 3]
# 1
# 2
# 3
# 4
for item in sorted(some_list):
print(item)
sort
const someList = [4, 2, 1, 3]
// 1
// 2
// 3
// 4
someList.sort().forEach(element => {
console.log(element)
})
sorted
some_list = [["c", 2], ["b", 3], ["a", 1]]
# a 1
# c 2
# b 3
for item in sorted(some_list, key=lambda x: x[1]):
print(f"{item[0]} {item[1]}")
sort
const someList = [['c', 2], ['b', 3], ['a', 1]]
// a 1
// c 2
// b 3
someList
.sort((a, b) => {
return a[1] - b[1]
})
.forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
items
some_dict = {"one": 1, "two": 2, "three": 3}
# one 1
# two 2
# three 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.items())
for key, value in some_dict.items():
print(f"{key} {value}")
entries
const someDict = { one: 1, two: 2, three: 3 }
// one 1
// two 2
// three 3
Object.entries(someDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
in
some_dict = {"one": 1, "two": 2, "three": 3}
# one is in the dict
if "one" in some_dict:
print("one is in the dict")
# four is not in the dict
if "four" not in some_dict:
print("four is not in the dict")
hasOwnProperty
const someDict = { one: 1, two: 2, three: 3 }
// one is in the dict
if (someDict.hasOwnProperty('one')) {
console.log('one is in the dict')
}
// four is not in the dict
if (!someDict.hasOwnProperty('four')) {
console.log('four is not in the dict')
}
original_dict = {"one": 1, "two": 2}
original_dict["three"] = 3
# one 1
# two 2
# three 3
for key, value in original_dict.items():
print(f"{key} {value}")
const originalDict = { one: 1, two: 2 }
originalDict.three = 3
// one 1
// two 2
// three 3
Object.entries(originalDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
Unpacking
original_dict = {"one": 1, "two": 2}
new_dict = {**original_dict, "three": 3}
original_dict["one"] = 100
# one 1
# two 2
# three 3
for key, value in new_dict.items():
print(f"{key} {value}")
Spread
const originalDict = { one: 1, two: 2 }
const newDict = { ...originalDict, three: 3 }
originalDict.one = 100
// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
keys
some_dict = {"one": 1, "two": 2, "three": 3}
# one
# two
# three
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.keys())
for x in some_dict.keys():
print(x)
keys
const someDict = { one: 1, two: 2, three: 3 }
// one
// two
// three
Object.keys(someDict).forEach(element => {
console.log(element)
})
values
some_dict = {"one": 1, "two": 2, "three": 3}
# 1
# 2
# 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.values())
for x in some_dict.values():
print(x)
values
const someDict = { one: 1, two: 2, three: 3 }
// 1
// 2
// 3
Object.values(someDict).forEach(element => {
console.log(element)
})
del
some_dict = {"one": 1, "two": 2, "three": 3}
del some_dict["two"]
# one 1
# three 3
for key, value in some_dict.items():
print(f"{key} {value}")
delete
const someDict = { one: 1, two: 2, three: 3 }
delete someDict.two
Object.entries(someDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
get
some_dict = {"one": 1, "two": 2, "three": 3}
# some_dict["four"] will be KeyError
# Doesn't exist
print(some_dict.get("five", "Doesn't exist"))
||
const someDict = { one: 1, two: 2, three: 3 }
// Doesn't exist
console.log(someDict.five || "Doesn't exist")
Dictionary Comprehensions
original_list = {"one": 1, "two": 2}
# {"one": 1, "two": 4}
new_list = {key: value * value for key, value in original_list.items()}
# one 1
# two 4
for key, value in new_list.items():
print(f"{key} {value}")
entries
const originalDict = { one: 1, two: 2 }
const newDict = {}
Object.entries(originalDict).forEach(element => {
// newDict.element[0] doesn't work - for variable key use []
newDict[element[0]] = element[1] * element[1]
})
// one 1
// two 4
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
copy
original_dict = {"one": 1, "two": 2, "three": 3}
new_dict = original_dict.copy()
original_dict["one"] = 100
# one 1
# two 2
# three 3
for key, value in new_dict.items():
print(f"{key} {value}")
Spread
const originalDict = { one: 1, two: 2, three: 3 }
const newDict = { ...originalDict }
originalDict.one = 100
// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
json.dumps
import json
some_dict = {"one": 1, "two": 2, "three": 3}
# {
# "one": 1,
# "two": 2,
# "three": 3
# }
print(json.dumps(some_dict, indent=2))
JSON.stringify
const someDict = { one: 1, two: 2, three: 3 }
// {
// "one": 1,
// "two": 2,
// "three": 3
// }
console.log(JSON.stringify(someDict, null, 2))
json.loads
import json
some_json = """{
"one": 1,
"two": 2,
"three": 3
}"""
dict_from_json = json.loads(some_json)
# 2
print(dict_from_json["two"])
JSON.parse
const someJson = `{
"one": 1,
"two": 2,
"three": 3
}`
const dictFromJson = JSON.parse(someJson)
// 2
console.log(dictFromJson.two)
some_variable = 2
some_dict = {(some_variable + 1): "three"}
# three
print(some_dict[3])
Computed Property Names
const someVariable = 2
const someDict = { [someVariable + 1]: 'three' }
// three
console.log(someDict[3])
def add(x, y):
print(f"Adding {x} and {y}")
return x + y
# Adding 1 and 2
# 3
print(add(1, 2))
const add = (x, y) => {
console.log(`Adding ${x} and ${y}`)
return x + y
}
// Adding 1 and 2
// 3
console.log(add(1, 2))
def add(a, b, c):
return a + b + c
# 6
print(add(b=1, a=2, c=3))
const add = ({ a, b, c }) => {
return a + b + c
}
// 6
console.log(
add({
b: 1,
a: 2,
c: 3
})
)
def greet(name, word="Hello"):
print(f"{word} {name}")
# Hello World
greet("World")
# Goodbye World
greet("World", "Goodbye")
Default Parameters
const greet = (name, word = 'Hello') => {
console.log(`${word} ${name}`)
}
// Hello World
greet('World')
// Goodbye World
greet('World', 'Goodbye')
def greet(name="World", word="Hello"):
print(f"{word} {name}")
# Goodbye World
greet(word="Goodbye")
# Hello Programming
greet(name="Programming")
Default Value
const greet = ({ name = 'World', word = 'Hello' }) => {
console.log(`${word} ${name}`)
}
// Goodbye World
greet({ word: 'Goodbye' })
// Hello Programming
greet({ name: 'Programming' })
Arbitrary Argument Lists
def positional_args(a, b, *args):
print(a)
print(b)
for x in args:
print(x)
# 1
# 2
# 3
# 4
positional_args(1, 2, 3, 4)
Rest Parameters
const positionalArgs = (a, b, ...args) => {
console.log(a)
console.log(b)
args.forEach(element => {
console.log(element)
})
}
// 1
// 2
// 3
// 4
positionalArgs(1, 2, 3, 4)
Keyword Arguments
def func_1(**kwargs):
for key, value in kwargs.items():
print(f"{key} {value}")
def func_2(x, *args, **kwargs):
print(x)
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key} {value}")
# one 1
# two 2
func_1(one=1, two=2)
# 1
# 2
# 3
# a 4
# b 5
func_2(1, 2, 3, a=4, b=5)
Rest Parameters
const func1 = kwargs => {
Object.entries(kwargs).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
}
// ...args must be the last argument
const func2 = (x, kwargs, ...args) => {
console.log(x)
args.forEach(element => {
console.log(element)
})
Object.entries(kwargs).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
}
// one 1
// two 2
func1({ one: 1, two: 2 })
// 1
// 2
// 3
// a 4
// b 5
func2(1, { a: 4, b: 5 }, 2, 3)
Classes
class Duck:
def __init__(self, name):
self.name = name
def fly(self):
print(f"{self.name} can fly")
# not @classmethod: call a method on an instance
# duck = Duck(...)
# duck.create(...)
#
# @classmethod: call a method on a class
# Duck.create(...)
@classmethod
def create(cls, name, kind):
if kind == "mallard":
return MallardDuck(name)
elif kind == "rubber":
return RubberDuck(name)
else:
# cls = Duck
return cls(name)
class MallardDuck(Duck):
# @property:
# use duck.color instead of duck.color()
@property
def color(self):
return "green"
class RubberDuck(Duck):
def __init__(self, name, eye_color="black"):
super().__init__(name)
self.eye_color = eye_color
def fly(self):
super().fly()
print(f"Just kidding, {self.name} cannot fly")
@property
def color(self):
return "yellow"
regularDuck = Duck("reggie")
# reggie can fly
regularDuck.fly()
mallardDuck = Duck.create("mal", "mallard")
# mal
print(mallardDuck.name)
# green
print(mallardDuck.color)
rubberDuck = RubberDuck("vic", "blue")
# vic can fly
# Just kidding, vic cannot fly
rubberDuck.fly()
# yellow
print(rubberDuck.color)
# blue
print(rubberDuck.eye_color)
Classes
, Method Definitions
, static
, get
, super
class Duck {
constructor(name) {
this.name = name
}
fly() {
console.log(`${this.name} can fly`)
}
// not static: call a method on an instance
// const duck = new Duck(...)
// duck.create(...)
//
// static: call a method on a class
// Duck.create(...)
static create(name, kind) {
if (kind === 'mallard') {
return new MallardDuck(name)
} else if (kind === 'rubber') {
return new RubberDuck(name)
} else {
// this = Duck
return new this(name)
}
}
}
class MallardDuck extends Duck {
// get:
// use duck.color instead of duck.color()
get color() {
return 'green'
}
}
class RubberDuck extends Duck {
constructor(name, eyeColor = 'black') {
super(name)
this.eyeColor = eyeColor
}
fly() {
super.fly()
console.log(`Just kidding, ${this.name} cannot fly`)
}
get color() {
return 'yellow'
}
}
const regularDuck = new Duck('reggie')
// reggie can fly
regularDuck.fly()
const mallardDuck = Duck.create('mal', 'mallard')
// mal
console.log(mallardDuck.name)
// green
console.log(mallardDuck.color)
rubberDuck = new RubberDuck('vic', 'blue')
// vic can fly
// Just kidding, vic cannot fly
rubberDuck.fly()
// yellow
console.log(rubberDuck.color)
// blue
console.log(rubberDuck.eyeColor)