Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the health-check domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/yogisv5/sitesbyyogi.com/wp-includes/functions.php on line 6260
MODULE 4: Functions & Scope β€” Writing Reusable Code - SitesByYogi

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

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

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.