JavaScript Foundations β’ StreetGeek Academy
π§ MODULE 4: Functions & Scope β Writing Reusable Code
Understand how to define, call, and reuse JavaScript functions, how parameters and return values work, and how scope affects where variables can be accessed.
1) What Is a Function?
A function is a reusable block of code that performs a specific task.
Instead of writing the same logic over and over, you define it once and call it whenever needed.
Basic Syntax
function greet() {
console.log("Welcome to StreetGeek!");
}
greet(); // Call the function
Welcome to StreetGeek!
2) Parameters and Arguments
Functions can take parameters (placeholders) that receive arguments (real values).
function greetUser(name) {
console.log(`Hello, ${name}! Welcome back.`);
}
greetUser("Yogi");
greetUser("Alex");
Hello, Yogi! Welcome back.Hello, Alex! Welcome back.
You can use multiple parameters:
function showScore(user, score) {
console.log(`${user} scored ${score} points!`);
}
showScore("Yogi", 95);
3) Return Values
Functions can return data back to where they were called.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // 8
return statement ends the function immediately.Example: Portfolio Status Function
function getPortfolioStatus(projects) {
if (projects >= 10) return "Pro Developer π§ ";
if (projects >= 5) return "Rising Star π";
return "Beginner β‘";
}
let level = getPortfolioStatus(8);
console.log(level); // "Rising Star π"
4) Function Expressions
You can also store a function inside a variable:
const multiply = function (x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20
5) Arrow Functions (ES6+)
A shorter syntax for writing functions.
const greet = (name) => {
return `Hello, ${name}!`;
};
console.log(greet("Yogi"));
If the function is only one line, you can omit the return and {}:
const double = n => n * 2;
console.log(double(10)); // 20
6) Scope: Where Variables βLiveβ
Scope determines where a variable is accessible in your code.
| Type | Created By | Accessible In |
|---|---|---|
| Global Scope | Declared outside any function | Everywhere |
| Function Scope | Inside a function (var) |
That function only |
| Block Scope | Inside {} with let or const |
That block only |
Example
let message = "Global Message";
function showMessage() {
let message = "Local Message";
console.log(message);
}
showMessage(); // "Local Message"
console.log(message); // "Global Message"
7) Best Practices for Functions
- β One function = one clear task
- β
Use descriptive names (
calculateTotal, notdoThing) - β Avoid relying on global variables when possible
- β Keep functions small and reusable
8) Hands-On Practice
Exercise 1: Reusable Greeting Function
function greetUser(name, timeOfDay) {
console.log(`Good ${timeOfDay}, ${name}!`);
}
greetUser("Yogi", "morning");
greetUser("StreetGeek Student", "afternoon");
Exercise 2: Dynamic Portfolio Summary Function
<p id="portfolio-summary"></p>
function getSummary(projects, followers) {
return `You have ${projects} projects and ${followers} followers.`;
}
const summaryText = document.getElementById("portfolio-summary");
summaryText.textContent = getSummary(8, 152);
Exercise 3: Calculate Total Visitors
<p id="visitor-stats"></p>
function getTotalVisitors(visits) {
let total = 0;
for (let i = 0; i < visits.length; i++) {
total += visits[i];
}
return total;
}
const weekVisits = [120, 90, 150, 200, 130, 80, 170];
const visitorStats = document.getElementById("visitor-stats");
visitorStats.textContent = `This weekβs visitors: ${getTotalVisitors(weekVisits)}`;
Exercise 4 (Bonus): Arrow Function Dark Mode Toggle
<button id="dark-mode-btn">Toggle Dark Mode</button>
const darkModeBtn = document.getElementById("dark-mode-btn");
const toggleDarkMode = () => {
document.body.classList.toggle("dark");
console.log("Dark mode toggled π");
};
darkModeBtn.addEventListener("click", toggleDarkMode);
9) Quiz Time
Show/Hide Questions
1) Whatβs the main purpose of a function?
2) Whatβs the difference between function add() {} and const add = () => {}?
3) What happens when a function reaches a return statement?
4) Whatβs the difference between global and local scope?
5) How would you pass data into a function?
π Challenge Task: Reusable Stats Module
Add a Reusable Stats Module to your portfolio homepage.
In app.js:
function getBadge(projects) {
if (projects >= 10) return "Gold π
";
if (projects >= 5) return "Silver π₯";
return "Bronze π₯";
}
function updateStats(name, projects) {
const stats = document.getElementById("stats");
const badge = getBadge(projects);
stats.textContent = `${name} has completed ${projects} projects β ${badge} Badge Earned!`;
}
updateStats("Yogi", 8);
In index.html:
<p id="stats"></p>
π Module 4 Summary
- How to define and call functions
- How to pass and return data
- The difference between global, function, and block scope
- How to use arrow functions
- How to modularize and reuse logic in your portfolio
Next up β MODULE 5: Arrays & Objects (ES6 Essentials)
Youβll learn how to store and manage collections of data β and dynamically generate portfolio sections like your projects list straight from JavaScript.