Open original
Info
Demo 3.6

Functions

Files in this demo

├─ index.html
└─ script.js

A function is a named piece of code you can run whenever you want. Write it once, use it everywhere.

function greet(name) {
	return "Hello, " + name + "!";
}

greet("Moonbug");   // "Hello, Moonbug!"

The parts

  • Parameters ~ name in the brackets. Placeholders, filled in when the function is called.
  • Arguments ~ "Moonbug". The actual values you pass in.
  • return ~ hands a value back and stops the function there and then. Code after a return never runs.

A function without a return still works ~ it just gives you undefined. That’s fine if its job is to do something rather than work out something.

Arrow functions

const double = (n) => n * 2;

The same idea in fewer characters. With a single expression and no curly braces, the result is returned automatically. You’ll see these everywhere in modern JavaScript, especially as one-off callbacks.

Scope

Variables declared inside a function only exist inside it. Call the function again and they start fresh. This is a feature ~ it means two functions can both use a variable called count without ever interfering with each other.

Why bother

Three reasons, and they’re all the same reason really:

  1. 1Don’t repeat yourself. Fix a bug once instead of in six places.
  2. 2Name things. randomBetween(1, 6) reads better than the maths inside it.
  3. 3Think in smaller pieces. A big problem becomes several small ones.

If you catch yourself copy-pasting code and changing one value, that’s a function trying to be born.

Next demoLoops
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console