DEV Community

Mohin Sheikh
Mohin Sheikh

Posted on

From JavaScript to Python: A Syntax Guide for Developers

Introduction

If you’re a JavaScript developer diving into Python, you’ll find many concepts familiar but with syntactic twists. Python’s emphasis on readability and simplicity means fewer brackets, strict indentation, and a different approach to common tasks. Let’s break down key differences with side-by-side examples.


1. Variables and Constants

JavaScript

let mutableVar = 10;       // Mutable
const immutableVar = 20;   // Immutable
Enter fullscreen mode Exit fullscreen mode

Python

mutable_var = 10    # No 'let' or 'const'—all variables are mutable
IMMUTABLE_VAR = 20  # Convention: UPPER_CASE for "constants" (not enforced)
Enter fullscreen mode Exit fullscreen mode

Key Notes:

  • Python uses snake_case (not camelCase).
  • No var or const—just assign values.

2. Data Types

JavaScript Python Notes
number int, float Python distinguishes integers and floats.
string str Both use template literals/f-strings.
boolean (lowercase) bool (TitleCase) Python: True/False (case-sensitive).
array list, tuple Lists are mutable; tuples are immutable.
object dict Python dicts ≈ JS objects.
null/undefined None Python’s universal "no value" placeholder.

3. Conditionals

JavaScript

if (age > 18) {
  console.log("Adult");
} else if (age === 18) {
  console.log("Exactly 18");
} else {
  console.log("Minor");
}
Enter fullscreen mode Exit fullscreen mode

Python

if age > 18:
    print("Adult")
elif age == 18:    # 'elif' instead of 'else if'
    print("Exactly 18")
else:
    print("Minor")   # Indentation defines blocks (no curly braces!)
Enter fullscreen mode Exit fullscreen mode

Gotchas:

  • Use == for equality checks (Python has no ===).
  • Indentation is mandatory—use 4 spaces (no tabs).

4. Loops

For Loop

JavaScript (C-style):

for (let i = 0; i < 5; i++) {
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Python (range-based):

for i in range(5):   # range(0, 5) → 0,1,2,3,4
    print(i)
Enter fullscreen mode Exit fullscreen mode

Iterating Over Arrays/Lists

JavaScript:

const fruits = ["apple", "banana"];
for (const fruit of fruits) {
  console.log(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Python:

fruits = ["apple", "banana"]
for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

5. Functions

JavaScript

function multiply(a, b) {
  return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
Enter fullscreen mode Exit fullscreen mode

Python

def multiply(a, b):
    return a * b

# Lambda (anonymous)
multiply = lambda a, b: a * b
Enter fullscreen mode Exit fullscreen mode

Key Differences:

  • Python uses def instead of function.
  • Lambdas are limited to single expressions.

6. Strings

Template Literals (JS) vs. f-Strings (Python)

JavaScript:

const name = "Alice";
console.log(`Hello, ${name}!`);  // Backticks
Enter fullscreen mode Exit fullscreen mode

Python:

name = "Alice"
print(f"Hello, {name}!")  # 'f' prefix
Enter fullscreen mode Exit fullscreen mode

7. Arrays (JS) vs. Lists (Python)

Action JavaScript Python
Add element arr.push(4) lst.append(4)
Remove last arr.pop() lst.pop()
Check existence arr.includes(4) 4 in lst
Create copy [...arr] lst.copy()
Map arr.map(x => x*2) [x*2 for x in lst]

Python List Comprehension Example:

squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

8. Objects (JS) vs. Dictionaries (Python)

JavaScript:

const user = { 
  name: "Alice", 
  age: 30 
};
console.log(user.name);  // Dot notation
Enter fullscreen mode Exit fullscreen mode

Python:

user = {
    "name": "Alice",
    "age": 30
}
print(user["name"])   # Or user.get("name")
Enter fullscreen mode Exit fullscreen mode

9. Classes

JavaScript

class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() {
    console.log("Woof!");
  }
}
Enter fullscreen mode Exit fullscreen mode

Python

class Dog:
    def __init__(self, name):  # Constructor
        self.name = name

    def bark(self):            # 'self' is explicit
        print("Woof!")
Enter fullscreen mode Exit fullscreen mode

Key Notes:

  • Python requires self as the first method parameter.
  • No new keyword: my_dog = Dog("Buddy").

10. Error Handling

JavaScript:

try {
  throw new Error("Failed!");
} catch (error) {
  console.log(error.message);
}
Enter fullscreen mode Exit fullscreen mode

Python:

try:
    raise Exception("Failed!")
except Exception as e:
    print(e)
Enter fullscreen mode Exit fullscreen mode

11. Modules and Imports

JavaScript (ES6):

import React from 'react';
export const PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

Python:

import math
from math import sqrt

# Exporting: Just write variables/functions in the file.
PI = 3.14
Enter fullscreen mode Exit fullscreen mode

12. Truthy and Falsy Values

JavaScript Falsy Python Falsy
false, 0, "" False, 0, ""
null, undefined None
NaN [], {}, ()

Example:

if not []:   # Empty list is falsy
    print("This list is empty!")
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Indentation Rules: Python uses indentation (4 spaces) instead of curly braces.
  2. Simplicity: Python favors explicit, readable code (e.g., elif over else if).
  3. Rich Data Structures: Lists, tuples, sets, and dictionaries offer flexibility.
  4. No Semicolons: Optional in Python (but avoid them).

Example: Factorial Function

JavaScript:

function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}
Enter fullscreen mode Exit fullscreen mode

Python:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)
Enter fullscreen mode Exit fullscreen mode

Next Steps

  1. Practice: Use platforms like LeetCode to solve problems in Python.
  2. Explore Libraries: Learn numpy (arrays), pandas (dataframes), and requests (HTTP).
  3. Read the Zen of Python: Run import this in a Python shell.

Final Thoughts

Python’s syntax feels minimalist compared to JavaScript, but its strict structure encourages clean code. Start small, embrace indentation, and leverage Python’s powerful built-in tools.

Happy coding! 🐍


Author: Mohin Sheikh

Follow me on GitHub for more insights!


Top comments (0)