HTML & JS Topic

JavaScript Functions 

1. Function Declaration (Named Functions)

Basic Syntax:

javascript

// Function declaration (hoisted - can be called before declaration)
function greet() {
    console.log("Hello, world!");
}

// Calling the function
greet(); // Output: "Hello, world!"

Hoisting Example:

javascript

// This works because function declarations are hoisted
sayHello(); // Output: "Hello!"

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

2. Function Parameters & Arguments

Single Parameter:

javascript

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

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

Multiple Parameters:

javascript

function calculateTotal(price, quantity, taxRate) {
    const subtotal = price * quantity;
    const tax = subtotal * taxRate;
    return subtotal + tax;
}

const total = calculateTotal(10, 3, 0.08);
console.log(total); // 32.4

Default Parameters (ES6+):

javascript

function createUser(name, role = "user", isActive = true) {
    return {
        name: name,
        role: role,
        isActive: isActive
    };
}

console.log(createUser("Alice")); 
// {name: "Alice", role: "user", isActive: true}

console.log(createUser("Bob", "admin", false));
// {name: "Bob", role: "admin", isActive: false}

Rest Parameters (...):

javascript

// Collects all remaining arguments into an array
function sumAll(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}

console.log(sumAll(1, 2, 3));        // 6
console.log(sumAll(1, 2, 3, 4, 5));  // 15

Parameters vs Arguments:

javascript

// Parameters are the variables in function definition
function multiply(a, b) {  // a and b are parameters
    return a * b;
}

// Arguments are the actual values passed
multiply(5, 3);  // 5 and 3 are arguments

3. Return Values

Returning a Value:

javascript

function add(a, b) {
    return a + b;  // Returns the sum
}

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

Multiple Returns (Conditional):

javascript

function getGrade(score) {
    if (score >= 90) {
        return "A";
    } else if (score >= 80) {
        return "B";
    } else if (score >= 70) {
        return "C";
    } else {
        return "F";
    }
    // Any code here won't execute
}

console.log(getGrade(85)); // "B"

Returning Early:

javascript

function login(username, password) {
    // Early return for invalid input
    if (!username || !password) {
        return "Please enter both username and password";
    }
    
    // Early return for authentication failure
    if (username !== "admin" || password !== "1234") {
        return "Invalid credentials";
    }
    
    // Main logic for successful login
    return "Login successful!";
}

console.log(login("", ""));        // "Please enter both..."
console.log(login("user", "pass")); // "Invalid credentials"
console.log(login("admin", "1234")); // "Login successful!"

Returning Multiple Values:

javascript

// Return an object
function getStats(numbers) {
    const sum = numbers.reduce((a, b) => a + b, 0);
    const avg = sum / numbers.length;
    const max = Math.max(...numbers);
    const min = Math.min(...numbers);
    
    return {
        sum: sum,
        average: avg,
        maximum: max,
        minimum: min
    };
}

const stats = getStats([10, 20, 30, 40, 50]);
console.log(stats.average); // 30
console.log(stats.maximum); // 50

// Return an array (destructure)
function getCoordinates() {
    return [40.7128, -74.0060]; // [latitude, longitude]
}

const [lat, lon] = getCoordinates();
console.log(`Lat: ${lat}, Lon: ${lon}`);

4. Function Expression

javascript

// Anonymous function assigned to a variable
const sayHello = function() {
    console.log("Hello!");
};

sayHello(); // Output: "Hello!"

// Named function expression (useful for debugging)
const factorial = function fact(n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);  // Can reference itself
};

console.log(factorial(5)); // 120

5. Arrow Functions (ES6+)

Basic Syntax:

javascript

// Traditional function
const addTraditional = function(a, b) {
    return a + b;
};

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

// Even shorter (implicit return)
const addShort = (a, b) => a + b;

console.log(addTraditional(2, 3)); // 5
console.log(addArrow(2, 3));       // 5
console.log(addShort(2, 3));       // 5

Different Arrow Function Forms:

javascript

// Single parameter - parentheses optional
const square = x => x * x;

// No parameters - parentheses required
const greet = () => "Hello, World!";

// Multiple parameters - parentheses required
const multiply = (a, b) => a * b;

// Multiple lines - braces and return needed
const calculate = (a, b) => {
    const sum = a + b;
    const product = a * b;
    return { sum, product };
};

// Returning objects - wrap in parentheses
const createUser = (name, age) => ({
    name: name,
    age: age,
    isAdult: age >= 18
});

Arrow Functions vs Regular Functions:

javascript

// 1. 'this' binding
const person = {
    name: "Alice",
    
    // Regular function - 'this' refers to person object
    greetTraditional: function() {
        console.log(`Hello, I'm ${this.name}`);
    },
    
    // Arrow function - 'this' refers to outer scope (window/global)
    greetArrow: () => {
        console.log(`Hello, I'm ${this.name}`); // undefined
    }
};

person.greetTraditional(); // "Hello, I'm Alice"
person.greetArrow();       // "Hello, I'm undefined"

// 2. Cannot be used as constructors
function Car(make) { this.make = make; }  // OK
const CarArrow = (make) => { this.make = make; };  // Error
// new CarArrow("Toyota"); // TypeError

// 3. No 'arguments' object in arrow functions
function regularFunc() {
    console.log(arguments); // Works
}

const arrowFunc = () => {
    console.log(arguments); // ReferenceError
};

6. Practical Examples

Example 1: Calculator Functions

javascript

// Function declarations for calculator
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 "Cannot divide by zero";
    return a / b; 
}

// Using the functions
const x = 10, y = 5;
console.log(add(x, y));        // 15
console.log(subtract(x, y));   // 5
console.log(multiply(x, y));   // 50
console.log(divide(x, y));     // 2

// Calculator object with arrow functions
const calculator = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => b !== 0 ? a / b : "Error",
    calculate: function(operation, a, b) {
        return this[operation](a, b);
    }
};

console.log(calculator.calculate("add", 10, 5)); // 15

Example 2: User Validation

javascript

// Arrow functions for validation
const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
};

const validatePassword = (password) => {
    return password.length >= 8 && 
           /[A-Z]/.test(password) &&
           /[0-9]/.test(password);
};

const validateUser = (email, password) => {
    const errors = [];
    
    if (!validateEmail(email)) {
        errors.push("Invalid email format");
    }
    
    if (!validatePassword(password)) {
        errors.push("Password must be at least 8 characters with uppercase and number");
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
};

// Usage
const result = validateUser("user@example.com", "Pass1234");
console.log(result.isValid ? "Valid!" : `Errors: ${result.errors.join(", ")}`);

Example 3: Array Processing

javascript

const numbers = [1, 2, 3, 4, 5];

// Traditional function
const doubledTraditional = numbers.map(function(num) {
    return num * 2;
});

// Arrow function (much cleaner)
const doubledArrow = numbers.map(num => num * 2);

// Multiple operations
const processed = numbers
    .filter(num => num % 2 === 0)      // Keep even numbers
    .map(num => num * 3)               // Multiply by 3
    .reduce((total, num) => total + num, 0); // Sum them up

console.log(doubledArrow);  // [2, 4, 6, 8, 10]
console.log(processed);     // 18 (2*3 + 4*3 = 6 + 12 = 18)

Example 4: Callback Functions

javascript

// Higher-order function that accepts a callback
function processUserInput(callback) {
    const name = prompt("Please enter your name:");
    callback(name);
}

// Regular function as callback
function greet(name) {
    console.log(`Hello, ${name}!`);
}

// Arrow function as callback
const shout = (name) => {
    console.log(`HELLO, ${name.toUpperCase()}!`);
};

// Using the callbacks
processUserInput(greet);   // Shows prompt, then "Hello, [name]!"
processUserInput(shout);   // Shows prompt, then "HELLO, [NAME]!"

// Inline arrow function as callback
processUserInput(name => {
    console.log(`Welcome aboard, ${name}!`);
});

7. Common Patterns & Best Practices

Function Composition:

javascript

const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const square = x => x * x;

// Compose functions
const result = square(add(multiply(2, 3), 4));
// multiply(2, 3) = 6
// add(6, 4) = 10
// square(10) = 100
console.log(result); // 100

IIFE (Immediately Invoked Function Expression):

javascript

// Traditional IIFE
(function() {
    console.log("This runs immediately!");
})();

// Arrow function IIFE
(() => {
    console.log("This also runs immediately!");
})();

// IIFE with parameters
((name) => {
    console.log(`Hello, ${name}!`);
})("Alice");

Factory Functions:

javascript

// Function that creates and returns objects
function createPerson(name, age) {
    return {
        name,
        age,
        greet() {
            console.log(`Hi, I'm ${this.name}`);
        },
        // Arrow function for methods that don't need 'this'
        getBirthYear: () => new Date().getFullYear() - age
    };
}

const alice = createPerson("Alice", 25);
alice.greet(); // "Hi, I'm Alice"
console.log(alice.getBirthYear());

Quick Reference

Feature Function Declaration Arrow Function
Syntax function name() {} () => {}
Hoisting Yes No
this binding Dynamic Lexical (from parent)
arguments Available Not available
Constructor Can be used Cannot be used
Implicit Return No Yes (without braces)

Key Takeaways

  1. Use function declarations when you need hoisting or to use as constructors

  2. Use arrow functions for callbacks and when lexical this is desired

  3. Always return something from functions that calculate values

  4. Use default parameters to make functions more robust

  5. Keep functions small and focused on a single task

  6. Choose descriptive names that indicate what the function does

Functions are the building blocks of JavaScript applications. Mastering function declaration, parameters, return values, and arrow functions will make your code more organized, reusable, and maintainable.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?