Welcome to functions—one of JavaScript's most powerful features! Think of functions as named, reusable blocks of code that you can create to perform specific tasks.
Just like a calculator has a "square root" button you can press anytime, functions let you run the same code easily.
Engagement Message
What's a task you do repeatedly that could benefit from being a single "button"?
Functions help you avoid writing the same code over and over again. Instead of copying and pasting, you write the logic once inside a function and then call it whenever you need it. This is a core programming principle called DRY (Don't Repeat Yourself).
Engagement Message
How does updating code in one function instead of five places make it less error-prone?
Creating a function in JavaScript uses the function
keyword, followed by a name you choose, parentheses ()
, and curly braces {}
:
Engagement Message
Why do you think JavaScript uses curly braces instead of just indentation to group function code?
To use a function, you call it by writing its name followed by parentheses:
This tells JavaScript to find the function with that name and execute all the code inside its body. You can call the same function as many times as you need.
Engagement Message
If you define a function but never call it, what happens?
