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
βœ… Output: 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");
βœ… Output:
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
πŸ’‘ The 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 🌟"
βœ… Reusable, readable, and clean.

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
βœ… Cleaner and commonly used in modern JS.

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"
βœ… Variables inside a function do not affect variables outside it.

7) Best Practices for Functions

  • βœ… One function = one clear task
  • βœ… Use descriptive names (calculateTotal, not doThing)
  • βœ… 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);
βœ… Clean and maintainable β€” just update the numbers to refresh the summary.

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)}`;
βœ… Functions + loops = powerful dynamic data display.

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);
βœ… Adds reusable functionality with a single click!

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>
βœ… You now have a function-driven component that can be reused anywhere in your portfolio.

🏁 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.