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.
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.
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:
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.
Key takeaways
- Function = name + parameters + body; call by name with arguments.
returnhands a result to the program and ends the function;printonly shows a human.- Functions assemble into constructs; one function — one job.
- Telling function names make code read like prose.