⚙️ Lesson 16: Functions

Functions are reusable blocks of code that perform a specific task. They help you avoid repeating code and make your programs more organized.

Defining Functions

Function Declaration

Traditional way to define functions:

function greet(name) { console.log("Hello, " + name); } greet("Alice"); // Output: Hello, Alice greet("Bob"); // Output: Hello, Bob

Function Expression

Assign a function to a variable:

const add = function(a, b) { return a + b; }; console.log(add(5, 3)); // 8

Arrow Function (Modern)

Concise syntax using arrow (=>):

const multiply = (a, b) => { return a * b; }; const square = (x) => x * x; // Implicit return console.log(multiply(4, 5)); // 20 console.log(square(5)); // 25

Parameters and Arguments

Parameters are variables defined in the function. Arguments are values passed to the function.

// Parameters: name, age function introduce(name, age) { console.log(`I am ${name} and I am ${age} years old`); } // Arguments: "Alice", 28 introduce("Alice", 28);

Return Values

Functions can return values using the return keyword:

function calculateTotal(price, quantity) { return price * quantity; } let total = calculateTotal(10, 5); // 50 console.log(total);

Multiple Returns

Return different values based on conditions:

function checkAge(age) { if (age >= 18) { return "Adult"; } else { return "Minor"; } } console.log(checkAge(25)); // "Adult" console.log(checkAge(15)); // "Minor"

Default Parameters

Set default values for parameters:

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

Rest Parameters

Accept any number of arguments using ...:

function sum(...numbers) { let total = 0; for (let num of numbers) { total += num; } return total; } console.log(sum(1, 2, 3)); // 6 console.log(sum(1, 2, 3, 4, 5)); // 15

Scope

Where variables are accessible:

Global Scope

let globalVar = "I'm global"; function myFunction() { console.log(globalVar); // Can access }

Local/Function Scope

function myFunction() { let localVar = "I'm local"; console.log(localVar); // Can access } console.log(localVar); // ERROR - not accessible

Block Scope (let/const)

if (true) { let blockVar = "Block scope"; const blockConst = "Also block"; } console.log(blockVar); // ERROR - not accessible

Practical Examples

Calculator Function

function calculate(a, b, operation) { if (operation === "+") { return a + b; } else if (operation === "-") { return a - b; } else if (operation === "*") { return a * b; } else if (operation === "/") { return a / b; } } console.log(calculate(10, 5, "+")); // 15 console.log(calculate(10, 5, "*")); // 50

Check Password Strength

function checkPasswordStrength(password) { if (password.length < 6) { return "Weak"; } else if (password.length < 10) { return "Medium"; } else { return "Strong"; } } console.log(checkPasswordStrength("123")); // Weak console.log(checkPasswordStrength("password")); // Medium console.log(checkPasswordStrength("MyStr0ng!Pwd")); // Strong

Function Hoisting

Function declarations are hoisted (moved to top), but function expressions are not:

// OK - declaration is hoisted myFunction(); function myFunction() { console.log("Hello"); } // ERROR - expression is not hoisted myExpression(); const myExpression = function() { console.log("Hello"); };

Callback Functions

Pass functions as arguments to other functions:

function greetWith(greeting, name, callback) { let message = greeting + ", " + name; callback(message); } function logMessage(msg) { console.log(msg); } greetWith("Hello", "Alice", logMessage); // Hello, Alice

Interactive Example

Key Takeaways

← Back to Course | ← Previous | Next: DOM Manipulation →