Skip to content
jshacks.dev
Fundamentals

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.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Python, npm and Vite logos.

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

PythonJavaScriptNotes
listArrayMethods are on the array: arr.push(x), not list.append
dictObject or MapObject keys are strings or symbols; Map takes any key
tupleArray, usually frozenNo tuple type
setSetSame idea, with insertion order
Nonenull and undefinedTwo values, not one
True, Falsetrue, falseLower case
len(x)x.lengthA property, not a function
print()console.log()
def f(x):function f(x) {} or (x) => {}
selfthisNot a parameter, and set by how a function is called
import ximport x from "x"ES modules

Truthiness

This is the first surprise, and it causes silent bugs.

python
for value in [[], {}, "", "0", 0, None, float("nan")]:
    print(repr(value), bool(value))
Text
[] False
{} False
'' False
'0' True
0 False
None False
nan True
JavaScript
for (const value of [[], {}, "", "0", 0, null, undefined, NaN]) {
  console.log(JSON.stringify(value), Boolean(value));
}
Text
[] true
{} true
"" false
"0" true
0 false
null false
undefined false
null false

An 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.

python
print(7 / 2, 7 // 2, 2 ** 100, 0.1 + 0.2)
Text
3.5 3 1267650600228229401496703205376 0.30000000000000004
JavaScript
console.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);
Text
3.5 3 1.2676506002282294e+30 0.30000000000000004
9007199254740991 true
1267650600228229401496703205376n number bigint
number true 1 -1

Division 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

python
print([1, 2] == [1, 2], "1" == 1, None == 0, 1 < 2 < 3)
Text
True False False True
JavaScript
console.log([1, 2] === [1, 2], "1" == 1, null == 0, 1 < 2 < 3, 3 > 2 > 1);
Text
false true false true false

Arrays 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

python
print("a" in {"a": 1}, 1 in [5, 6], "ell" in "hello")
for i in [10, 20]:
    print(i)
Text
True False True
10
20
JavaScript
console.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));
Text
true true true
0 string
1 string
10
20
true

The 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

python
print(sorted([10, 9, 1, 100]))
Text
[1, 9, 10, 100]
JavaScript
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)));
Text
[ 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

python
items = ["a", "b", "c", "d"]
print(items[-1], items[1:3], items[::-1], "hello"[1:3])
Text
d ['b', 'c'] ['d', 'c', 'b', 'a'] el
JavaScript
const items = ["a", "b", "c", "d"];
console.log(items[-1], items.at(-1), items.slice(1, 3), items.toReversed(), "hello".slice(1, 3));
Text
undefined d [ 'b', 'c' ] [ 'd', 'c', 'b', 'a' ] el

items[-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.

python
def add(x, items=[]):
    items.append(x)
    return items

print(add(1), add(2))
Text
[1, 2] [1, 2]
JavaScript
function add(x, items = []) {
  items.push(x);
  return items;
}

console.log(add(1), add(2));
Text
[ 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

JavaScript
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);
Text
[ '1', '2', 'b', 'a' ]
undefined default false
number key string key 2

An 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.

JavaScript
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()));
Text
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

JavaScript
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());
Text
Hello, Ada! 2 + 2 = 4
[ 'a', 'b', 'c' ] a-b pad
2 1 STRASSE

Template 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

PythonJavaScript
[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.

JavaScript
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);
Text
load started
after creating the promise
data

Calling 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

JavaScript
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);
}
Text
syntax problem
string

There 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.

Taggedpython
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.