In our last course, we learned about loops to repeat actions. But what if we want to reuse entire chunks of code across different parts of our program?
Engagement Message
Have you ever wished you could copy-paste code but make it smarter?
That's where functions come in! A function is a named block of code that you can write once and then "call" (or run) whenever you need it. Think of it like creating a custom shortcut for a series of steps.
Engagement Message
What would you name a function that prints a welcome message?
Functions help us avoid writing the same code over and over again. This is a core programming principle called DRY (Don't Repeat Yourself). It makes our code cleaner, more organized, and easier to update.
Engagement Message
Can you think of any repetitive tasks in your daily life?
Here's how you define a function in JavaScript. You use the function
keyword, followed by a name you choose, parentheses ()
, and a block of code inside curly braces {}
.
Engagement Message
Notice how the curly braces group the function's code?
Let's create our first function! This one will print a simple greeting:
