Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / JavaScript Tutorial / Chapter 2: Control Flow & Functions
JAVASCRIPT ⏱ 12 min read

Functions: Declaration, Expressions, Return Values

Functions are reusable blocks of code that take inputs, perform operations, and return results. They are the primary building blocks of programs.

What is it?

A function is a subprogram designed to perform a specific task. In JavaScript, functions are 'first-class citizens', meaning they can be assigned to variables, passed as arguments, and returned from other functions.

Why is it used?

Functions promote DRY (Don't Repeat Yourself) code, modularity, readability, and testability.

Detailed Explanation

Defining Functions: 1. Function Declaration: `function add(a, b) { return a + b; }` (Hoisted to the top of its scope). 2. Function Expression: `const add = function(a, b) { return a + b; };` (Not hoisted). 3. Default Parameters: Set fallback values for missing arguments (e.g. `function greet(name = "Student")`). 4. Return Value: The `return` keyword passes back a value and immediately terminates function execution.

Syntax Structure

Syntax Blueprint
function functionName(param1, param2 = defaultValue) {
  // Code statements
  return result;
}

Code Example

JAVASCRIPT Code
// Function declaration with default parameters
function calculateNetTuition(basePrice, discountPercent = 0, gstRate = 0.18) {
  const discountAmount = (basePrice * discountPercent) / 100;
  const discountedPrice = basePrice - discountAmount;
  const gstAmount = discountedPrice * gstRate;
  const finalAmount = discountedPrice + gstAmount;

  return Math.round(finalAmount);
}

// Invoking the function
const standardFee = calculateNetTuition(2500);
const festiveDiscountFee = calculateNetTuition(2500, 10); // 10% discount

console.log("Standard Fee with GST:", `₹${standardFee}`);
console.log("Festive Fee with GST: ", `₹${festiveDiscountFee}`);

Explanation of the Code

• Declares reusable tuition calculation logic. • Uses default parameter `discountPercent = 0` and `gstRate = 0.18`. • Returns clean calculated number rounded with `Math.round()`.

Expected Output

Standard Fee with GST: ₹2950 Festive Fee with GST: ₹2655

Real-World Application

Used across business software to compute taxes, format currencies, validate passwords, and calculate metrics.

Common Mistakes to Avoid

• Forgetting the `return` statement (function returns `undefined` by default). • Modifying global variables inside functions instead of accepting inputs via parameters.

Quick Practice Challenge

Write a function `celsiusToFahrenheit(celsius)` that converts temperature using `(celsius * 9/5) + 32`.

Key Takeaways

• Functions encapsulate reusable logic. • Use default parameters to handle optional arguments cleanly. • Every function returns `undefined` unless an explicit `return` is provided.