Lesson 14: JavaScript Functions Part 2

Master advanced JavaScript functions with interactive examples and practical applications.

14.1 Finding Maximum Number

This example demonstrates how to create a function that finds and returns the maximum number out of three numbers entered by the user.

Key points: We use conditional operators and logical operators to compare the values. The function accepts three parameters and returns the largest value.

Example 14.1: Maximum Number Function

// Function to find maximum of three numbers
function max(x, y, z) {
    if ((x > y) && (x > z)) {
        return x;
    } else if ((y > x) && (y > z)) {
        return y;
    } else {
        return z;
    }
}

// Using the function
const num1 = 25;
const num2 = 37;
const num3 = 19;
console.log(`Max of ${num1}, ${num2}, ${num3} is ${max(num1, num2, num3)}`);
// Output: Max of 25, 37, 19 is 37
Result will appear here

14.2 Creating Dice Functions

Dice functions are essential for many games. We'll explore two types: a digital dice that displays numbers and a graphical dice that shows dice images.

14.2.1 Digital Dice Function

This function uses Math.random() to generate random numbers between 1 and 6, simulating a dice roll.

Example 14.2: Digital Dice

// Digital dice function
function rollDigitalDice() {
    return Math.floor(1 + Math.random() * 6);
}

// Roll the dice
const roll = rollDigitalDice();
console.log(`Dice roll: ${roll}`);
?
Roll results will appear here

14.2.2 Graphical Dice Function

This function displays graphical representations of dice using images. Each number corresponds to a dice image.

Example 14.3: Graphical Dice

// Graphical dice function
function rollGraphicalDice() {
    const roll = Math.floor(1 + Math.random() * 6);
    return `<img src="dice-${roll}.png" alt="Dice ${roll}">`;
}

// Roll the dice and display
document.getElementById('graphicalDice').innerHTML = 
    rollGraphicalDice();
Dice

14.3 Advanced Function Techniques

Explore more advanced function techniques including higher-order functions and function composition.

14.3.1 Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return functions.

Example 14.4: Function as Argument

// Higher-order function example
function calculate(operation, a, b) {
    return operation(a, b);
}

// Define operations
function add(x, y) { return x + y; }
function multiply(x, y) { return x * y; }

// Using the higher-order function
const sum = calculate(add, 5, 3); // 8
const product = calculate(multiply, 5, 3); // 15
Result will appear here

14.3.2 Function Composition

Function composition is combining two or more functions to produce a new function.

Example 14.5: Function Composition

// Function composition
const compose = (f, g) => x => f(g(x));

// Example functions
const double = x => x * 2;
const square = x => x * x;
const increment = x => x + 1;

// Compose functions
const doubleThenSquare = compose(square, double);
const incrementThenDouble = compose(double, increment);

// Using composed functions
const result1 = doubleThenSquare(3); // (3*2)^2 = 36
const result2 = incrementThenDouble(3); // (3+1)*2 = 8
Result will appear here

14.4 Real-World Applications

Functions are used in virtually every JavaScript application. Here are more practical examples:

Example 14.6: Password Strength Checker

This function checks password strength based on length, character diversity, and special characters.

function checkPasswordStrength(password) {
    let strength = 0;
    
    // Length check
    if (password.length >= 8) strength += 1;
    if (password.length >= 12) strength += 1;
    
    // Character diversity
    if (/[a-z]/.test(password)) strength += 1;
    if (/[A-Z]/.test(password)) strength += 1;
    if (/[0-9]/.test(password)) strength += 1;
    if (/[^a-zA-Z0-9]/.test(password)) strength += 1;
    
    // Strength categories
    if (strength <= 2) return "Weak";
    if (strength <= 4) return "Medium";
    if (strength <= 6) return "Strong";
    return "Very Strong";
}
Password strength will appear here

Example 14.7: Temperature Converter

Convert between Celsius, Fahrenheit, and Kelvin using functions.

// Temperature conversion functions
function celsiusToFahrenheit(celsius) {
    return (celsius * 9/5) + 32;
}

function fahrenheitToCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5/9;
}

function celsiusToKelvin(celsius) {
    return celsius + 273.15;
}

function kelvinToCelsius(kelvin) {
    return kelvin - 273.15;
}
Conversion result will appear here