Course
BASICModule 2: Loops & Functions· 2/3

Functions

Packaging logic

A chunk of code you need in three places can be copied three times — and edited three times on every change. A function solves this: the logic is packaged once and called by name as many times as you like.

PLAYGROUND

Anatomy: the declaration (function in JS, def in Python), a name, parameters in parentheses — the input data, and a body — what to do. A call is the name with parentheses and concrete values (arguments).

You've been using functions since the first lesson: console.log and print are built-in functions of the language. Now you make your own.

Returning a result

The printer function above only prints. The real power is in functions that return a result: you can put it into a variable, pass it on, use it in calculations.

PLAYGROUND

return hands back a value and immediately ends the function — code after it doesn't run. A function without a return returns nothing (undefined / None).

The difference between "print" and "return" is crucial for a beginner: print shows a human and disappears, return hands a value to the program for further work. Function building blocks are built on return.

Functions call functions

A program grows up when functions start assembling into constructs:

PLAYGROUND

Each function does one thing and does it well — the main principle of breaking programs apart. Reading code with telling function names, you read almost prose: "order summary = discount, then format."

Exercise

Write a function isStrongPassword that takes a string and returns a boolean: length 8+ characters. String length: s.length (JS) / len(s) (Python). Test it on a couple of examples.

PLAYGROUND

Key takeaways

  • Function = name + parameters + body; call by name with arguments.
  • return hands a result to the program and ends the function; print only shows a human.
  • Functions assemble into constructs; one function — one job.
  • Telling function names make code read like prose.
CHECK YOURSELF
1. How does return differ from print/console.log?
2. What happens to code after return inside a function?
3. The same calculation is needed in four places in the program. The right solution?
LoopsYour First Real Program