JavaScript → Python Cheatsheet

Quick reference for JS developers learning Python

Variables

JavaScriptPythonNotes
const x = 5;x = 5No const/let/var needed
let y = 10;y = 10Variables are mutable by default
const arr = [1, 2, 3];arr = [1, 2, 3]Lists are always mutable

Data Types

JavaScriptPythonNotes
true / falseTrue / FalseCapital first letter
nullNone
undefinedNonePython has only None
'string' or "string"'string' or "string"Same! Also '''multiline'''
[1, 2, 3][1, 2, 3]Arrays → Lists
{ key: 'value' }{ 'key': 'value' }Objects → Dicts (keys need quotes)
new Set([1, 2, 3]){1, 2, 3} or set([1, 2, 3])
new Map()dict() or {}

Operators

JavaScriptPythonNotes
=====No triple equals in Python
!==!=
&&and
||or
!valuenot value
a ?? ba if a is not None else bNullish coalescing
cond ? a : ba if cond else bTernary operator
x++x += 1No ++ or -- operators
x--x -= 1
****Same! Exponentiation
//# (comment) or // (floor div)// is floor division in Python

Loops

JavaScriptPythonNotes
for (let i = 0; i < 5; i++)for i in range(5):
for (let i = 1; i < 10; i++)for i in range(1, 10):Start at 1
for (let i = 0; i < 10; i += 2)for i in range(0, 10, 2):Step by 2
for (let i = 10; i > 0; i--)for i in range(10, 0, -1):Count down
for (const item of arr)for item in arr:
for (const [i, item] of arr.entries())for i, item in enumerate(arr):
for (const key in obj)for key in obj:
for (const [k, v] of Object.entries(obj))for k, v in obj.items():
while (condition)while condition:No parentheses needed
arr.forEach(x => console.log(x))for x in arr: print(x)

Functions

JavaScriptPythonNotes
function add(a, b) { return a + b; }def add(a, b): return a + b
const add = (a, b) => a + b;add = lambda a, b: a + bArrow → Lambda
function greet(name = 'World')def greet(name='World'):Default params
function sum(...nums)def sum(*nums):Rest params → *args
function config({a, b})def config(**kwargs):Destructuring → **kwargs
async function fetch()async def fetch():
await promiseawait coroutine

Conditionals

JavaScriptPythonNotes
if (x > 5) { ... }if x > 5: ...No parentheses, use colon
} else if (x > 3) {elif x > 3:elif, not else if
} else {else:
switch (x) { case 1: ... }match x: case 1: ...Python 3.10+ match

Arrays → Lists

JavaScriptPythonNotes
arr.lengthlen(arr)
arr.push(x)arr.append(x)
arr.pop()arr.pop()Same!
arr.shift()arr.pop(0)Pop from front
arr.unshift(x)arr.insert(0, x)Insert at front
arr.slice(1, 3)arr[1:3]Slicing syntax
arr.slice(1)arr[1:]From index to end
arr.slice(-2)arr[-2:]Last 2 elements
arr.splice(i, 1)del arr[i] or arr.pop(i)Remove at index
arr.concat(other)arr + otherOr arr.extend(other)
arr.indexOf(x)arr.index(x)Raises ValueError if not found
arr.includes(x)x in arr
arr.find(x => x > 5)next((x for x in arr if x > 5), None)
arr.findIndex(x => x > 5)next((i for i, x in enumerate(arr) if x > 5), -1)
arr.filter(x => x > 5)[x for x in arr if x > 5]List comprehension
arr.map(x => x * 2)[x * 2 for x in arr]List comprehension
arr.reduce((a, b) => a + b, 0)sum(arr)Or functools.reduce()
arr.some(x => x > 5)any(x > 5 for x in arr)
arr.every(x => x > 5)all(x > 5 for x in arr)
arr.sort()arr.sort() or sorted(arr)sort() mutates, sorted() returns new
arr.sort((a, b) => a - b)arr.sort() or sorted(arr)Numbers sort correctly by default
arr.sort((a, b) => a.localeCompare(b))arr.sort() or sorted(arr)Strings sort correctly by default
arr.reverse()arr.reverse() or arr[::-1]reverse() mutates
arr.join(', ')', '.join(arr)Separator comes first
[...arr]arr.copy() or arr[:]Shallow copy
[...arr1, ...arr2][*arr1, *arr2]Spread → Unpack

Strings

JavaScriptPythonNotes
str.lengthlen(str)
str.charAt(i)str[i]
str.substring(1, 3)str[1:3]
str.slice(1)str[1:]
str.split(',')str.split(',')Same!
str.trim()str.strip()
str.trimStart()str.lstrip()
str.trimEnd()str.rstrip()
str.toLowerCase()str.lower()
str.toUpperCase()str.upper()
str.startsWith('a')str.startswith('a')Lowercase 'w'
str.endsWith('z')str.endswith('z')Lowercase 'w'
str.includes('x')'x' in str
str.indexOf('x')str.find('x')Returns -1 if not found
str.replace('a', 'b')str.replace('a', 'b')Same!
str.replaceAll('a', 'b')str.replace('a', 'b')Python replaces all by default
`Hello ${name}`f'Hello {name}'Template literals → f-strings
str.repeat(3)str * 3
str.padStart(5, '0')str.zfill(5) or str.rjust(5, '0')

Objects → Dicts

JavaScriptPythonNotes
{ key: 'value' }{ 'key': 'value' }Keys need quotes
obj.keyobj['key'] or obj.get('key')get() returns None if missing
obj.key = 'new'obj['key'] = 'new'
delete obj.keydel obj['key']
'key' in obj'key' in objSame!
Object.keys(obj)obj.keys() or list(obj.keys())
Object.values(obj)obj.values() or list(obj.values())
Object.entries(obj)obj.items()
{ ...obj1, ...obj2 }{ **obj1, **obj2 }Spread → Unpack
const { a, b } = obja, b = obj['a'], obj['b']No destructuring shorthand

Math

JavaScriptPythonNotes
Math.floor(x)int(x) or x // 1// is floor division
Math.ceil(x)math.ceil(x)import math
Math.round(x)round(x)
Math.abs(x)abs(x)
Math.max(a, b, c)max(a, b, c)
Math.min(a, b, c)min(a, b, c)
Math.pow(x, y)x ** y
Math.sqrt(x)x ** 0.5 or math.sqrt(x)
Math.random()random.random()import random
Math.floor(Math.random() * 10)random.randint(0, 9)
parseInt('42')int('42')
parseFloat('3.14')float('3.14')
Number.isInteger(x)isinstance(x, int)
Number.isNaN(x)math.isnan(x)
Infinityfloat('inf')

Type Checking

JavaScriptPythonNotes
typeof x === 'string'isinstance(x, str)
typeof x === 'number'isinstance(x, (int, float))
typeof x === 'boolean'isinstance(x, bool)
typeof x === 'object'isinstance(x, dict)Or list, etc.
typeof x === 'function'callable(x)
Array.isArray(x)isinstance(x, list)
x instanceof Dateisinstance(x, datetime)from datetime import datetime

Error Handling

JavaScriptPythonNotes
try { ... } catch (e) { ... }try: ... except Exception as e: ...
throw new Error('msg')raise Exception('msg')
finally { ... }finally: ...Same concept

Classes

JavaScriptPythonNotes
class Dog { }class Dog:
constructor(name) { this.name = name; }def __init__(self, name): self.name = name
this.nameself.nameExplicit self
class Dog extends Animalclass Dog(Animal):
super()super().__init__()
static method() { }@staticmethod def method():
get name() { return this._name; }@property def name(self):

Common Patterns

JavaScriptPythonNotes
arr.length === 0len(arr) == 0 or not arrEmpty check
str === ''str == '' or not strEmpty string check
x === null || x === undefinedx is None
x !== null && x !== undefinedx is not None
Math.max(...arr)max(arr)No spread needed
Math.min(...arr)min(arr)
arr.flat()[x for sub in arr for x in sub]Flatten one level
[...new Set(arr)]list(set(arr))Remove duplicates
Object.assign({}, obj)obj.copy() or dict(obj)Shallow copy
JSON.stringify(obj)json.dumps(obj)import json
JSON.parse(str)json.loads(str)import json