JavaScript for Python Developers a Practical Comparison
A guide for Python developers learning JavaScript: truthiness, numbers, the in operator, sorting, this and async. Side by side with the surprises explained.

A Python developer picking up JavaScript can write working code in an afternoon, because the two languages share most of their ideas: dynamic types, first-class functions, closures, exceptions, list and dictionary literals, string interpolation. The trouble comes from the places where the same-looking code means something different. An empty list is false in Python and true in JavaScript, in checks membership in one language and keys in the other, and a default sort treats numbers as text. Each is a small surprise, and together they account for most of the first month's bugs. This post compares the two side by side in the places where a Python habit gives the wrong answer in JavaScript, with the output of each snippet, and ends with the differences in how programs run: the event loop and promises instead of asyncio. The JavaScript runs on Node.js 24, and the Python is Python 3.13, with outputs written from the language rules.
The vocabulary map
| Python | JavaScript | Notes |
|---|---|---|
list | Array | Methods are on the array: arr.push(x), not list.append |
dict | Object or Map | Object keys are strings or symbols; Map takes any key |
tuple | Array, usually frozen | No tuple type |
set | Set | Same idea, with insertion order |
None | null and undefined | Two values, not one |
True, False | true, false | Lower case |
len(x) | x.length | A property, not a function |
print() | console.log() | |
def f(x): | function f(x) {} or (x) => {} | |
self | this | Not a parameter, and set by how a function is called |
import x | import x from "x" | ES modules |
Truthiness
This is the first surprise, and it causes silent bugs.
for value in [[], {}, "", "0", 0, None, float("nan")]:
print(repr(value), bool(value))[] False
{} False
'' False
'0' True
0 False
None False
nan Truefor (const value of [[], {}, "", "0", 0, null, undefined, NaN]) {
console.log(JSON.stringify(value), Boolean(value));
}[] true
{} true
"" false
"0" true
0 false
null false
undefined false
null falseAn empty array and an empty object are truthy in JavaScript, so if (items) is not a check for a non-empty list: write if (items.length > 0). The last line prints null for the value NaN, because JSON.stringify(NaN) gives the text null, and its Boolean is false. That is another difference: NaN is falsy in JavaScript and truthy in Python. The falsy values in JavaScript are false, 0, -0, 0n, "", null, undefined and NaN, and everything else is truthy.
Numbers
JavaScript has one number type, a 64-bit floating-point value, and a separate BigInt for large integers.
print(7 / 2, 7 // 2, 2 ** 100, 0.1 + 0.2)3.5 3 1267650600228229401496703205376 0.30000000000000004console.log(7 / 2, Math.trunc(7 / 2), 2 ** 100, 0.1 + 0.2);
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 === 2 ** 53 + 1);
console.log(2n ** 100n, typeof 5, typeof 5n);
console.log(typeof (5 / 1), Number.isInteger(5.0), 7 % 3, -7 % 3);3.5 3 1.2676506002282294e+30 0.30000000000000004
9007199254740991 true
1267650600228229401496703205376n number bigint
number true 1 -1Division always produces a float, and there is no // operator: use Math.trunc() or Math.floor(). Integers above 2 to the power 53 lose precision, which is why 2 ** 53 === 2 ** 53 + 1 is true. Use BigInt literals, with the n suffix, when you need exact large integers, and remember that it cannot be mixed with ordinary numbers. The remainder operator keeps the sign of the left operand, so -7 % 3 is -1, where Python gives 2.
Equality and comparison
print([1, 2] == [1, 2], "1" == 1, None == 0, 1 < 2 < 3)True False False Trueconsole.log([1, 2] === [1, 2], "1" == 1, null == 0, 1 < 2 < 3, 3 > 2 > 1);false true false true falseArrays and objects are compared by identity in JavaScript, so two separate arrays with the same items are not equal. Python compares by value. Use ===, which never converts types, and avoid ==, which converts, so "1" == 1 is true. The chained comparison 3 > 2 > 1 evaluates (3 > 2) > 1, which is true > 1, which is false, and does not mean what it means in Python. To compare arrays by content, compare their items, or use isDeepStrictEqual from node:util.
in, for and membership
print("a" in {"a": 1}, 1 in [5, 6], "ell" in "hello")
for i in [10, 20]:
print(i)True False True
10
20console.log("a" in { a: 1 }, 1 in [5, 6], "hello".includes("ell"));
for (const i in [10, 20]) console.log(i, typeof i);
for (const v of [10, 20]) console.log(v);
console.log([5, 6].includes(5));true true true
0 string
1 string
10
20
trueThe facts to remember: in tests whether a key or index exists, so 1 in [5, 6] is true because index 1 exists, and for membership of a value you use includes(). for...in loops over keys as strings, and for...of loops over values, like Python's for. Use for...of, and use .entries() for an index and value, in place of enumerate.
Sorting
print(sorted([10, 9, 1, 100]))[1, 9, 10, 100]console.log([10, 9, 1, 100].sort());
console.log([10, 9, 1, 100].sort((a, b) => a - b));
console.log(["b", "a", "C"].sort(), ["b", "a", "C"].toSorted((a, b) => a.localeCompare(b)));[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 'C', 'a', 'b' ] [ 'a', 'b', 'C' ]sort() without an argument converts items to strings and compares them as text, so 10 comes before 9. Always pass a comparator for numbers. Strings compare by UTF-16 code units, so uppercase sorts before lowercase, and localeCompare gives the order a reader expects. sort() also changes the array in place and returns it, where sorted() returns a new list; toSorted() is the copying form.
Negative indexes and slicing
items = ["a", "b", "c", "d"]
print(items[-1], items[1:3], items[::-1], "hello"[1:3])d ['b', 'c'] ['d', 'c', 'b', 'a'] elconst items = ["a", "b", "c", "d"];
console.log(items[-1], items.at(-1), items.slice(1, 3), items.toReversed(), "hello".slice(1, 3));undefined d [ 'b', 'c' ] [ 'd', 'c', 'b', 'a' ] elitems[-1] is not an error, and it is undefined, because -1 is looked up as a property name. Use .at(-1). There is no slice syntax, so use the slice(start, end) method, which accepts negative numbers, and toReversed() or a copy and reverse() for the step of -1.
Default arguments
Python evaluates a default value once, when the function is defined, and JavaScript evaluates it on each call.
def add(x, items=[]):
items.append(x)
return items
print(add(1), add(2))[1, 2] [1, 2]function add(x, items = []) {
items.push(x);
return items;
}
console.log(add(1), add(2));[ 1 ] [ 2 ]The classic Python trap, the shared mutable default, does not exist in JavaScript, since a new array is created for every call. The Python habit of using None as a default and creating the list inside is unnecessary, and a null default is not the same as no argument: undefined triggers the default, and null does not.
Objects, dictionaries and key order
const lookup = { b: 1, 2: "two", a: 3, 1: "one" };
console.log(Object.keys(lookup));
console.log(lookup.missing, lookup.missing ?? "default", "missing" in lookup);
const map = new Map([[1, "number key"], ["1", "string key"]]);
console.log(map.get(1), map.get("1"), map.size);[ '1', '2', 'b', 'a' ]
undefined default false
number key string key 2An object's keys are strings, and integer-like keys come first in ascending order, followed by the other keys in insertion order. That differs from a Python dictionary, which keeps pure insertion order. Reading a missing key gives undefined and not a KeyError, and ?? provides a default like dict.get(key, default). When keys are not strings, or when order and size matter, use a Map, which keeps both key types apart.
this and self
self in Python is an explicit parameter that is always the instance. this in JavaScript is set by how the function is called, and a method that is detached from its object loses it.
class Counter {
count = 0;
increment() {
this.count += 1;
return this.count;
}
}
const counter = new Counter();
console.log(counter.increment());
const detached = counter.increment;
try {
detached();
} catch (e) {
console.log(e.name);
}
console.log([1, 2].map(() => counter.increment()));1
TypeError
[ 2, 3 ]In Python a bound method such as counter.increment carries its instance with it, and passing it to map works. In JavaScript you must bind it, or wrap it in an arrow function, as the interview post on this explains.
Strings and text
const name = "Ada";
console.log(`Hello, ${name}! 2 + 2 = ${2 + 2}`);
console.log("a,b,c".split(","), ["a", "b"].join("-"), " pad ".trim());
console.log("๐".length, [..."๐"].length, "straรe".toUpperCase());Hello, Ada! 2 + 2 = 4
[ 'a', 'b', 'c' ] a-b pad
2 1 STRASSETemplate literals with backticks replace f-strings. The join method is on the array and not on the separator, so it reads ["a", "b"].join("-"). String length counts UTF-16 code units, so an emoji has length 2, where Python counts code points and gives 1. Spread into an array to count code points, or use Intl.Segmenter for characters a reader sees.
Comprehensions and built-in functions
| Python | JavaScript |
|---|---|
[x * 2 for x in xs if x > 1] | xs.filter((x) => x > 1).map((x) => x * 2) |
sum(xs) | xs.reduce((a, b) => a + b, 0) |
any(...), all(...) | xs.some(...), xs.every(...) |
enumerate(xs) | xs.entries() |
zip(a, b) | a.map((x, i) => [x, b[i]]) |
range(5) | Array.from({ length: 5 }, (_, i) => i) |
sorted(xs, key=f) | xs.toSorted((a, b) => f(a) - f(b)) |
type(x) | typeof x |
d.get(k, 0) | d[k] ?? 0 |
Async: promises start immediately
Python coroutines do nothing until awaited. A JavaScript promise starts its work when it is created.
function load() {
console.log("load started");
return new Promise((resolve) => setTimeout(() => resolve("data"), 10));
}
const promise = load();
console.log("after creating the promise");
console.log(await promise);load started
after creating the promise
dataCalling load() started the work at once, as asyncio.create_task would, and not lazily as a bare async def call does in Python. async functions in JavaScript also run synchronously until their first await. There is no asyncio.run: the event loop is part of the runtime, and a module can use await at the top level.
Exceptions
try {
JSON.parse("{bad");
} catch (error) {
if (error instanceof SyntaxError) {
console.log("syntax problem");
} else {
throw error;
}
}
try {
throw "a plain string";
} catch (error) {
console.log(typeof error);
}syntax problem
stringThere is one catch block with no type filter, and you branch inside it with instanceof, rethrowing what you do not handle. JavaScript lets you throw any value, so always throw Error objects, which carry a stack trace.
Practical rules we follow
Use const and let, never var. Use ===. Write .length > 0 for emptiness. Use .at(-1) for the last item. Pass a comparator to sort() for numbers. Use Map for non-string keys. Use arrow functions for callbacks. Run a linter, since it catches several of these before they run. And read the output: much of the surprise is small differences that print differently.
Where the Python comparison stops
The two languages differ in much more than syntax: a single-threaded event loop instead of threads with a lock, prototype-based classes, no operator overloading, a different standard library and a huge package ecosystem with different norms. The class syntax looks familiar and works differently underneath, as the post on prototypal inheritance shows. The reference is in the MDN JavaScript guide and the Python documentation.


