Functions and data structures · Part 7 of 36

Functions: name a piece of work

Basic 14 min

Define functions with parameters and return values, understand scope, and write small pure functions.

What you will learn

  • You can define and call functions with parameters and return values.
  • You can explain local and global scope.
  • You can tell a pure function from one with side effects.

Before this: Loops: repeating work

Why functions?

A function is a named block of code that does one job. You define it once and call it as often as you like. Functions make programs shorter, easier to read and easier to test, because each piece can be checked on its own.

// JavaScript
function areaOfBed(length, width) {
  return length * width;
}
const a = areaOfBed(3, 1.2);  // 3.6
# Python
def area_of_bed(length, width):
    return length * width

a = area_of_bed(3, 1.2)  # 3.6

length and width are parameters — placeholders. 3 and 1.2 are the arguments you pass in a call. return hands a value back to the caller and ends the function. A function without return gives back undefined (JavaScript) or None (Python).

JavaScript has a second, shorter syntax that you will see everywhere — the arrow function:

const areaOfBed = (length, width) => length * width;

Python's short form is lambda length, width: length * width, but it is limited to one expression, so def is the norm.

A small machine with a funnel in and a chute out turning apples into juice

Default and named arguments

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Sam")                    # Hello, Sam!
greet("Sam", greeting="Hi")     # Hi, Sam!
function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

Python supports keyword arguments (greeting="Hi") directly. In JavaScript you get the same readability by passing an object: greet({ name: "Sam", greeting: "Hi" }).

A Python trap: never use a mutable default such as def add(item, items=[]) — the same list is shared by every call. Use items=None and create the list inside.

Scope: where names live

Variables created inside a function are local: they exist only while the function runs and are invisible outside. Names defined at the top level are global. A function can read globals, but relying on them makes code hard to follow. Pass what a function needs as parameters and return what it produces.

In JavaScript, let and const are also limited to the nearest { … } block; in Python, an if or for block does not create a new scope — only functions (and classes, modules) do.

Pure functions and side effects

A pure function always returns the same output for the same input and changes nothing else — like area_of_bed. A function with side effects prints, writes a file, changes a global or modifies its arguments. You need side effects (otherwise a program can't show anything), but keep them at the edges and the core logic pure: pure functions are trivial to test and safe to reuse.

Functions calling functions

Functions can call other functions — even themselves (recursion):

def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

Each call waits for the inner one; that waiting list is the call stack you saw in stack traces. Too many nested calls overflow it — Python stops at about 1,000 levels by default.

Try it: JavaScript sandbox

Write and run small JavaScript programs; the checker tells you when an exercise is solved.

Turn on JavaScript to use this lab. Worked example:

Exercise 7: write a function celsiusToFahrenheit(c) that returns c × 9 / 5 + 32. The checker calls it with 0, 100 and −40 and expects 32, 212 and −40.

Key points

  • A function names a piece of work: parameters in, return value out.
  • JavaScript: function f(a) {} or arrow (a) => …; Python: def f(a):.
  • Default values and keyword arguments make calls readable; avoid mutable defaults in Python.
  • Local variables live only inside the function; avoid depending on globals.
  • Keep the core logic in pure functions and side effects at the edges.

Flashcards

Question: What is the difference between a parameter and an argument?
Answer: The parameter is the placeholder in the definition; the argument is the value passed in the call.
Question: What does a function without return give back?
Answer: undefined in JavaScript, None in Python.
Question: What is a pure function?
Answer: One that returns the same output for the same input and has no side effects.
Question: Why is def f(items=[]) a trap in Python?
Answer: The default list is created once and shared by every call.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. What does area_of_bed(2.5, 4) return?

    Show the answer

    10

    2.5 × 4 = 10.

    Source: The Python Tutorial, 4.8 Defining Functions

  2. Which of these JavaScript functions is pure?

    • (a, b) => a + b
    • () => console.log("hi")
    • (list) => list.push(1)
    • () => Date.now()
    Show the answer

    (a, b) => a + b

    Only a + b depends solely on its inputs and changes nothing; the others print, modify an argument or read the clock.

    Source: MIT OCW 6.100L

  3. In Python you define a function with the keyword ___.

    Show the answer

    def

    def starts a function definition.

    Source: The Python Tutorial, 4.8

  4. A variable created inside a function is…

    • local to that function
    • visible everywhere
    • shared by all functions
    • a constant
    Show the answer

    local to that function

    Names assigned inside a function are local to it.

    Source: The Python Tutorial, 9.2 Scopes and Namespaces

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.