Function Mastery: From Beginner to Clean Code
When your code gets long and copy–paste starts spreading, that's your sign: you need functions.
Functions separate script writers from real developers.
What Is a Function?
A function is a reusable block of logic.
function sayHello() {
console.log("Hello world 👋");
}
sayHello();Instead of repeating logic, you wrap it once and reuse it.
Function Declaration vs Expression
Function Declaration
function greet() {
console.log("Hi!");
}- Can be called before declaration
- Good for core logic
Function Expression
const greet = function() {
console.log("Hi!");
};- Stored in a variable
- More predictable
- Common in modern codebases
Arrow Functions
Cleaner. Shorter. Modern.
const greet = () => {
console.log("Hello!");
};Ultra-short version:
const greet = () => console.log("Hello!");This is what you'll see in React and modern projects.
Return Value
Without return, a function only talks. With return, it gives results.
function add(a, b) {
return a + b;
}
let result = add(3, 4);
console.log(result);No return? You get undefined.
Parameters & Default Values
function greet(name) {
console.log("Hello " + name);
}
greet("Syfa");Default parameter:
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet();Safe, clean, no runtime errors.
Scope: Global vs Local
Global Scope
let name = "Syfa";
function showName() {
console.log(name);
}Everyone can access it. Dangerous at scale.
Local Scope
function showAge() {
let age = 20;
console.log(age);
}Local variables stay inside. Cleaner. Safer.
Mini Project — Simple Calculator
function calculate(a, b, operator) {
if (operator === "+") return a + b;
if (operator === "-") return a - b;
if (operator === "*") return a * b;
if (operator === "/") return a / b;
return "Invalid operator";
}
console.log(calculate(10, 5, "+"));
console.log(calculate(10, 5, "*"));This is real-world logic, not toy code.
Mini Project — Random Quote Generator
const quotes = [
"Stay hungry, stay foolish.",
"Code. Sleep. Repeat.",
"Consistency beats talent."
];
function getRandomQuote() {
let index = Math.floor(Math.random() * quotes.length);
return quotes[index];
}
console.log(getRandomQuote());This connects perfectly to DOM later.
Mini Challenges
- Function: return "Even" or "Odd"
- Function: input score → return grade
- Function: login validation
Try first. Solutions come later.
Why This Module Is Critical
- DOM uses functions
- Events are functions
- Fetch API uses functions
- React is function-based
No functions = chaotic codebase.
