By the end of this lesson, learners will be able to:
In programming, a function is a reusable block of code designed to do a specific task.
Instead of writing the same instructions multiple times, we define them once in a function and then call that function whenever we need it.
Imagine a coffee machine:
The coffee machine is a function:
Here’s why functions are crucial in JavaScript (and all programming):
Reason | Explanation |
---|---|
✅ Reusability | Write code once, reuse it everywhere |
✅ Clarity | Break code into readable, manageable chunks |
✅ Maintainability | Update logic in one place instead of many |
✅ DRY Principle | Don’t Repeat Yourself – avoid copying the same code repeatedly |
✅ Testing | Functions are easier to test and debug |
function functionName() {
// code to run when the function is called
}
function
: JavaScript keyword to define a functionfunctionName
: any valid name (should describe what it does)()
– parentheses can hold parameters (covered in next lessons){}
– curly braces enclose the function body (code to run)function greetUser() {
console.log("Hello! Welcome to Codevisionz!");
}
✅ This function is now defined, but it won’t do anything until you call it.
greetUser(); // Output: Hello! Welcome to Codevisionz!
greetUser
.console.log("Welcome!");
console.log("Welcome!");
console.log("Welcome!");
function sayWelcome() {
console.log("Welcome!");
}
sayWelcome();
sayWelcome();
sayWelcome();
➡️ Same result, but cleaner, more reusable code.
printMessage()
is better than doThing()
greetUser()
, calculateTotal()
)Term | Description |
---|---|
Function | A block of code that performs a task |
Define | Writing the function once with the function keyword |
Call | Running the function using its name followed by () |
Body | The code inside the function’s {} that runs when called |