JavaScript Functions: Declarations, Expressions, Arrow Functions & Parameters

In JavaScript, functions are first-class citizens. This foundational design principle means functions can be stored in variables, passed as arguments into other functions, returned from functions, and assigned properties just like any standard object.

The Three Primary Ways to Define Functions

1. Function Declaration (Hoisted)

Traditional function syntax declared using the function keyword. They are hoisted entirely to memory, allowing invocation before definition:

// Can be called BEFORE declaration line:
console.log(calculateRectangleArea(5, 8)); // Output: 40

function calculateRectangleArea(width, height) {
    return width * height;
}

2. Function Expression (Not Hoisted)

An anonymous or named function assigned to a variable. It follows normal variable hoisting rules and cannot be called before initialization:

const multiply = function(x, y) {
    return x * y;
};
console.log(multiply(4, 5)); // Output: 20

3. Modern ES6 Arrow Functions (=>)

Introduced in ES6, arrow functions deliver ultra-concise syntax and lexical this scoping:

// Multi-line arrow function
const calculateDiscount = (price, percentage) => {
    const discountAmount = price * (percentage / 100);
    return price - discountAmount;
};

// Concise one-line arrow function with IMPLICIT RETURN:
const square = n => n * n;
console.log(square(9)); // 81

Modern Function Parameter Features (ES6+)

A. Default Parameters

Prevents having to write boilerplate param = param || defaultValue checks:

function sendNotification(message, user = "Guest", priority = "Normal") {
    console.log(`[${priority}] Sending to ${user}: ${message}`);
}
sendNotification("System rebooting"); // Uses defaults for user and priority
sendNotification("Account verified", "Amit", "High");

B. Rest Parameters (...rest)

Collects all remaining arguments into a clean, genuine JavaScript Array (replacing the clunky legacy arguments object):

function calculateTotalMarks(studentName, ...scores) {
    // 'scores' is a true JavaScript array
    const total = scores.reduce((sum, score) => sum + score, 0);
    return `${studentName} Total Score: ${total}`;
}

console.log(calculateTotalMarks("Vikram", 85, 92, 78, 90)); // Vikram Total Score: 345

Function Return Values & Early Exit Pattern

The return statement immediately stops function execution and sends a value back to the caller. The Guard Clause / Early Exit pattern reduces nested code and enhances readability:

// CLEAN CODE: Guard Clauses / Early Exit
function processOrder(order) {
    if (!order) return "Invalid Order: Payload empty.";
    if (!order.items || order.items.length === 0) return "Order has no items.";
    if (order.total <= 0) return "Invalid order total amount.";

    // Main execution path remains flat and unnested!
    return `Order #${order.id} processed successfully.`;
}

University Exam Corner (BCA Examination Notes)

Exam Question: "What are Higher-Order Functions (HOF) and Callback Functions? Provide a source code example."

Definition: A Higher-Order Function is a function that accepts another function as an argument, or returns a function as its result. The function passed as an argument is called a Callback Function.
function applyDiscountCalculator(price, discountCalculatorCallback) {
    return discountCalculatorCallback(price);
}

const festivalOffer = p => p * 0.8; // 20% off
console.log(applyDiscountCalculator(1000, festivalOffer)); // 800

Next Step

Congratulations on completing Tier 1: JavaScript Fundamentals! Now let us explore decision making, branching, and conditional logic. Proceed to Tier 2: JavaScript If..Else Conditions & Branching →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

Scope Chain & Closures →

Lexical environment and private variables.

The this Keyword →

Call, apply, bind, and arrow function this.

Functional Programming →

Higher-order functions and currying.

Callbacks & Asynchronous JS →

Callback patterns and event loop execution.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!