Skip to content

Programming Basics

Functions

The idea, in plain English

A function is a recipe card. You write the steps once and give the recipe a name. From then on, you just say the name whenever you want those steps done. You don't have to rewrite them every time. You can also hand it different ingredients, called 'arguments', so it makes something a little different each time.

How it works

  1. 1Define the function once. Give it a name and list the inputs it needs, called 'parameters', in parentheses.
  2. 2Write the steps inside it. Use `return` to send back an answer.
  3. 3'Call' the function anywhere by writing its name with actual values in parentheses. The computer runs those steps and hands you back whatever it returned.

When you'd use it

Use a function any time you find yourself writing the same steps more than once. You can also use one just to give a chunk of logic a clear name, so your code reads like plain English.

Common beginner mistakes

  • Forgetting `return`. The function does the work but never hands back an answer. Calling it gives you nothing usable.
  • Confusing a function's parameters (the placeholders in its definition) with arguments (the actual values you pass in when calling it).

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Hello, Sam!
Hello, Mia!
Area: 20

Not sure this is the right topic? See the learning paths → or where this leads →