Lesson 13 ยท JavaScript Deep Dive ยท about 20 minutes
๐ช Functions: Your Own Spells
So far you've been casting OTHER people's spells. Today you learn to write your OWN: a chunk of code with a name, that you write once and cast a thousand times. This is the biggest power-up in all of programming.
๐ฌ Watch first (90 seconds)
Write the spell once, cast it forever
Imagine you invent an amazing recipe for robot cookies. Do you re-invent it every time you're hungry? No way โ you write it down once, give it a name ("Robot Cookies"), and then just say the name whenever you want cookies.
A function is exactly that: a recipe with a name. Here's one:
function cheer(name) {
return "Go " + name + "!";
}
Read it like a wizard would:
functionโ "I'm writing a new spell!"cheerโ the spell's name. You pick it, like a variable name.(name)โ an ingredient slot. Fancy word: parameter. It's an empty bowl waiting for whatever you pour in later.{ ... }โ the spell's steps, between the curly braces (you know these from if/else!).returnโ "hand the answer back to whoever cast me." The spell's result comes flying back out.
And here's how you CAST it โ this is called calling the function:
cheer("Robo Sneakers") // โก๏ธ gives back "Go Robo Sneakers!"
cheer("Tugay") // โก๏ธ gives back "Go Tugay!"
Same recipe, different ingredients, different cookies. One spell, endless cheers!
- DEFINING the function (
function cheer(name) { ... }) does NOTHING yet. You just wrote the recipe in the cookbook. The kitchen is silent. No cookies exist. - CALLING the function (
cheer("Robo Sneakers")) is what actually makes it run. NOW you're cooking.
One more secret: you've been calling functions since lesson 8! document.getElementById("buy")? That's a function call โ getElementById is a spell somebody at the browser factory wrote for you, "buy" is the ingredient you pour in, and the brick it hands back is its return. You've been a spell-caster all along. Today you become a spell-writer.
๐ ๏ธ Build it (the fun part)
- Open
practice/myshop.htmlin VS Code and find your<script>at the end of the body. - At the TOP of the script, write your first-ever spell (type it, don't copy-paste!):
Save and refresh. Notice: nothing happens. That's correct! You only wrote the recipe โ nobody cooked it yet.function priceWithTax(price) { return price * 2; // 100% kid-tax! ๐ } - Now write a second spell right below it. This one doesn't return anything โ it DOES something instead:
(You need yourfunction announce(text) { document.getElementById("message").textContent = text; }<p id="message"></p>from lesson 8 โ add it back if it's gone.) - Time to COOK. Change your Buy button's click listener so the inside becomes:
Look closely โ that's a spell calling a spell:btn.addEventListener("click", function () { announce("Total: " + priceWithTax(5) + " coins"); });priceWithTax(5)runs first and hands back10, thenannouncewrites the whole sentence on the page. - Save (โS), refresh (โR), click Buy now. Does it say Total: 10 coins? You just wrote, cast, and CHAINED your own spells. ๐ช๐
๐น๏ธ Try it right here โ the lesson checks your code!
Good news: THESE preview boxes have their electricity ON โ your scripts really run as you type. Build it, watch it appear, then press Check my code โ.
๐จ Now break it!
Do these in your real myshop.html file. Predict what will happen BEFORE you refresh!
- Cast it three times. Under your button wiring, add three calls with different ingredients:
console.log(priceWithTax(5));,console.log(priceWithTax(50));,console.log(priceWithTax(100));. Refresh and open the Console (right-click โ Inspect โ Console). Three answers from ONE recipe โ that's the whole point of functions. - Steal the return. Delete the word
returnfrompriceWithTax(keepprice * 2;). Refresh, click Buy. It says Total: undefined coins! Meetundefinedโ JavaScript's way of saying "the box came back empty." Withoutreturn, the spell still ran, but it handed nothing back. You will meet this word 1000 more times in your coding life โ now you know it just means "empty box". Putreturnback. - Rename only the recipe. Change the definition to
function priceWithTaxx(price)but leave the CALL aspriceWithTax(5). Refresh, click Buy, check the Console: a red error โ priceWithTax is not defined. The browser looked for a recipe with that exact name and the cookbook page was missing. Fix the name back.
๐ฎ Quiz time
No peeking at the notes above โ trying to remember is what makes it stick!