JavaScript for Pythonistas Cheat Sheet

Already know Python? This cheat sheet maps what you know to modern JavaScript, side by side, so you can write, read, and review JavaScript with the right mental models. You can also download the information as a printable cheat sheet:

Free Bonus: JavaScript for Pythonistas Cheat Sheet

Get the JavaScript for Pythonistas Cheat Sheet (PDF), a printable reference to Python-to-JavaScript equivalents for None and null, numbers, f-strings, collections, truthiness, loops, classes, exceptions, async, modules, and common traps:

JavaScript for Pythonistas Cheat Sheet

Want a guided path instead of a reference? Start learning at realjs.com.

Values & Types

  • Python’s None splits into null and undefined
  • One number type covers int and float
  • Use bigint (10n) for huge integers
Language: JavaScript Filename: None vs null & undefined
// Python: None
const n = null;      // Empty on purpose
let u;               // undefined: not set
n == null            // true (also for u)
n ?? "default"       // "default"
n?.name              // undefined, no error
Language: JavaScript Filename: int & float vs number
// Python: 7 / 2, 7 // 2
7 / 2                // 3.5
Math.trunc(7 / 2)    // 3
-7 % 3               // -1 (Python: 2)
2 ** 53 + 1          // 9007199254740992
2n ** 64n            // 18446744073709551616n
Language: JavaScript Filename: f-strings vs Template Literals
// Python: f"Hi, {name}!"
const name = "Ada";
`Hi, ${name}!`       // "Hi, Ada!"
`${2 + 2}`           // "4"
// Python: "-".join(["a", "b"])
["a", "b"].join("-") // "a-b"
// Python: "a-b".split("-")
"a-b".split("-")     // ["a", "b"]

Truthiness & Equality

  • Empty [] and {} are truthy in JavaScript
  • Prefer ===; == null is the one handy ==
  • Objects compare by identity, always
Language: JavaScript Filename: Truthiness
// Python: bool([]) is False
Boolean([])          // true
Boolean({})          // true
Boolean(new Map())   // true
Boolean("")          // false
Boolean("0")         // true
Boolean(NaN)         // false
// Python: if not xs:
if (xs.length === 0) {}
Language: JavaScript Filename: == and is vs ===
// Python: 1 == 1.0 is True
1 === 1.0            // true
"1" == 1             // true (avoid)
"1" === 1            // false
// Python: [1] == [1] is True
[1] === [1]          // false
null === undefined   // false

Collections

  • list is Array, dict is Object or Map
  • set is Set, and tuple has no twin
  • Copy before you mutate: [...xs], { ...d }
Language: JavaScript Filename: list vs Array
const xs = [1, 2, 3];
xs.push(4);          // xs.append(4)
xs.length            // len(xs): 4
xs.at(-1)            // xs[-1]: 4
xs.slice(-2)         // xs[-2:]: [3, 4]
xs.includes(4)       // 4 in xs: true
4 in xs              // false! Checks index
Language: JavaScript Filename: dict vs Object & Map
const d = { a: 1, b: 2 };
d.c = 3;             // d["c"] = 3
"a" in d             // true (key check)
delete d.c;          // del d["c"]
Object.entries(d)    // d.items()
// [["a", 1], ["b", 2]]
const m = new Map([["a", 1]]);
m.get("a")           // 1 (any key type)
Language: JavaScript Filename: set vs Set
const s = new Set([1, 1, 2]);
s.size               // len(s): 2
s.add(3);            // s.add(3)
s.has(2)             // 2 in s: true
[...s]               // list(s): [1, 2, 3]
Language: JavaScript Filename: Comprehensions vs map & filter
// [x * 2 for x in xs if x > 1]
xs.filter((x) => x > 1).map((x) => x * 2)
// [4, 6, 8]

// {k: v * 2 for k, v in d.items()}
Object.fromEntries(
  Object.entries(d)
    .map(([k, v]) => [k, v * 2]),
);                   // { a: 2, b: 4 }

Loops & Functions

  • Loop with for...of, not for...in
  • Options objects replace **kwargs
Language: JavaScript Filename: for, enumerate, range & zip
// for x in xs
for (const x of xs) {}
// for i, x in enumerate(xs)
for (const [i, x] of xs.entries()) {}
// for i in range(3)
for (let i = 0; i < 3; i++) {}
const ys = ["a", "b", "c"];
xs.map((x, i) => [x, ys[i]])
// like zip(), but pads with undefined
Array.from({ length: 3 }, (_, i) => i)
// list(range(3)): [0, 1, 2]
Language: JavaScript Filename: *args & **kwargs vs Rest & Spread
// def f(a, b=2, *args)
function f(a, b = 2, ...args) {
  return [a, b, args];
}
f(1)                 // [1, 2, []]
f(1, 5, 6, 7)        // [1, 5, [6, 7]]
f(...xs)             // [1, 2, [3, 4]]

// def g(*, x, y=0)
function g({ x, y = 0 }) {
  return x + y;
}
g({ x: 1 })          // 1
({ ...d, e: 5 })     // {**d, "e": 5}

Strings, Numbers & Sorting

  • Methods return new values; strings are immutable
  • sort() changes the array and compares as text
  • Use toSorted() for Python’s sorted()
Language: JavaScript Filename: Strings
const s = " Hi, Ada ";
s.trim()             // s.strip(): "Hi, Ada"
s.includes("Ada")    // "Ada" in s: true
s.startsWith(" Hi")  // true
"ab".repeat(3)       // "ab" * 3: "ababab"
Language: JavaScript Filename: Sorting
const n = [3, 1, 2];
// sorted(n)
n.toSorted((a, b) => a - b) // [1, 2, 3]
// n.sort() sorts as text and mutates
[10, 9, 1].sort()    // [1, 10, 9]
Language: JavaScript Filename: Convert & Round
Number("42")         // int("42"): 42
Number("4x")         // NaN, not ValueError
String(42)           // str(42): "42"
(3.14159).toFixed(2) // round(x, 2): "3.14"
Math.round(2.5)      // 3 (Python: 2)
Language: JavaScript Filename: Missing Keys & Defaults
const d = { a: 1 };
d.b                  // undefined: no error
d.b ?? 0             // d.get("b", 0): 0
d.a ?? 0             // 1
Language: JavaScript Filename: Destructuring vs Unpacking
// head, *tail = [3, 1, 2]
const [head, ...tail] = [3, 1, 2];
// head is 3, tail is [1, 2]
const { a, z = 9 } = d;  // a is 1, z is 9
Language: JavaScript Filename: Generators
// def count(n): yield from range(n)
function* count(n) {
  for (let i = 0; i < n; i++) yield i;
}
[...count(3)]   // list(count(3)): [0, 1, 2]

Async, Modules & Tooling

  • JavaScript has a built-in event loop: no asyncio.run()
  • Promises start running as soon as you call them
Language: JavaScript Filename: asyncio vs async & await
// asyncio.gather(a(), b())
const [x, y] = await Promise.all([
  a(),
  b(),
]);                  // ["a", "b"]
// await asyncio.sleep(1)
await new Promise(
  (r) => setTimeout(r, 1000),
);
Language: JavaScript Filename: Imports & Exports
// from math import add
import { add } from "./math.js";
// import math
import * as math from "./math.js";
// Nothing is private by default; export it
export const PI = 3.14159;
Language: JavaScript Filename: print vs console.log
console.log("Total:", 42);  // print()
console.log(d);      // { a: 1, b: 2 }
console.error("Oops");      // To stderr
JSON.stringify(d)    // '{"a":1,"b":2}'
`${d}`               // "[object Object]"

Classes & Errors

  • No self parameter: this is implicit
  • this is set by how you call a method
  • Instantiate with new
Language: JavaScript Filename: Classes: self vs this
// class Dog: def __init__(self, name)
class Dog {
  constructor(name) {
    this.name = name;   // self.name = name
  }
  bark() {
    return `${this.name}: woof`;
  }
}
const rex = new Dog("Rex");  // Dog("Rex")
rex.bark()           // "Rex: woof"
Language: JavaScript Filename: Losing this
const bark = rex.bark;
bark()               // TypeError
rex.bark.bind(rex)() // "Rex: woof"
Language: JavaScript Filename: Exceptions
// try / except / finally / raise
try {
  throw new RangeError("bad");
} catch (e) {
  // except RangeError as e
  if (!(e instanceof RangeError)) throw e;
  console.log(e.message);  // bad
} finally {
  console.log("done");     // done
}

Traps for Pythonistas

  • JavaScript rarely raises: it returns undefined or NaN
  • Operators don’t overload: "ab" * 3 is NaN
Language: JavaScript Filename: Silent Failures
const xs = [1, 2, 3];
xs[-1]               // undefined
xs.at(-1)            // 3
"ab" * 3             // NaN
"ab".repeat(3)       // "ababab"
Language: JavaScript Filename: Default Arguments
// Python: def add(x, l=[]) shares one list
function add(x, list = []) {
  list.push(x);
  return list;
}
add(1)               // [1]
add(2)               // [2] (fresh each call)
Language: JavaScript Filename: Keys Are Strings
const o = {};
o[1] = "x";
o["1"]               // "x"
Object.keys(o)       // ["1"]
const m = new Map([[1, "a"]]);
m.get("1")           // undefined
m.get(1)             // "a"
Language: JavaScript Filename: Key Order
// Integer-like keys jump to the front
({ b: 1, 2: 1, 1: 1 })
// { '1': 1, '2': 1, b: 1 }
Language: JavaScript Filename: No Keyword Arguments
// Python: area(w=3, h=2)
function area({ w, h = 1 }) {
  return w * h;
}
area({ h: 2, w: 3 })   // 6
area({ w: 3 })         // 3
Language: JavaScript Filename: json.dumps vs JSON.stringify
// Python: '{"a": 1, "b": [1, 2]}'
JSON.stringify({ a: 1, b: [1, 2] })
// '{"a":1,"b":[1,2]}'
JSON.stringify({ a: 1 }, null, 2)
// indent=2: '{\n  "a": 1\n}'
JSON.stringify({ u: undefined })  // "{}"
Language: JavaScript Filename: any, all, sum, max & type
const v = [1, 2, 3];
v.some((x) => x > 2)        // any(...): true
v.every((x) => x > 0)       // all(...): true
v.reduce((a, x) => a + x, 0) // sum(v): 6
Math.max(...v)       // max(v): 3
typeof "a"           // type("a"): "string"

Python Tooling vs npm

Python JavaScript
pip install npm install
.venv/ node_modules/
pyproject.toml package.json
requirements.txt package-lock.json
python script.py node script.js
pytest npm test
uvx / pipx run npx
snake_case camelCase
Language: JavaScript Filename: @property, @staticmethod & _private
class Temp {
  #c = 20;             // _c: private by #
  get f() { return this.#c * 9 / 5 + 32; }
  static zero() { return new Temp(); }
  toString() { return "Temp"; } // __str__
}
new Temp().f           // 68
`${Temp.zero()}`       // "Temp"
Language: JavaScript Filename: or vs || & ??
0 || 5               // 5 (like Python's or)
0 ?? 5               // 0 is kept
"" || "n/a"          // "n/a"
"" ?? "n/a"          // ""

You can download this information as a printable cheat sheet:

Free Bonus: JavaScript for Pythonistas Cheat Sheet

Get the JavaScript for Pythonistas Cheat Sheet (PDF), a printable reference to Python-to-JavaScript equivalents for None and null, numbers, f-strings, collections, truthiness, loops, classes, exceptions, async, modules, and common traps:

JavaScript for Pythonistas Cheat Sheet