Write Functions
Learning Objectives
- Understand functions and their purpose
- Learn function declaration and invocation
- Master parameters and return values
- Understand anonymous functions
- Apply functions to organize code
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?
- Reusability: Write once, use many times
- Organization: Keep code organized and readable
- Maintainability: Easier to update and debug
- Modularity: Break large problems into smaller pieces
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:
- Takes a name and age as input
- Returns a personalized greeting
- displays the result
Challenge 6.2: Number Squaring
Task: Create a function that:
- Takes a number as input
- Returns the square of that number
- Test with different values
Challenge 6.3: Minimum of Two Numbers
Task: Create a function that:
- Takes two numbers as parameters
- Returns the smaller of the two
- Test with various inputs
Challenge 6.4: Calculator
Task: Create functions for:
- Addition
- Subtraction
- Multiplication
- Division
- Use each function to calculate results
Challenge 6.5: Circumference and Area of a Circle
Task: Create functions to calculate:
- Circumference: 2πr
- Area: πr²
- Take radius as input parameter
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
- Why would you use a function instead of writing code directly?
- What's the difference between parameters and arguments?
- How does a return statement work?
- What is an arrow function?
- How do you call a function?
Next Module: Module 7 - Create your First Object