Functions: Reusable Code
Functions are reusable code blocks. They're fundamental!
Why Use Functions?
Without function:
javascript
console.log("Hello, Maria!");console.log("Hello, John!");console.log("Hello, Anna!");With function:
javascript
function greet(name) { console.log(`Hello, ${name}!`);} greet("Maria");greet("John");greet("Anna");Advantages:
- Reuse - write once, use many times
- Organization - code is more readable
- Maintenance - change in one place
Creating Functions
Function Declaration
javascript
function greet() { console.log("Hello!");} greet(); // calling the functionFunction with Parameters
javascript
function greet(name) { console.log(`Hello, ${name}!`);} greet("Maria"); // "Hello, Maria!"greet("John"); // "Hello, John!"Function with Return
javascript
function sum(a, b) { return a + b;} const result = sum(5, 3);console.log(result); // 8return sends the value back and ends the function.
Function Expression
javascript
const greet = function(name) { return `Hello, ${name}!`;}; console.log(greet("Maria"));Arrow Function (Modern)
javascript
// With braces (multiple lines)const greet = (name) => { return `Hello, ${name}!`;}; // Simplified (one line)const greet = (name) => `Hello, ${name}!`; // One parameter (no parentheses needed)const double = n => n * 2; // No parametersconst sayHi = () => "Hi!";Default Parameters
javascript
function greet(name = "visitor") { console.log(`Hello, ${name}!`);} greet(); // "Hello, visitor!"greet("Maria"); // "Hello, Maria!"Multiple Parameters
javascript
function createProfile(name, age, city) { return { name: name, age: age, city: city };} const profile = createProfile("John", 25, "NYC");Scope
Where variables exist:
javascript
const global = "I exist everywhere"; function test() { const local = "I only exist in here"; console.log(global); // ✅ Works console.log(local); // ✅ Works} console.log(global); // ✅ Worksconsole.log(local); // ❌ Error!Functions Calling Functions
javascript
function square(n) { return n * n;} function squareSum(a, b) { return square(a) + square(b);} console.log(squareSum(3, 4)); // 9 + 16 = 25Higher-Order Functions
Functions that receive other functions:
javascript
const numbers = [1, 2, 3, 4, 5]; // map - transforms each elementconst doubled = numbers.map(n => n * 2);// [2, 4, 6, 8, 10] // filter - filters elementsconst evens = numbers.filter(n => n % 2 === 0);// [2, 4] // find - finds first matchconst greaterThan3 = numbers.find(n => n > 3);// 4 // reduce - accumulatesconst sum = numbers.reduce((acc, n) => acc + n, 0);// 15Practical Exercise: Calculator
javascript
function add(a, b) { return a + b;} function subtract(a, b) { return a - b;} function multiply(a, b) { return a * b;} function divide(a, b) { if (b === 0) { return "Error: cannot divide by zero"; } return a / b;} function calculate(a, operator, b) { switch (operator) { case "+": return add(a, b); case "-": return subtract(a, b); case "*": return multiply(a, b); case "/": return divide(a, b); default: return "Invalid operator"; }} // Usageconsole.log(calculate(10, "+", 5)); // 15console.log(calculate(10, "-", 3)); // 7console.log(calculate(4, "*", 3)); // 12console.log(calculate(20, "/", 4)); // 5Tips
- Descriptive names:
calculateAverageis better thancalc - One thing per function: if the name has "and", maybe split it
- Few parameters: ideally up to 3
- Always return: even if it's a message
Summary
- ✅ Functions organize and reuse code
- ✅ Parameters make them flexible
- ✅
returnsends value back - ✅ Arrow functions are modern and concise
- ✅ Scope controls where variables exist
In the next lesson, we'll learn arrays and objects! 🚀