All lessons

Functions

9 min · JavaScript

Package code under a name so you can reuse it.

JavaScript · Functions0/5 cleared

Enemy 1 of 5

A function is a named, reusable block of code — write the logic once, then run it as many times as you need just by calling its name. This is how programmers avoid repeating themselves: wrap a task in a function instead of copy-pasting the same lines everywhere they're needed.

Define one with the function keyword, a name, parameters inside ( ), and the body inside { }. Defining a function doesn't run it — JavaScript just remembers the recipe. It only actually executes when you call it by name followed by parentheses, like double(5) below.

Use return to hand a value back to whoever called the function, so that result can be stored, printed, or passed into more code. A function that never hits a return statement automatically hands back undefined instead — which is worth remembering if you ever forget the return and wonder why your value came back empty.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.

Stuck? Ask Rena

Your AI tutor that gives assistance.

Asking Rena in lessons is on Ultimate.