Dev Tools

Python \u2194 JavaScript Snippets

Quick reference for common Python patterns and their JavaScript equivalents.

35 snippets
Variable declarationVariables & Types
Python
x = 10
name = "Alice"
JavaScript
let x = 10;
let name = "Alice";
ConstantsVariables & Types
Python
MAX_SIZE = 100  # convention
JavaScript
const MAX_SIZE = 100;
Type checkingVariables & Types
Python
isinstance(x, int)
type(x).__name__
JavaScript
typeof x === "number"
typeof x
None / null / undefinedVariables & Types
Python
x = None
if x is None:
JavaScript
let x = null;
if (x === null) {}
String interpolationVariables & Types
Python
f"Hello, {name}!"
JavaScript
`Hello, ${name}!`
Multi-line stringVariables & Types
Python
"""line1
line2
line3"""
JavaScript
`line1
line2
line3`
List / ArrayCollections
Python
items = [1, 2, 3]
items.append(4)
JavaScript
const items = [1, 2, 3];
items.push(4);
Dictionary / ObjectCollections
Python
d = {"key": "value"}
d["key"]
JavaScript
const d = { key: "value" };
d.key // or d["key"]
DestructuringCollections
Python
a, b, c = [1, 2, 3]
JavaScript
const [a, b, c] = [1, 2, 3];
Spread / unpackCollections
Python
merged = [*a, *b]
JavaScript
const merged = [...a, ...b];
Dict mergeCollections
Python
merged = {**a, **b}
JavaScript
const merged = { ...a, ...b };
SetCollections
Python
s = {1, 2, 3}
s.add(4)
JavaScript
const s = new Set([1, 2, 3]);
s.add(4);
For loopLoops & Iteration
Python
for i in range(10):
    print(i)
JavaScript
for (let i = 0; i < 10; i++) {
  console.log(i);
}
For-eachLoops & Iteration
Python
for item in items:
    print(item)
JavaScript
for (const item of items) {
  console.log(item);
}
EnumerateLoops & Iteration
Python
for i, val in enumerate(items):
    print(i, val)
JavaScript
items.forEach((val, i) => {
  console.log(i, val);
});
List comprehension / mapLoops & Iteration
Python
squares = [x**2 for x in range(10)]
JavaScript
const squares = Array.from(
  {length: 10}, (_, x) => x ** 2
);
FilterLoops & Iteration
Python
evens = [x for x in nums if x % 2 == 0]
JavaScript
const evens = nums.filter(x => x % 2 === 0);
ReduceLoops & Iteration
Python
from functools import reduce
total = reduce(lambda a,b: a+b, nums)
JavaScript
const total = nums.reduce((a, b) => a + b);
Function definitionFunctions
Python
def greet(name):
    return f"Hello, {name}"
JavaScript
function greet(name) {
  return `Hello, ${name}`;
}
Lambda / arrow functionFunctions
Python
double = lambda x: x * 2
JavaScript
const double = (x) => x * 2;
Default argumentsFunctions
Python
def greet(name="World"):
    pass
JavaScript
function greet(name = "World") {}
Rest / *argsFunctions
Python
def func(*args):
    print(args)
JavaScript
function func(...args) {
  console.log(args);
}
Keyword / destructured argsFunctions
Python
def func(**kwargs):
    print(kwargs)
JavaScript
function func({ key, other }) {
  console.log(key, other);
}
If / elseControl Flow
Python
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")
JavaScript
if (x > 10) {
  console.log("big");
} else if (x > 5) {
  console.log("medium");
} else {
  console.log("small");
}
TernaryControl Flow
Python
result = "yes" if x else "no"
JavaScript
const result = x ? "yes" : "no";
Try / except / catchControl Flow
Python
try:
    risky()
except ValueError as e:
    print(e)
JavaScript
try {
  risky();
} catch (e) {
  console.log(e);
}
Class definitionClasses
Python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} barks!"
JavaScript
class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() {
    return `${this.name} barks!`;
  }
}
InheritanceClasses
Python
class Puppy(Dog):
    def __init__(self, name):
        super().__init__(name)
JavaScript
class Puppy extends Dog {
  constructor(name) {
    super(name);
  }
}
Async functionAsync
Python
import asyncio

async def fetch():
    await asyncio.sleep(1)
    return "data"
JavaScript
async function fetchData() {
  await new Promise(r => setTimeout(r, 1000));
  return "data";
}
Promise / FutureAsync
Python
result = await fetch_data()
JavaScript
const result = await fetchData();
Print / logCommon Operations
Python
print("Hello")
JavaScript
console.log("Hello");
String methodsCommon Operations
Python
"hello".upper()
"HELLO".lower()
"hello world".split()
JavaScript
"hello".toUpperCase()
"HELLO".toLowerCase()
"hello world".split(" ")
Array/list sliceCommon Operations
Python
items[1:3]
items[::-1]  # reverse
JavaScript
items.slice(1, 3)
[...items].reverse()
JSON parse/stringifyCommon Operations
Python
import json
data = json.loads(s)
s = json.dumps(data)
JavaScript
const data = JSON.parse(s);
const s = JSON.stringify(data);
Date / timeCommon Operations
Python
from datetime import datetime
now = datetime.now()
JavaScript
const now = new Date();
Was this page helpful?

Related tools

About Python to JavaScript

Convert simple Python snippets into equivalent JavaScript to speed up porting and learning. Handles common syntax like prints, loops, and basic data structures as a starting point.

How to use

  1. Paste a Python snippet.
  2. Review the generated JavaScript.
  3. Adjust library-specific calls that have no direct JS equivalent.

Frequently asked questions

Will it convert any Python program?
It handles common syntax as a head start; framework- and library-specific code usually needs manual adjustment.
Does it convert indentation to braces?
Yes — Python’s block indentation is translated into JavaScript’s brace-delimited blocks.