Back to series
· 11 min read

Differences Between Python and JavaScript


I. Basic Positioning of Python and JavaScript

Python and JavaScript are both high-level, dynamically typed programming languages, but there are clear differences between them in terms of the background of their creation, their design philosophies, and their primary areas of application.

1. Python

Python was first released by Guido van Rossum in 1991. It is a programming language that emphasizes code readability, development efficiency, and generality.

Python's core design principles include:

  • Simple and readable: the syntax is clear, reducing unnecessary boilerplate code.
  • Dynamic typing: variables do not need to be declared with a fixed type in advance.
  • Multi-paradigm programming: supports object-oriented, procedural, and functional programming.
  • A rich standard library: provides foundational capabilities such as file handling, network communication, data structures, and concurrency.
  • A powerful third-party ecosystem: covers artificial intelligence, data analysis, automation, scientific computing, and web development.

Python is commonly used for:

  • Artificial intelligence and machine learning
  • Data analysis and data science
  • Automation scripts
  • Web backend development
  • Scientific computing
  • Web scraping
  • Operations and infrastructure tooling

2. JavaScript

JavaScript was originally designed by Brendan Eich in 1995, mainly for web page interaction on the browser side.

With the development of browser engines and runtimes, JavaScript has expanded from a browser scripting language into a general-purpose development language.

Its core design principles include:

  • Dynamic typing: the actual type of a variable is determined at runtime.
  • Event-driven: well suited to handling user interaction and asynchronous events.
  • Functions as first-class citizens: functions can be assigned, passed, and returned.
  • Prototypal inheritance: objects can share properties and methods through the prototype chain.
  • A non-blocking I/O ecosystem: especially suited to building highly concurrent network applications.
  • Cross-platform execution: can run in environments such as browsers, Node.js, Deno, and Bun.

JavaScript is commonly used for:

  • Web frontend development
  • Single-page applications (SPA)
  • Server-side development
  • Real-time communication systems
  • Desktop applications
  • Cross-platform mobile applications
  • Browser automation

II. Core Differences Between Python and JavaScript

Both languages offer dynamic typing, automatic memory management, and multi-paradigm programming capabilities, but they differ significantly in syntax, object model, execution mechanism, and runtime environment.

Comparison Dimension Python JavaScript
Design focus Simple, readable, general-purpose development Web interaction, event-driven
Type system Dynamic typing Dynamic typing
Main programming paradigms Object-oriented, procedural, functional Prototype-based, object-oriented, functional
Code blocks Indicated by indentation Indicated by curly braces
Variable declaration var assignment requires no keyword; let and const are usually not applicable let, const, var
Function definition def function, arrow functions
Object model Primarily a class-based object model A prototype-based object model
Inheritance mechanism Class inheritance, MRO Prototype chain inheritance, class syntax
Null value None null, undefined
Array structure list, tuple, etc. Array
Dictionary structure dict Object, Map
Asynchronous mechanism asyncio, coroutines, Future Promise, async/await, event loop
Concurrency model Multithreading, multiprocessing, coroutines, etc. Event loop, Worker, asynchronous I/O
Main runtime environments CPython, PyPy, etc. Browser engines, Node.js, etc.
Common applications AI, data science, automation, backend Frontend, full stack, real-time services

It should be noted that JavaScript's ECMAScript specification and Python's language specification define language behavior, while the specific runtime environment is responsible for providing host capabilities such as browser APIs, file systems, and networking.

III. Differences in Syntax Structure

The most intuitive difference between Python and JavaScript is how code is organized.

1. Code Blocks and Indentation

Python uses indentation to denote code blocks; indentation is part of the syntax.

age = 20

if age >= 18:
    print("成年人")
else:
    print("未成年人")

JavaScript uses curly braces to denote code blocks:

const age = 20;

if (age >= 18) {
    console.log("成年人");
} else {
    console.log("未成年人");
}

Main differences:

Comparison Python JavaScript
Code block Indentation {}
Statement terminator Usually no semicolon required Usually uses semicolons; can be omitted in some cases
Whitespace Indentation is syntactically significant Usually used for formatting and organization
Code style PEP 8 Enforced by tools such as ESLint and Prettier

Python is strict about indentation; mixing inconsistent indentation can produce an IndentationError.

JavaScript, on the other hand, requires attention to the rules of automatic semicolon insertion (ASI). Omitting semicolons does not mean that every line break can safely replace a semicolon.

2. Variable Declarations

Python does not require a special keyword to declare ordinary variables:

name = "Alice"
age = 25

name = "Bob"

JavaScript has several ways to declare variables:

let name = "Alice";
const age = 25;
var city = "Singapore";

name = "Bob";

Differences among the three keywords:

Keyword Scope Allows Reassignment Allows Redeclaration
let Block scope Yes Not allowed in the same scope
const Block scope Cannot be rebound Not allowed in the same scope
var Function scope Yes Yes

Note the following:

  • In Python, variable names are bound to objects, not fixed-type variable slots in the traditional sense.
  • JavaScript's const restricts the variable binding; it does not mean the object's internals cannot be modified.
  • JavaScript's var has historical behaviors such as hoisting and function scope; modern development usually favors let and const.

For example:

const user = {
    name: "Alice"
};

user.name = "Bob"; // valid

// user = {}; // invalid, cannot rebind

3. Comments

Python uses # for single-line comments:

# This is a single-line comment
name = "Alice"

JavaScript uses // and /* */:

// Single-line comment

/*
 Multi-line comment
*/
const name = "Alice";

Python's triple-quoted strings are often used for docstrings and are not simply equivalent to JavaScript multi-line comments.

4. Differences in Data Types

Python and JavaScript are both dynamically typed languages, but their built-in types and type conversion rules differ noticeably.

1. Python Data Types

Common built-in types in Python include:

Type Example Description
int 100 Integer
float 3.14 Floating-point number
complex 2 + 3j Complex number
bool True Boolean value
str "Hello" String
list [1, 2, 3] Mutable sequence
tuple (1, 2, 3) Immutable sequence
dict {"name": "Alice"} Dictionary
set {1, 2, 3} Set
NoneType None None type

Example:

age = 25
price = 19.99
is_active = True
name = "Alice"

numbers = [1, 2, 3]
user = {"name": "Alice", "age": 25}

Python integers can represent integers of arbitrary precision, limited in practice by available memory.

2. JavaScript Data Types

JavaScript's primitive types include:

  • undefined
  • null
  • boolean
  • number
  • bigint
  • string
  • symbol

In addition, JavaScript also has object types, including plain objects, arrays, functions, dates, and more.

Example:

const age = 25;
const price = 19.99;
const isActive = true;
const name = "Alice";

const numbers = [1, 2, 3];
const user = {
    name: "Alice",
    age: 25
};

JavaScript's ordinary number is represented using IEEE 754 double-precision floating point, so the range of integers that can be represented exactly is limited.

For larger integers, you can use BigInt:

const bigNumber = 9007199254740993n;

3. Differences in Numeric Types

This is one of the important differences between the two languages.

Python:

a = 10
b = 3

print(a / b)   # 3.3333333333333335
print(a // b)  # 3

JavaScript:

const a = 10;
const b = 3;

console.log(a / b); // 3.3333333333333335
console.log(Math.floor(a / b)); // 3

In Python, / denotes true division, and // denotes floor division.

In JavaScript, ordinary numeric division always uses /; there is no corresponding // operator.

In addition, the behavior of the two when dividing negative numbers deserves special attention:

print(-7 // 3)  # -3
console.log(Math.floor(-7 / 3)); // -3
console.log(Math.trunc(-7 / 3)); // -2

Python's // rounds toward negative infinity, whereas JavaScript's Math.trunc() truncates toward zero; the two must not be confused.

V. Differences in Type Conversion and Operation Rules

Python and JavaScript differ noticeably in implicit type conversion.

1. Python: Relatively Strict Type Conversion

Python will not automatically add a string and an integer directly.

age = 25
text = "年龄:" + str(age)

print(text)

The following code will raise a TypeError:

# print("25" + 10)

Python usually requires developers to perform type conversion explicitly:

number = int("100")
price = float("19.99")
text = str(100)

2. JavaScript: More Implicit Type Conversion

JavaScript automatically converts types in certain operation scenarios.

console.log("25" + 10); // "2510"
console.log("25" - 10); // 15
console.log(true + 1);  // 2

The + operator may perform string concatenation or numeric addition.

Other arithmetic operators usually attempt to convert operands to numbers.

3. Equality Comparison

Python:

print(1 == True)  # True
print(1 == "1")   # False

JavaScript:

console.log(1 == true);  // true
console.log(1 == "1");   // true
console.log(1 === "1");  // false

JavaScript has two common equality operators:

Operator Description
== Loose equality; may perform type conversion
=== Strict equality; does not perform ordinary implicit type conversion

In engineering practice, JavaScript generally prefers === and !==.

Python has no operator exactly equivalent to JavaScript's ===. Python's == is used for value equality comparison, while is is used for object identity comparison.

For example:

a = [1, 2]
b = [1, 2]

print(a == b)  # True
print(a is b)  # False

6. Differences in Function Mechanisms

Both Python and JavaScript treat functions as first-class citizens; functions can be assigned, passed, and returned, but the function definition syntax and some semantics differ.

1. Python Functions

Python uses def to define functions:

def add(a, b):
    return a + b

result = add(10, 20)
print(result)

Python supports:

  • Default parameters
  • Keyword arguments
  • Variable positional arguments *args
  • Variable keyword arguments **kwargs
  • Lambda expressions
  • Decorators
  • Generator functions

For example:

def introduce(name, age=18):
    print(f"{name}, {age}")

introduce("Alice")
introduce(name="Bob", age=25)

2. JavaScript Functions

JavaScript can use function declarations:

function add(a, b) {
    return a + b;
}

const result = add(10, 20);
console.log(result);

It can also use function expressions and arrow functions:

const add = function(a, b) {
    return a + b;
};

const multiply = (a, b) => a * b;

JavaScript supports:

  • Default parameters
  • Rest parameters ...args
  • Closures
  • Higher-order functions
  • Arrow functions
  • Generator functions
  • Async functions

3. Comparison of Function Features

Feature Python JavaScript
Function declaration def function
Anonymous functions lambda Function expressions, arrow functions
Default parameters Supported Supported
Variadic parameters *args, **kwargs ...args
Closures Supported Supported
Higher-order functions Supported Supported
Decorators Native support Usually implemented with higher-order functions; standardized decorator syntax is also supported
Generators yield function*, yield
Async functions async def async function

4. Function Argument Passing

Both Python and JavaScript use object-reference-related argument passing semantics, but a distinction must be made between mutating a mutable object and rebinding a variable.

Python:

def modify(items):
    items.append(4)

numbers = [1, 2, 3]
modify(numbers)

print(numbers)  # [1, 2, 3, 4]

JavaScript:

function modify(items) {
    items.push(4);
}

const numbers = [1, 2, 3];
modify(numbers);

console.log(numbers); // [1, 2, 3, 4]

In both languages, the same mutable object can be accessed through a function argument, and its internal state can be modified.

However, if the parameter is rebound to a new object inside the function, the binding of the caller's variable is not changed automatically.

VII. Differences in Object-Oriented Mechanisms

Both Python and JavaScript support object-oriented programming, but their object models differ.

1. Python: A Class-Based Object Model

In Python, classes are an important mechanism for creating objects and organizing behavior.

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"{self.name}: {self.age}")

user = User("Alice", 25)
user.introduce()

Core concepts:

  • class: defines a class.
  • __init__: initializes an object.
  • self: refers to the current instance.
  • Instance attributes: belong to a specific object.
  • Class attributes: shared and accessible by the class and its instances.
  • Inheritance: extends functionality through a parent class.
  • MRO: determines the method resolution order in multiple-inheritance scenarios.

Python supports multiple inheritance and uses the C3 linearization algorithm to determine the method resolution order.

2. JavaScript: A Prototype-Based Object Model

JavaScript's object inheritance is based on the prototype chain.

const animal = {
    speak() {
        console.log("Animal speaks");
    }
};

const dog = Object.create(animal);

dog.bark = function() {
    console.log("Woof");
};

dog.speak();
dog.bark();

When accessing an object property, JavaScript first looks for the property on the object itself, then searches up the prototype chain.

3. JavaScript class Syntax

Modern JavaScript supports class syntax:

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    introduce() {
        console.log(`${this.name}: ${this.age}`);
    }
}

const user = new User("Alice", 25);
user.introduce();

JavaScript's class is a syntactic abstraction built on top of the prototype mechanism; it has not replaced the prototype-based inheritance model.

4. Comparison of Object Models

Comparison Dimension Python JavaScript
Object model Class-centric Prototype-centric
Class definition class class
Constructor initialization __init__ constructor
Current object reference self this
Inheritance Class inheritance Prototypal inheritance, class extends
Multiple inheritance Supported Class syntax does not support multiple inheritance
Method resolution MRO Prototype chain
Dynamically adding properties Supported, subject to object type restrictions Supported, subject to object property restrictions
Private members _name convention; __name name mangling; language-level mechanisms beyond __name, such as property control; dedicated private syntax beyond __name that newer versions also support is not applicable #field private fields

Note that Python’s __name double-underscore name mangling is not a true access-control mechanism; JavaScript’s #field, by contrast, is a language-level private field.

VIII. Differences in Modules and Package Management

Both Python and JavaScript support modular development, but their module systems and package management ecosystems are different.

1. Python Module System

Python typically uses .py files as modules.

For example:

project/
├── main.py
└── utils.py

utils.py:

def add(a, b):
    return a + b

main.py:

from utils import add

print(add(10, 20))

Commonly used Python package management tools:

  • pip
  • uv
  • Poetry
  • Conda

Dependencies are usually recorded in files such as requirements.txt and pyproject.toml.

2. JavaScript Module System

Modern JavaScript mainly uses ES Modules.

// math.js
export function add(a, b) {
    return a + b;
}
// main.js
import { add } from "./math.js";

console.log(add(10, 20));

JavaScript also has the CommonJS module system, commonly found in legacy Node.js projects.

// CommonJS export
module.exports = {
    add
};
// CommonJS import
const { add } = require("./math");

Modern JavaScript projects commonly use:

  • npm
  • pnpm
  • Yarn
  • Bun

3. Comparison of Modules and Package Management

Comparison Dimension Python JavaScript
Module form .py files .js, .mjs, .cjs, etc.
Mainstream module mechanism import ES Modules
Legacy module mechanism Traditional package import CommonJS
Package manager pip, uv, Poetry npm, pnpm, Yarn
Package registry PyPI npm Registry
Project configuration pyproject.toml, etc. package.json
Dependency locking requirements lock files, uv.lock, poetry.lock, etc. package-lock.json, pnpm-lock.yaml, yarn.lock

IX. Differences in Asynchronous Programming Mechanisms

Asynchronous programming is one of the important differences between Python and JavaScript.

JavaScript's language and mainstream runtimes have formed a mature asynchronous development model around the event loop; Python, by contrast, provides coroutines and asynchronous I/O capabilities through mechanisms such as asyncio.

1. Python: asyncio and Coroutines

Python uses async def to define coroutine functions and await to wait for asynchronous operations.

import asyncio

async def get_data():
    await asyncio.sleep(1)
    return "数据加载完成"

async def main():
    result = await get_data()
    print(result)

asyncio.run(main())

Core concepts:

  • async def: Defines a coroutine function.
  • await: Waits for an awaitable to complete.
  • asyncio: Provides the event loop and asynchronous task management.
  • Task: Used to schedule and manage coroutine execution.
  • Future: Represents a result that may complete in the future.

Python's asyncio is suitable for a large number of I/O-bound tasks, but it does not automatically make CPU-bound computations run in parallel.

2. JavaScript: Promise and async/await

JavaScript uses Promise to represent the eventual result of an asynchronous operation.

function getData() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("数据加载完成");
        }, 1000);
    });
}

async function main() {
    const result = await getData();
    console.log(result);
}

main();

Core concepts:

  • Promise: Represents the result of an asynchronous operation.
  • then(): Registers success-handling logic.
  • catch(): Handles failures.
  • finally(): Registers final cleanup logic.
  • async: Declares an asynchronous function.
  • await: Waits for awaitables such as Promise.

3. Asynchronous Execution Flow

flowchart TB
    A["Start executing the main program"] --> B["Start an asynchronous task"]
    B --> C["Register a completion callback"]
    C --> D["Current task yields execution control"]
    D --> E["Execute other tasks"]
    E --> F["Asynchronous operation completes"]
    F --> G["Callback enters the runnable queue"]
    G --> H["Event loop schedules the callback"]
    H --> I["Resume subsequent logic"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a conceptualized asynchronous execution process, not an identical internal scheduling implementation in both runtimes.

JavaScript's event loop behavior is defined jointly by the host environment and the language specification. The task queues, microtasks, and I/O scheduling details differ between browsers and Node.js.

Python asyncio, in turn, schedules coroutines and callbacks through an event loop, and the concrete implementation may be supplied by different event loop implementations.

4. Asynchronous Programming Comparison

Comparison dimension Python JavaScript
Coroutine definition async def async function
Await syntax await await
Asynchronous result Future, Task Promise
Event loop Implementations such as asyncio Host environments such as browsers and Node.js
Concurrent tasks asyncio.create_task() Promise, event loop
Asynchronous I/O asyncio, asynchronous libraries Host APIs, Node.js I/O
CPU parallelism Multiple processes, threads, extensions, etc. Worker, Node.js Worker Threads, etc.

10. Differences Between Concurrency and Parallelism Mechanisms

Both Python and JavaScript can handle concurrent tasks, but their default execution models are different.

1. Python's Concurrency Model

Python provides multiple concurrency mechanisms:

  • Multithreading: threading
  • Multiprocessing: multiprocessing
  • Coroutines: asyncio
  • Thread pool: concurrent.futures.ThreadPoolExecutor
  • Process pool: concurrent.futures.ProcessPoolExecutor

In CPython built with the traditional GIL, multiple threads within the same interpreter process are usually limited by the global interpreter lock when executing Python bytecode.

Therefore:

  • I/O-intensive tasks are suitable for threads or coroutines.
  • For CPU-intensive tasks, consider multiprocessing.
  • C extensions can release the GIL when conditions permit.
  • Some modern Python implementations and optional free-threaded CPython builds have different thread execution behavior.

It cannot simply be assumed that all Python implementations are necessarily subject to the same GIL limitations.

2. JavaScript's Concurrency Model

JavaScript usually adopts the event loop model in browsers and common Node.js environments.

A single JavaScript execution thread usually executes code in task order, but it can wait for multiple operations simultaneously through asynchronous I/O.

For CPU-intensive tasks, you can use:

  • Web Workers
  • Node.js Worker Threads
  • Multiprocessing or clustering mechanisms

Example:

console.log("开始");

setTimeout(() => {
    console.log("异步任务完成");
}, 1000);

console.log("结束");

Output order:

开始
结束
异步任务完成

Asynchronous callbacks are not inserted and executed immediately during the execution of the current synchronous code; instead, they run during subsequent scheduling.

3. Comparison of Concurrency Models

Comparison dimension Python JavaScript
Common default model Threads, synchronous execution, coroutines, etc. Event loop
Multithreading Supported Host environments support mechanisms such as Worker
Multiprocessing multiprocessing Node.js child_process, cluster, etc.
Coroutines asyncio Promise, async/await
I/O concurrency Threads or asynchronous I/O Event loop and asynchronous I/O
CPU parallelism Multiple processes, threads, or extensions Worker, child processes
Shared memory Supports multiple sharing mechanisms Workers can share data through mechanisms such as SharedArrayBuffer

11. Differences in Exception Handling Mechanisms

Both Python and JavaScript support exception handling, but their syntax structures and exception type systems are different.

1. Python: try, except, finally

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("发生错误:", e)
finally:
    print("程序结束")

Common Python exceptions:

  • TypeError
  • ValueError
  • IndexError
  • KeyError
  • ZeroDivisionError
  • FileNotFoundError

Python uses raise to throw an exception:

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为零")

    return a / b

2. JavaScript: try, catch, finally

try {
    const result = 10 / 0;

    if (!Number.isFinite(result)) {
        throw new Error("结果不是有限数值");
    }
} catch (error) {
    console.log("发生错误:", error.message);
} finally {
    console.log("程序结束");
}