What is a JavaScript Function?

A function in JavaScript is a block of reusable code that performs a specific task. Functions are fundamental building blocks in JavaScript and are essential for writing clean, maintainable, and efficient code.

// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet('Alice')); // Output: Hello, Alice!

Why Use Functions?

Basic Function Syntax

There are several ways to define functions in JavaScript:

// Function declaration
function add(a, b) {
    return a + b;
}
// Function expression
const subtract = function(a, b) {
    return a - b;
};
// Arrow function (ES6+)
const multiply = (a, b) => a * b;
// Immediately Invoked Function Expression (IIFE)
(function() {
    console.log('This runs immediately!');
})();

Function Parameters and Arguments

Functions can accept parameters (placeholders) and receive arguments (actual values) when called.

function greet(name = 'Guest') {
    console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Bob'); // Output: Hello, Bob!

Rest Parameters

Use the rest parameter syntax (...) to accept an indefinite number of arguments as an array.

function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10, 20, 30, 40)); // Output: 100

Return Values

Functions can return values using the return statement. If no return is specified, the function returns undefined.

function isEven(num) {
    return num % 2 === 0;
}
const result = isEven(4);
console.log(result); // Output: true
console.log(isEven(5)); // Output: false

Function Scope

Variables declared inside a function are not accessible outside of it (local scope). Variables declared outside functions have global scope.

let globalVar = 'I am global';
function testScope() {
    let localVar = 'I am local';
    console.log(globalVar); // Accessible
    console.log(localVar);  // Accessible
}
testScope();
console.log(localVar); // Error: localVar is not defined

Higher-Order Functions

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

// Function that takes a function as an argument
function greet(name, callback) {
    console.log(`Hello, ${name}!`);
    callback();
}
// Function that returns a function
function createMultiplier(factor) {
    return function(number) {
        return number * factor;
    };
}
const double = createMultiplier(2);
console.log(double(5)); // Output: 10

Best Practices for Writing Functions

  1. Use descriptive names: Name functions based on what they do (e.g., calculateTotal instead of func1)
  2. Keep functions small: Each function should do one thing well
  3. Use default parameters: Provide sensible defaults for optional parameters
  4. Document your functions: Use comments or JSDoc to explain parameters and return values
  5. Avoid side effects: Pure functions (same input → same output) are easier to test and debug
/**
 * Calculates the total price with tax
 * @param {number} subtotal - The subtotal amount
 * @param {number} [taxRate=0.08] - Optional tax rate (default: 8%)
 * @returns {number} The total price
 */
function calculateTotal(subtotal, taxRate = 0.08) {
    return subtotal * (1 + taxRate);
}
Try It Yourself