← Back to Articles

Syntax

Comparing the syntax differences between Python and JavaScript

Feature JavaScript Python
Variable Declaration let x = 10;
// Variables & assignment
let count = 0;
const user = "Bob";
var temp = undefined; // Python -> None
const PI = 3.14159;
x = 10
# Variables & assignment
count = 0
user = "Bob"
temp = None
PI = 3.14159
Comments
// This is a comment

/* This is a multi-line comment */
# This is a comment
Boolean let flag = true; flag = True (case-sensitive)
Types typeof(x) type(x)
print(type(10))        # 
print(type(3.14))      # 
print(type("Hello"))   # 
print(type(True))      # 
print(type([]))        # 
Type Coercion

JavaScript automatically performs type coercion.

console.log("5" + 3);      // "53"
console.log(true + 1);     // 2
console.log(0 == false);   // true

Python requires explicit conversion for most types.

print("5" + 3)       # TypeError
print("5" + str(3))  # "53"
print(True + 1)      # 2
print(0 == False)    # True
print(int("42"))     # 42
print(float("42"))   # 42.0
String Literals
const name = "Alice";
const age = 30;

console.log(`Hello ${name}, you are ${age}!`);
name, age = "Alice", 30

greeting = f"Hello {name}, you are {age}!"
print(greeting)
Slice
const s = "sketch";

console.log(s.slice(0, 3)); // "ske"
console.log(s.slice(1, 4)); // "ket"
console.log(s.slice(-2));   // "ch"
s = "sketch"

print(s[0:3])   # "ske"
print(s[1:4])   # "ket"
print(s[-2:])   # "ch"
Upper case console.log("hello".toUpperCase());// 'HELLO' print("hello".upper())# 'HELLO'
Replace console.log("hello".replace("l", "L"));// 'heLlo' replaces first ONLY the first occurrence print("hello".replace("l", "L"))# 'heLLo' replaces all occurrences

print("hello".replace("l", "L", 1))# 'heLLo' replaces only the first occurrence
Includes console.log("hello".includes("e"));// true print("e" in "hello") # True (includes -> in)
=== console.log([]===[]) // true print([]==[]) # True
! console.log(!true) // false print(not True) # False
Ternary console.log(true ? "yes" : "no") // "yes"

const age = 20;

const status = age >= 18 ? "adult" : "minor";
print("yes" if True else "no") # "yes"

age = 20;

"adult" if age >= 18 else "minor"
&& || => and or console.log( 2 < 5 && 7 < 5) // false

console.log( 2 < 5 || 7 < 5) // true
print( 2 < 5 and 7 < 5) # False

print( 2 < 5 or 7 < 5) # True
Destructuring/ unpacking const [first, second, third] = [1, 2, 3]; first, second, third = [1, 2, 3]
spread operator const [head, ...tail] = [1, 2, 3, 4, 5]; // ... spread; head, *tail = [1, 2, 3, 4, 5]
Loops for (let i = 0; i < 5; i++) {} for i in range(5):