← Back to Articles

Functions

Comparison between Functions in JavaScript and Python

Feature JavaScript Python
Basic function
const book = {title: "Dune", author: "herbert"}
function describe(book) {
  return `${book.title} is good`;
}
console.log(describe({ title: "Dune" }));
`def` instead of `function`, a colon + indentation instead of braces.
book = {"title": "Dune", "author: "Herbert"}

def describe(book):
    return f"{book['title']} is good"

print(describe({"title": "Dune"}))
undefined and none
function noop() {}
console.log(noop());  // undefined
pass (returns None)
def noop():
    pass # `pass` returns None — Python's null

print(noop()) # None
Order of Arguments Arguments print in the same order as they were passed in
function printFn(a, b, c) {
  console.log(a, b, c);
}
printFn(1, 2, 3);
the non positional * vs the positional /
# Anything AFTER * must be passed by name, not position.
def print_fn(a, *, b, c):
    print(a, b, c)

print_fn(1, b=3, c=2)
# The / separator forces positional-only.
def positional(a, b, /):
    print(a, b)

positional(1, 2)
Arrow and Lambda functions Arrow function
const square = (x) => x * x;
console.log(square(5));  // 25
Lambda functions
square = lambda x: x * x
print(square(5))  # 25
Closures the inner fn remembers outer state
function make() {
  let borrowed = 0;
  return function borrow() {
    borrowed += 1; // knows about `borrowed`
    return borrowed;
  };
}
need `nonlocal` to REASSIGN an outer variable
def make():
    borrowed = 0
    def borrow():
        nonlocal borrowed # without this: UnboundLocalError
        borrowed += 1
        return borrowed
    return borrow
Decorators no Decorators Decorators
def log(fn):
    def wrapper(*args, **kwargs):
        print("starting the function")
        result = fn(*args, **kwargs)
        print("function executed: {result}")
        return result
    return wrapper

@log  # <--  readable wrapping
def print_title(title):
    return f"I need to print {title}"

print(print_title("Python for JS Devs"))