πŸͺ„
World 13 Β· Fancy Function Tricks

Closures: Pocket Functions

What if you could write a tiny function right where you need it, pop it in your pocket, and use it later? That’s a closure β€” a little pocket-sized function. πŸͺ„

A function you can save in a box

Normally a function gets a name and lives at the top of your file. A closure is different. You write it right inside your code and tuck it into a variable, like saving a handy shortcut to use again and again.

Closures use bars | | around their inputs instead of round brackets. Watch:

We made a closure called add_one. Whatever number you hand it, it gives back that number plus one. Then we called it just like a normal function: add_one(5). πŸŽ‰

Think of it like this… A closure is a quick note you jot on a sticky note. You keep the note in your pocket and use it whenever you want β€” no need to walk all the way back to the source.

Closures can peek at what’s around them

Here’s the powerful part: a closure can use variables from the area around it, even ones you didn’t pass in. It β€œcloses around” them β€” that’s why it’s called a closure!

We never handed bonus to the closure, but it grabbed it from nearby anyway. Handy! πŸͺ„

Ferris says: Those bars | | are like little doorways where your inputs walk in. If a closure takes nothing, just use empty bars: || 42.
Try this! Change add_one into double that does x * 2, then run it with the number 8. What do you get?

Quick quiz

What does a closure use around its inputs?

Yes! Closures wrap their inputs in bars, like |x| x + 1. πŸŽ‰

You learned… A closure is a little pocket-sized function you can store in a variable, written with bars like |x| x + 1, and it can even peek at variables nearby. Next up: Iterators: Going Through Stuff β€” where closures really shine! πŸ”„