Write Functions

Learning Objectives

Section 6.1: Discovering Functions

What is a Function?

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

Why Use Functions?

Simple Function

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

greet();  // Call the function
greet();  // Call again

Section 6.2: Function Contents

Function with Parameters

Parameters are variables that store input values:

function greetUser(name) {
    console.log("Hello, " + name + "!");
}

greetUser("Alice");   // Hello, Alice!
greetUser("Bob");     // Hello, Bob!

Multiple Parameters

function add(a, b) {
    console.log(a + b);
}

add(5, 3);    // 8
add(10, 20);  // 30

Return Values

Functions can return a value:

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

let result = multiply(4, 5);
console.log(result);  // 20

Function with Multiple Operations

function squareNumber(num) {
    let squared = num * num;
    return squared;
}

console.log(squareNumber(5));  // 25

Early Return

function checkAge(age) {
    if (age < 18) {
        return "You are a minor";
    }
    return "You are an adult";
}

console.log(checkAge(15));  // You are a minor
console.log(checkAge(25));  // You are an adult

Functions Without Return

function displayMessage(msg) {
    console.log(msg);  // No return statement
}

displayMessage("Hello");  // Prints "Hello"

Section 6.3: Anonymous Functions

What is an Anonymous Function?

A function without a name, stored in a variable:

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

console.log(add(5, 3));  // 8

Arrow Functions (Modern Syntax)

Shorter syntax for anonymous functions:

let multiply = (a, b) => {
    return a * b;
};

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

Arrow Function Shorthand

// Short form for single return statement
let square = x => x * x;

console.log(square(5));  // 25

Comparison

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

// Function expression
let addExpr = function(a, b) {
    return a + b;
};

// Arrow function
let addArrow = (a, b) => a + b;

Section 6.4: Guidelines for Programming with Functions

Writing Good Functions

// ✅ GOOD: Clear what it does
function calculateTax(price, taxRate) {
    return price * taxRate;
}

// ❌ BAD: Unclear purpose
function calc(p, r) {
    return p * r;
}
// ✅ GOOD: Function does one thing
function validateEmail(email) {
    return email.includes("@");
}

// ❌ BAD: Too many responsibilities
function validateAndSaveUser(email, name, password) {
    // Validation AND saving
}
// ✅ GOOD
function isAdult(age) { return age >= 18; }

// ❌ BAD
function check(a) { return a >= 18; }
// ✅ GOOD
function calculateDiscount(originalPrice, discountRate) {
    return originalPrice * discountRate;
}

// ❌ BAD
function calc(a, b) {
    return a * b;
}

Default Parameters

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

greet();           // Hello, Guest
greet("Alice");    // Hello, Alice

Coding Challenges

Challenge 6.1: Improved Hello

Task: Create a function that:

Challenge 6.2: Number Squaring

Task: Create a function that:

Challenge 6.3: Minimum of Two Numbers

Task: Create a function that:

Challenge 6.4: Calculator

Task: Create functions for:

Challenge 6.5: Circumference and Area of a Circle

Task: Create functions to calculate:

Key Takeaways

✅ Functions organize and reuse code
✅ Parameters allow functions to accept input
✅ Return statements provide output values
✅ Anonymous and arrow functions are shorter syntax
✅ Functions should have clear, single purpose
✅ Use meaningful names for functions and parameters

Quiz Questions


Next Module: Module 7 - Create your First Object