Understand what a function is in JavaScript, why it’s used, how it works, and how it fits into real-world programming.
A function is a named block of code that performs a specific task.
You write the function once, and then you can use it (or “call” it) whenever you need that task to be performed.
Think of a function as a reusable tool — once it’s built, you don’t have to rebuild it every time you want to use it.
Imagine a coffee machine:
This is like a function:
function makeCoffee() {
console.log("Here is your coffee ☕");
}
makeCoffee();
✅ It runs when you call makeCoffee()
✅ It produces an output without repeating the steps manually
| Without Functions | With Functions |
|---|---|
| Code gets long and repetitive | Code is shorter and reusable |
| Hard to maintain or change | Easy to update one function in one place |
| Difficult to test and understand | Clear separation of logic into tasks |
Functions help with:
A function can:
function greet() {
console.log("Hello, world!");
}
function: keyword to start the function definitiongreet: the name of the function() → for input values (called parameters; more later){} → the block of code that will rungreet(); // Output: Hello, world!
Without a function:
console.log("Hello, world!");
console.log("Hello, world!");
console.log("Hello, world!");
With a function:
function greet() {
console.log("Hello, world!");
}
greet();
greet();
greet();
✅ Same result — cleaner code
| Term | Meaning |
|---|---|
| Function | A reusable block of code that performs a task |
| Call | Using a function to run the code inside |
| Parameter | A placeholder for data passed into the function (later lesson) |
| Return | Sending data back from a function (later lesson) |