What Is a Function?

Grade 6, page 1 of 11. A two-minute read.

Let's say you've written some code that greets someone in a fancy way:

JavaScript
console.log("=====================");
console.log("  Welcome, friend!  ");
console.log("=====================");

It prints

=====================
  Welcome, friend!  
=====================

Lovely. Now you need that fancy greeting in five different places in your program. You could copy and paste it five times. But then your boss (or your little sister) says "actually, can the border be made of stars?" and you have to change it in five places. And you'll miss one. You always miss one.

There's a better way. You can wrap that code up in a function, give it a name, and then use that name whenever you want the code to run.

Think of it like thisThe vending machine

A function is like a vending machine. Somebody built it once, and now anybody can use it, as many times as they like, without knowing how it works inside. You put something in (money and a button press), the machine does its work inside (which you don't need to see), and something comes out (a cold drink). Functions work exactly the same way: inputs go in, work happens, and a result comes out.

A function: inputs go in the top, the body does the work, and a result comes out

You've actually been using functions since Kindergarten! console.log(), Math.random(), Number(), alert()... these are all functions that someone else wrote and packaged up for you. Now you're going to learn how to make your own.

Functions are arguably the most important concept in all of programming. They let you:

  1. Reuse code instead of copying and pasting it. Programmers call this DRY: Don't Repeat Yourself.
  2. Give a name to a chunk of work, which makes your code read like a story.
  3. Break big problems into small pieces that are easy to think about one at a time.
  4. Fix things in one place. Change the function, and every place that uses it gets the fix.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning