Lesson 5: Functions - Reusable Code Blocks

What You'll Learn

  • What functions are and why they're essential
  • How to create and call functions
  • How to pass information to functions (parameters)
  • How to get results from functions (return values)
  • Different ways to write functions in JavaScript

Why This Matters

Functions are like recipes - you write the instructions once, then use them as many times as you need. They help you:

  • Avoid repeating the same code
  • Organize your program into logical pieces
  • Make code easier to understand and maintain
  • Reuse code across different projects

---

Part 1: What is a Function?

A function is a named block of code that performs a specific task.

Think of it like a machine:

  • Input: You give it information (parameters)
  • Process: It does something with that information
  • Output: It gives you back a result (return value)

---

Part 2: Creating Your First Function

Create a new file: lesson-05/functions.js

Basic Function (No Parameters, No Return)

function greet() {
  console.log("Hello, World!");
}

// Call (execute) the function
greet();
greet();
greet();
Output:
Hello, World!
Hello, World!
Hello, World!

Understanding the Syntax

function functionName() {
  // Code to execute
}
  • function: Keyword to create a function
  • functionName: Name you give the function (use camelCase)
  • (): Parentheses (will hold parameters later)
  • { }: Curly braces contain the function's code
  • Calling: Use the function name followed by () to execute it

Why Use Functions?

Without functions:
console.log("Welcome to the game!");
console.log("Loading...");
console.log("Ready!");

// Later in code...
console.log("Welcome to the game!");
console.log("Loading...");
console.log("Ready!");

// And again...
console.log("Welcome to the game!");
console.log("Loading...");
console.log("Ready!");
With functions:
function showWelcome() {
  console.log("Welcome to the game!");
  console.log("Loading...");
  console.log("Ready!");
}

showWelcome();  // Use once
showWelcome();  // Use again
showWelcome();  // Use anywhere!

---

Part 3: Functions with Parameters

Parameters let you pass information into a function.

function greetPerson(name) {
  console.log(`Hello, ${name}!`);
}

greetPerson("Alice");   // Output: Hello, Alice!
greetPerson("Bob");     // Output: Hello, Bob!
greetPerson("Charlie"); // Output: Hello, Charlie!

Understanding Parameters

function functionName(parameter) {
  // Use parameter here
}
  • parameter: A variable name you use inside the function
  • Argument: The actual value you pass when calling: greetPerson("Alice")

Multiple Parameters

function introduce(name, age) {
  console.log(`My name is ${name} and I am ${age} years old.`);
}

introduce("Emma", 25);
// Output: My name is Emma and I am 25 years old.

introduce("John", 30);
// Output: My name is John and I am 30 years old.
Parameter order matters! The first argument goes to the first parameter, second to second, etc.

Default Parameters

You can give parameters default values:

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}

greet("Alice");  // Hello, Alice!
greet();         // Hello, Guest! (uses default)

---

Part 4: Functions with Return Values

Functions can send data back using return.

function add(a, b) {
  return a + b;
}

const result = add(5, 3);
console.log(result);  // Output: 8

console.log(add(10, 20));  // Output: 30

Understanding Return

function functionName(params) {
  return value;
}
  • return: Keyword that sends a value back and exits the function
  • The returned value can be stored in a variable or used directly

Return Stops the Function

function checkAge(age) {
  if (age >= 18) {
    return "Adult";  // Function stops here if true
  }
  return "Minor";    // Only reached if age < 18
}

console.log(checkAge(25));  // Adult
console.log(checkAge(15));  // Minor

Once return runs, the function immediately stops and exits.

Functions Without Return

If a function doesn't return anything, it simply performs an action:

function logMessage(message) {
  console.log(message);
  // No return statement
}

logMessage("Hello!");

Part 5: Function Expressions

You can also create functions as values:

const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5));  // Output: 20

Arrow Functions (Modern Syntax)

Arrow functions are a shorter way to write functions:

// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow function
const add2 = (a, b) => {
  return a + b;
};

// Arrow function (even shorter - implicit return)
const add3 = (a, b) => a + b;

console.log(add3(5, 3));  // Output: 8

Arrow Function Syntax

// Multiple lines (explicit return)
const funcName = (param) => {
  // code
  return value;
};

// Single expression (implicit return)
const funcName = (param) => expression;

// Single parameter (parentheses optional)
const square = (n) => n * n;

// No parameters
const greet = () => console.log("Hi!");

Part 6: Function Scope

Variables created inside functions are local to that function:

function calculateArea() {
  const width = 10;    // Local variable
  const height = 5;    // Local variable
  return width * height;
}

console.log(calculateArea());  // Output: 50
console.log(width);            // ❌ ERROR! width doesn't exist here

Global vs Local Scope

const globalVar = "I'm global";  // Available everywhere

function example() {
  const localVar = "I'm local";  // Only in this function
  console.log(globalVar);   // ✅ Can access global
  console.log(localVar);    // ✅ Can access local
}

example();
console.log(globalVar);  // ✅ Can access global
console.log(localVar);   // ❌ ERROR! Not available here
Best practice: Keep variables as local as possible. Use parameters instead of global variables.

Part 7: Practical Examples

Example 1: Temperature Converter

function celsiusToFahrenheit(celsius) {
  return celsius * 9/5 + 32;
}

function fahrenheitToCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5/9;
}

console.log(`25°C = ${celsiusToFahrenheit(25)}°F`);  // 77°F
console.log(`77°F = ${fahrenheitToCelsius(77)}°C`);  // 25°C

Example 2: Validation Function

function isValidAge(age) {
  return age >= 0 && age <= 120;
}

console.log(isValidAge(25));   // true
console.log(isValidAge(-5));   // false
console.log(isValidAge(150));  // false

Example 3: Greeting Based on Time

function greetByTime(hour) {
  if (hour >= 5 && hour < 12) {
    return "Good morning!";
  } else if (hour >= 12 && hour < 18) {
    return "Good afternoon!";
  } else if (hour >= 18 && hour < 22) {
    return "Good evening!";
  } else {
    return "Good night!";
  }
}

console.log(greetByTime(9));   // Good morning!
console.log(greetByTime(14));  // Good afternoon!
console.log(greetByTime(20));  // Good evening!

Example 4: Calculate Discount

function calculateDiscount(price, discountPercent) {
  const discount = price * (discountPercent / 100);
  return price - discount;
}

const originalPrice = 100;
const finalPrice = calculateDiscount(originalPrice, 20);
console.log(`Original: $${originalPrice}, Final: $${finalPrice}`);
// Output: Original: $100, Final: $80

Practice Exercises

Exercise 1: Rectangle Area

Create a function that calculates the area of a rectangle:

function calculateRectangleArea(width, height) {
  // Your code here
}

Exercise 2: Even or Odd

Create a function that returns true if a number is even, false if odd:

function isEven(num) {
  // Your code here
}

Exercise 3: Max of Two Numbers

Create a function that returns the larger of two numbers:

function max(a, b) {
  // Your code here
}

Exercise 4: Full Name

Create a function that takes first and last name and returns full name:

function getFullName(firstName, lastName) {
  // Your code here
}

Exercise 5: Grade Letter

Create a function that converts a numeric grade to a letter (A-F):

function getGradeLetter(score) {
  // Your code here
}

Exercise 6: Password Validator

Create a function that checks if a password is strong (at least 8 characters):

function isStrongPassword(password) {
  // Your code here
}

Common Mistakes

Mistake 1: Forgetting to Call the Function

function greet() {
  console.log("Hello!");
}

greet;  // ❌ Does nothing! Missing ()
greet();  // ✅ Correct - actually calls the function

Mistake 2: Wrong Number of Arguments

function add(a, b) {
  return a + b;
}

add(5);      // ❌ ERROR! Missing second argument
add(5, 3);   // ✅ Correct
add(5, 3, 2);  // ❌ ERROR! Too many arguments

Mistake 3: Forgetting to Return

function add(a, b) {
  a + b;  // ❌ Calculated but not returned!
}

const result = add(5, 3);
console.log(result);  // undefined

// Fix:
function add(a, b) {
  return a + b;  // ✅ Return the result
}

Mistake 4: Using Variables Outside Scope

function calculate() {
  const result = 42;
}

console.log(result);  // ❌ ERROR! result is not defined here

---

Key Concepts Summary

Concept Definition Example
Function Reusable block of code function greet() { }
Parameter Input variable in function definition function add(a, b)
Argument Actual value passed to function add(5, 3)
Return Send a value back from function return result;
void Function returns nothing function log()
Arrow function Shorter function syntax const add = (a, b) => a + b
Scope Where variables are accessible Local vs Global

What You Learned

  • ✅ How to create functions with the function keyword
  • ✅ How to pass data to functions using parameters
  • ✅ How to return values from functions
  • ✅ How to use arrow functions (modern syntax)
  • ✅ The difference between parameters and arguments
  • ✅ Function scope and variable visibility
  • ✅ When and why to use functions

What's Next?

In the next lesson, you'll learn about arrays - how to store and work with lists of data!