Skip to content

Functions

Function Definition and Invocation

Python Function Definition

python
# Python - Basic function definition
def greet(name):
    """This is a simple greeting function"""
    return f"Hello, {name}!"

# Call the function
result = greet("Alice")
print(result)  # Hello, Alice!

# Function with default parameters
def greet_with_default(name="World"):
    return f"Hello, {name}!"

print(greet_with_default())      # Hello, World!
print(greet_with_default("Bob")) # Hello, Bob!

# Function with multiple parameters
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # 8

# Returning multiple values
def get_name_and_age():
    return "Alice", 25

name, age = get_name_and_age()
print(f"{name} is {age} years old")

JavaScript Function Definition

javascript
// JavaScript - Basic function definition
function greet(name) {
  return `Hello, ${name}!`;
}

// Call the function
const result = greet("Alice");
console.log(result); // Hello, Alice!

// Function with default parameters
function greetWithDefault(name = "World") {
  return `Hello, ${name}!`;
}

console.log(greetWithDefault()); // Hello, World!
console.log(greetWithDefault("Bob")); // Hello, Bob!

// Function with multiple parameters
function addNumbers(a, b) {
  return a + b;
}

const result2 = addNumbers(5, 3);
console.log(result2); // 8

// Returning multiple values (using an object)
function getNameAndAge() {
  return { name: "Alice", age: 25 };
}

const { name, age } = getNameAndAge();
console.log(`${name} is ${age} years old`);

Parameter Passing Comparison

FeaturePythonJavaScript
Default Parametersdef func(a=1)function func(a=1)
Keyword Argumentsfunc(a=1, b=2)func({a: 1, b: 2})
Variable Arguments*args...args
Keyword Variable Args**kwargsObject destructuring

Advanced Function Features

Python Advanced Function Features

python
# Python - Variable arguments
def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3, 4, 5))  # 15

# Python - Keyword variable arguments
def create_person(**kwargs):
    return kwargs

person = create_person(name="Alice", age=25, city="New York")
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Python - Mixed arguments
def complex_function(name, age, *args, **kwargs):
    print(f"Name: {name}, Age: {age}")
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

complex_function("Alice", 25, "Engineer", "Python", city="NYC", hobby="coding")

# Python - Functions as parameters
def apply_operation(func, x, y):
    return func(x, y)

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

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

print(apply_operation(add, 5, 3))      # 8
print(apply_operation(multiply, 5, 3)) # 15

JavaScript Advanced Function Features

javascript
// JavaScript - Variable arguments
function sumNumbers(...args) {
  return args.reduce((sum, num) => sum + num, 0);
}

console.log(sumNumbers(1, 2, 3, 4, 5)); // 15

// JavaScript - Object parameters
function createPerson({ name, age, city }) {
  return { name, age, city };
}

const person = createPerson({ name: "Alice", age: 25, city: "New York" });
console.log(person); // {name: "Alice", age: 25, city: "New York"}

// JavaScript - Functions as parameters
function applyOperation(func, x, y) {
  return func(x, y);
}

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

function multiply(a, b) {
  return a * b;
}

console.log(applyOperation(add, 5, 3)); // 8
console.log(applyOperation(multiply, 5, 3)); // 15

Anonymous Functions

Python Anonymous Functions (Lambda)

python
# Python - Lambda function
square = lambda x: x ** 2
print(square(5))  # 25

# Lambda in sorting
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=lambda x: len(x))
print(sorted_fruits)  # ['date', 'apple', 'banana', 'cherry']

# Lambda in map
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# Lambda in filter
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4]

# Multi-parameter Lambda
add = lambda x, y: x + y
print(add(3, 4))  # 7

# Lambda in reduce
from functools import reduce
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all)  # 15

JavaScript Anonymous Functions

javascript
// JavaScript - Arrow function
const square = (x) => x ** 2;
console.log(square(5)); // 25

// Arrow function in sorting
const fruits = ["apple", "banana", "cherry", "date"];
const sortedFruits = fruits.sort((a, b) => a.length - b.length);
console.log(sortedFruits); // ['date', 'apple', 'banana', 'cherry']

// Arrow function in map
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map((x) => x ** 2);
console.log(squares); // [1, 4, 9, 16, 25]

// Arrow function in filter
const evenNumbers = numbers.filter((x) => x % 2 === 0);
console.log(evenNumbers); // [2, 4]

// Multi-parameter arrow function
const add = (x, y) => x + y;
console.log(add(3, 4)); // 7

// Arrow function in reduce
const sumAll = numbers.reduce((sum, num) => sum + num, 0);
console.log(sumAll); // 15

// Immediately Invoked Function Expression (IIFE)
const result = (() => {
  const x = 10;
  const y = 20;
  return x + y;
})();
console.log(result); // 30

Anonymous Function Comparison

FeaturePython LambdaJavaScript Arrow Function
Syntaxlambda x: x**2x => x**2
Multi-parameterlambda x, y: x+y(x, y) => x+y
Multi-lineNot supportedSupported (with braces and return)
this bindingNot applicableAutomatic binding
ConstructorCannot beCannot be

Functional Programming Features

Python Functional Programming

python
# Python - Higher-order functions
def compose(*functions):
    def inner(arg):
        for f in reversed(functions):
            arg = f(arg)
        return arg
    return inner

def add_one(x): return x + 1
def multiply_by_two(x): return x * 2

composed = compose(add_one, multiply_by_two)
print(composed(5))  # 11 (5 * 2 + 1)

JavaScript Functional Programming

javascript
// JavaScript - Higher-order functions
const compose =
  (...functions) =>
  (arg) =>
    functions.reduceRight((acc, f) => f(acc), arg);

const addOne = (x) => x + 1;
const multiplyByTwo = (x) => x * 2;

const composed = compose(addOne, multiplyByTwo);
console.log(composed(5)); // 11 (5 * 2 + 1)

Closures and Decorators

Python Closures and Decorators

python
# Python - Closure
def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

my_func = outer_function("Hello")
my_func()  # Hello

# Python - Decorator
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

say_whee()

JavaScript Closures

javascript
// JavaScript - Closure
function outerFunction(msg) {
  return function innerFunction() {
    console.log(msg);
  };
}

const myFunc = outerFunction("Hello");
myFunc(); // Hello

Summary

  • Python: Clear syntax, powerful argument handling (*args, **kwargs), and decorators.
  • JavaScript: Flexible functions, first-class citizens, closures are central.

Exercises

  1. Write a function that accepts another function as an argument.
  2. Create a decorator in Python.
  3. Implement a closure in JavaScript.

Next Steps

Now you know about functions. Next, we'll learn about modules and packages.