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
Syntax Structure
function functionName(param1, param2 = defaultValue) {
// Code statements
return result;
}
Code Example
// 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
Expected Output
Real-World Application
Used across business software to compute taxes, format currencies, validate passwords, and calculate metrics.
Common Mistakes to Avoid
Quick Practice Challenge
Write a function `celsiusToFahrenheit(celsius)` that converts temperature using `(celsius * 9/5) + 32`.