JavaScript Beginner

JavaScript Functions: Creating Reusable Code

CodingerWeb
CodingerWeb
16 views 55 min read

Understanding Functions

Functions are reusable blocks of code that perform specific tasks. They help organize your code and avoid repetition.

Function Declaration

// Basic function declaration
function greet() {
    console.log("Hello, World!");
}

// Call the function
greet();  // Output: Hello, World!

Functions with Parameters

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

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

// Multiple parameters
function addNumbers(a, b) {
    console.log(`${a} + ${b} = ${a + b}`);
}

addNumbers(5, 3);  // Output: 5 + 3 = 8

Return Values

function multiply(x, y) {
    return x * y;
}

let result = multiply(4, 7);
console.log(result);  // Output: 28

// Function with conditional return
function getGrade(score) {
    if (score >= 90) return "A";
    if (score >= 80) return "B";
    if (score >= 70) return "C";
    if (score >= 60) return "D";
    return "F";
}

console.log(getGrade(85));  // Output: B

Default Parameters

function greetWithDefault(name = "Guest") {
    return `Welcome, ${name}!`;
}

console.log(greetWithDefault());        // Welcome, Guest!
console.log(greetWithDefault("John"));  // Welcome, John!

// Multiple default parameters
function createUser(name, age = 18, city = "Unknown") {
    return {
        name: name,
        age: age,
        city: city
    };
}

console.log(createUser("Alice"));
console.log(createUser("Bob", 25, "Boston"));

Function Expressions

// Function expression
const square = function(num) {
    return num * num;
};

console.log(square(5));  // Output: 25

// Arrow functions (ES6)
const cube = (num) => {
    return num * num * num;
};

// Short arrow function (single expression)
const double = num => num * 2;

console.log(cube(3));   // Output: 27
console.log(double(4)); // Output: 8

Scope and Variables

let globalVar = "I'm global";

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

demonstrateScope();
console.log(globalVar);  // Works
// console.log(localVar);  // Error: localVar is not defined

// Function parameters are local to the function
function testParams(param) {
    param = "changed";
    console.log("Inside function:", param);
}

let myVar = "original";
testParams(myVar);
console.log("Outside function:", myVar);  // Still "original"

Higher-Order Functions

// Function that takes another function as parameter
function processArray(arr, callback) {
    let result = [];
    for (let item of arr) {
        result.push(callback(item));
    }
    return result;
}

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

// Using with different callback functions
const doubled = processArray(numbers, x => x * 2);
const squared = processArray(numbers, x => x * x);

console.log("Original:", numbers);
console.log("Doubled:", doubled);
console.log("Squared:", squared);

Practical Examples

// Calculator 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 : "Cannot divide by zero"
};

console.log(calculator.add(10, 5));      // 15
console.log(calculator.divide(10, 0));   // Cannot divide by zero

// Validation functions
function isValidEmail(email) {
    return email.includes("@") && email.includes(".");
}

function isValidAge(age) {
    return age >= 0 && age <= 150;
}

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

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

console.log(`25°C = ${celsiusToFahrenheit(25)}°F`);
console.log(`77°F = ${fahrenheitToCelsius(77).toFixed(1)}°C`);

Practice Exercise: Personal Library

// Create a personal function library
function formatName(firstName, lastName) {
    return `${firstName} ${lastName}`.trim();
}

function calculateAge(birthYear) {
    return new Date().getFullYear() - birthYear;
}

function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function capitalizeWords(sentence) {
    return sentence.split(" ")
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join(" ");
}

// Test your functions
console.log(formatName("john", "doe"));
console.log(calculateAge(1990));
console.log(generateRandomNumber(1, 100));
console.log(capitalizeWords("hello world from javascript"));