Welcome back! š You've just completed the entire Loops series ā amazing work! Now we're stepping into one of the most important concepts in all of JavaScript ā Functions!
A function is a reusable block of code designed to perform a specific task. Instead of writing the same logic over and over, you write it once inside a function and call it whenever you need it. Functions are the building blocks of every JavaScript program ā from tiny utilities to massive applications.
Let's master them completely!
What is a Function?
A function is a named, reusable block of code that runs only when you call it.
The Problem Functions Solve
Without functions, you repeat yourself constantly:
// ā Without functions ā repetitive and hard to maintain
console.log("Welcome, Mihir! You have 3 new messages.");
console.log("Welcome, Priya! You have 7 new messages.");
console.log("Welcome, Rahul! You have 1 new messages.");With a function:
// ā
With a function ā write once, use anywhere
function greetUser(name, messages) {
console.log(`Welcome, ${name}! You have ${messages} new messages.`);
}
greetUser("Mihir", 3);
greetUser("Priya", 7);
greetUser("Rahul", 1);Same result. Zero repetition. Easy to update ā change the function once and it updates everywhere.
Types of Functions in JavaScript
JavaScript has several ways to define a function. Each has its own syntax and use cases:
- Function Declaration ā the classic, hoisted way
- Function Expression ā assign a function to a variable
- Arrow Function ā modern, concise ES6 syntax
- Anonymous Function ā function without a name
- Default Parameters ā parameters with fallback values
- Rest Parameters ā accept unlimited arguments
1. Function Declaration
The most traditional way to define a function. It is hoisted ā meaning you can call it even before it's defined in the code.
Syntax
function functionName(parameters) {
// code to execute
return value; // optional
}Example
function greet(name) {
console.log(`Hello, ${name}! š`);
}
greet("Mihir"); // Hello, Mihir! š
greet("Priya"); // Hello, Priya! šHoisting ā Call Before Definition
// ā
Works! Function declarations are hoisted
sayHello();
function sayHello() {
console.log("Hello from a hoisted function!");
}
// Output: Hello from a hoisted function!2. Function Expression
A function stored in a variable. It is not hoisted ā you must define it before calling it.
Syntax
const functionName = function(parameters) {
// code to execute
return value;
};Example
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
console.log(multiply(3, 7)); // 21Not Hoisted
// ā Error! Cannot use before defined
console.log(square(5));
const square = function(n) {
return n * n;
};
// ReferenceError: Cannot access 'square' before initialization3. Arrow Function
Introduced in ES6, arrow functions are a shorter, cleaner way to write functions. They're now the most commonly used function style in modern JavaScript.
Syntax
// Full arrow function
const functionName = (parameters) => {
// code
return value;
};
// Concise ā single expression, implicit return
const functionName = (parameters) => expression;Examples
// Traditional function
function add(a, b) {
return a + b;
}
// Same as arrow function
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7// Single parameter ā parentheses optional
const double = n => n * 2;
console.log(double(6)); // 12
// No parameters ā empty parentheses required
const greet = () => console.log("Hello! š");
greet();
// Multiple lines ā need curly braces and return
const getGrade = (marks) => {
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 60) return "C";
return "F";
};
console.log(getGrade(85)); // BArrow vs Regular ā Key Differences
// Regular function ā has its own 'this'
function Timer() {
this.seconds = 0;
setInterval(function() {
this.seconds++; // ā 'this' refers to the callback scope, not Timer
}, 1000);
}
// Arrow function ā inherits 'this' from parent
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++; // ā
'this' correctly refers to Timer
}, 1000);
}4. Parameters and Arguments
Parameters are the variables listed in the function definition. Arguments are the actual values passed when calling the function.
// Parameters ā ā
function introduce(name, role) {
console.log(`Hi, I'm ${name} and I work as a ${role}.`);
}
// Arguments ā ā
introduce("Mihir", "Developer");
introduce("Priya", "Designer");
// Output:
// Hi, I'm Mihir and I work as a Developer.
// Hi, I'm Priya and I work as a Designer.Default Parameters
Give parameters a fallback value ā used when no argument is passed.
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}! š`);
}
greet("Mihir", "Welcome"); // Welcome, Mihir! š
greet("Priya"); // Hello, Priya! š
greet(); // Hello, Guest! šRest Parameters
Use ... to accept any number of arguments as an array.
function sumAll(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sumAll(1, 2, 3)); // 6
console.log(sumAll(10, 20, 30, 40)); // 100
console.log(sumAll(5)); // 5function introduce(firstName, lastName, ...hobbies) {
console.log(`Name: ${firstName} ${lastName}`);
console.log(`Hobbies: ${hobbies.join(", ")}`);
}
introduce("Mihir", "Shah", "Coding", "Reading", "Gaming");
// Output:
// Name: Mihir Shah
// Hobbies: Coding, Reading, Gaming5. The return Statement
return sends a value back to wherever the function was called. Once return executes, the function stops immediately.
function square(n) {
return n * n; // sends back the result
}
let result = square(5);
console.log(result); // 25Return Stops Execution
function checkAge(age) {
if (age < 0) {
return "Invalid age ā"; // Exits immediately
}
if (age < 18) {
return "Minor š¶";
}
return "Adult š§"; // Only reached if age >= 18
}
console.log(checkAge(-1)); // Invalid age ā
console.log(checkAge(15)); // Minor š¶
console.log(checkAge(22)); // Adult š§Functions Without return
A function with no return statement returns undefined.
function sayHi() {
console.log("Hi!");
// no return
}
let val = sayHi(); // prints "Hi!"
console.log(val); // undefinedReturning Multiple Values via Object
function getMinMax(numbers) {
let min = Math.min(...numbers);
let max = Math.max(...numbers);
return { min, max }; // return as an object
}
let { min, max } = getMinMax([3, 1, 9, 5, 7]);
console.log(`Min: ${min}, Max: ${max}`);
// Output: Min: 1, Max: 96. Function Scope
Variables declared inside a function are local ā they only exist within that function and cannot be accessed from outside.
function calculate() {
let result = 42; // local variable
console.log(result); // ā
accessible here
}
calculate();
console.log(result); // ā ReferenceError: result is not definedLocal vs Global Scope
let message = "I am global š"; // global variable
function showMessage() {
let message = "I am local š¦"; // local variable ā shadows global
console.log(message);
}
showMessage(); // I am local š¦
console.log(message); // I am global šFunctions Can Read Global Variables
let taxRate = 0.18;
function calculatePrice(basePrice) {
return basePrice + basePrice * taxRate; // reads global taxRate ā
}
console.log(calculatePrice(1000)); // 11807. Higher-Order Functions
A higher-order function is a function that either takes another function as an argument, or returns a function. This is one of the most powerful patterns in JavaScript.
Function as Argument
function applyOperation(a, b, operation) {
return operation(a, b);
}
const add = (x, y) => x + y;
const subtract = (x, y) => x - y;
const multiply = (x, y) => x * y;
console.log(applyOperation(10, 3, add)); // 13
console.log(applyOperation(10, 3, subtract)); // 7
console.log(applyOperation(10, 3, multiply)); // 30Function Returning a Function
function createMultiplier(factor) {
return (number) => number * factor;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
const times10 = createMultiplier(10);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(times10(5)); // 50Real-World Examples
Example 1: Temperature Converter
const celsiusToFahrenheit = (c) => (c * 9/5) + 32;
const fahrenheitToCelsius = (f) => (f - 32) * 5/9;
console.log(`25°C = ${celsiusToFahrenheit(25)}°F`); // 25°C = 77°F
console.log(`98.6°F = ${fahrenheitToCelsius(98.6).toFixed(1)}°C`); // 37.0°CExample 2: Validate Email
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
console.log(isValidEmail("mihir@example.com")); // true
console.log(isValidEmail("mihirexample.com")); // false
console.log(isValidEmail("mihir@example")); // falseExample 3: Calculate Discount
function calculateDiscount(price, discountPercent) {
if (discountPercent < 0 || discountPercent > 100) {
return "Invalid discount percentage ā";
}
let discountAmount = (price * discountPercent) / 100;
let finalPrice = price - discountAmount;
return {
original: price,
discount: discountAmount,
finalPrice: finalPrice,
};
}
let result = calculateDiscount(5000, 20);
console.log(`Original: ā¹${result.original}`);
console.log(`Discount: ā¹${result.discount}`);
console.log(`You Pay: ā¹${result.finalPrice}`);
// Output:
// Original: ā¹5000
// Discount: ā¹1000
// You Pay: ā¹4000Example 4: Generate a Student Report
function generateReport(students) {
let report = [];
for (let student of students) {
let grade = student.marks >= 90 ? "A"
: student.marks >= 75 ? "B"
: student.marks >= 60 ? "C"
: "F";
let status = student.marks >= 40 ? "Pass ā
" : "Fail ā";
report.push({ ...student, grade, status });
}
return report;
}
let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 78 },
{ name: "Rahul", marks: 35 },
{ name: "Sara", marks: 65 },
];
let report = generateReport(students);
console.log("=== š Report Card ===");
for (let s of report) {
console.log(`${s.name.padEnd(8)} | ${s.marks} marks | Grade: ${s.grade} | ${s.status}`);
}
// Output:
// Mihir | 92 marks | Grade: A | Pass ā
// Priya | 78 marks | Grade: B | Pass ā
// Rahul | 35 marks | Grade: F | Fail ā
// Sara | 65 marks | Grade: C | Pass ā
Example 5: Shopping Cart Functions
function addItem(cart, item) {
return [...cart, item];
}
function removeItem(cart, itemName) {
return cart.filter(item => item.name !== itemName);
}
function getTotal(cart) {
return cart.reduce((total, item) => total + item.price * item.qty, 0);
}
let cart = [];
cart = addItem(cart, { name: "Laptop", price: 55000, qty: 1 });
cart = addItem(cart, { name: "Mouse", price: 800, qty: 2 });
cart = addItem(cart, { name: "Bag", price: 1200, qty: 1 });
console.log("Cart:", cart.map(i => i.name).join(", "));
console.log("Total: ā¹" + getTotal(cart));
cart = removeItem(cart, "Bag");
console.log("After removal:", cart.map(i => i.name).join(", "));
console.log("New Total: ā¹" + getTotal(cart));
// Output:
// Cart: Laptop, Mouse, Bag
// Total: ā¹57800
// After removal: Laptop, Mouse
// New Total: ā¹56600Common Mistakes
Mistake 1: Calling Without Parentheses
function greet() {
console.log("Hello!");
}
// ā Just references the function ā doesn't call it
console.log(greet); // [Function: greet]
// ā
Parentheses are required to execute
greet(); // Hello! ā
Mistake 2: Forgetting return
function add(a, b) {
a + b; // ā Calculates but doesn't return ā lost!
}
console.log(add(2, 3)); // undefined ā
// ā
Always return the result
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5 ā
Mistake 3: Shadowing with Same Variable Name
let total = 100;
function addTax(price) {
let total = price * 1.18; // ā Creates a new local 'total', shadows global
return total;
}
console.log(addTax(500)); // 590
console.log(total); // Still 100 ā global unchanged (but confusing!)
// ā
Use distinct names to avoid confusion
function addTax(price) {
let priceWithTax = price * 1.18;
return priceWithTax;
}Mistake 4: Too Many Parameters
// ā Hard to read and easy to pass arguments in wrong order
function createUser(name, age, email, city, role, isActive) {
// ...
}
createUser("Mihir", 25, "mihir@ex.com", "Mumbai", "admin", true);
// ā
Use an object parameter instead
function createUser({ name, age, email, city, role, isActive }) {
console.log(`${name} | ${role} | ${city}`);
}
createUser({
name: "Mihir",
age: 25,
email: "mihir@ex.com",
city: "Mumbai",
role: "admin",
isActive: true,
});Practical Exercise
Create a file called functions.js:
// šÆ Functions Practice
// 1. Basic utility functions
const isEven = (n) => n % 2 === 0;
const isPositive = (n) => n > 0;
const clamp = (n, min, max) => Math.min(Math.max(n, min), max);
const percentage = (value, total) => ((value / total) * 100).toFixed(2) + "%";
console.log("=== Utilities ===");
console.log(isEven(4)); // true
console.log(isPositive(-3)); // false
console.log(clamp(15, 0, 10)); // 10
console.log(percentage(45, 200)); // 22.50%
// 2. Grade calculator with report
function getGrade(marks) {
if (marks >= 90) return { grade: "A+", label: "Outstanding š" };
if (marks >= 80) return { grade: "A", label: "Excellent š" };
if (marks >= 70) return { grade: "B", label: "Good š" };
if (marks >= 60) return { grade: "C", label: "Average š" };
if (marks >= 40) return { grade: "D", label: "Below Avg ā ļø" };
return { grade: "F", label: "Failed ā" };
}
console.log("\n=== Grade Report ===");
let testMarks = [95, 83, 71, 62, 45, 30];
for (let marks of testMarks) {
let { grade, label } = getGrade(marks);
console.log(`Marks: ${marks} ā Grade: ${grade} (${label})`);
}
// 3. Shopping cart
function createCart() {
let cart = [];
return {
add(item) {
cart.push(item);
console.log(`ā
Added: ${item.name}`);
},
remove(name) {
cart = cart.filter(i => i.name !== name);
console.log(`šļø Removed: ${name}`);
},
total() {
return cart.reduce((sum, i) => sum + i.price * i.qty, 0);
},
summary() {
console.log("\nš Cart Summary:");
for (let item of cart) {
console.log(` ${item.name.padEnd(10)}: ā¹${item.price} Ć ${item.qty} = ā¹${item.price * item.qty}`);
}
console.log(` ${"ā".repeat(35)}`);
console.log(` TOTAL: ā¹${this.total()}`);
},
};
}
console.log("\n=== Shopping Cart ===");
let myCart = createCart();
myCart.add({ name: "Laptop", price: 55000, qty: 1 });
myCart.add({ name: "Mouse", price: 800, qty: 2 });
myCart.add({ name: "Bag", price: 1200, qty: 1 });
myCart.remove("Bag");
myCart.summary();Run it:
node functions.jsExpected Output:
=== Utilities ===
true
false
10
22.50%
=== Grade Report ===
Marks: 95 ā Grade: A+ (Outstanding š)
Marks: 83 ā Grade: A (Excellent š)
Marks: 71 ā Grade: B (Good š)
...
=== Shopping Cart ===
ā
Added: Laptop
ā
Added: Mouse
ā
Added: Bag
šļø Removed: Bag
š Cart Summary:
Laptop : ā¹55000 Ć 1 = ā¹55000
Mouse : ā¹800 Ć 2 = ā¹1600
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
TOTAL: ā¹56600Key Takeaways
Congratulations! š You now have a solid foundation of JavaScript functions.
ā Functions are reusable blocks of code ā write once, use anywhere.
ā 3 main types:
function declarationā hoisted, traditionalfunction expressionā not hoisted, stored in variablearrow functionā concise, modern, no ownthis
ā Parameters vs Arguments:
- Parameters = placeholders in the definition
- Arguments = actual values passed when calling
ā Default parameters provide fallback values when arguments are missing.
ā
Rest parameters (...args) accept unlimited arguments as an array.
ā
return sends a value back and stops function execution immediately.
ā Scope ā variables inside a function are local; they don't leak outside.
ā Higher-order functions ā functions that accept or return other functions ā are the backbone of modern JavaScript.
Best Practices
- ā
Give functions a clear, descriptive name that says what they do ā
calculateTax, notct - ā Each function should do one thing only ā keep it focused
- ā Keep functions short ā if it's over 20 lines, consider splitting it
- ā
Use default parameters instead of checking for
undefinedmanually - ā Use object parameters when a function needs more than 3 arguments
- ā
Always
returna value from functions meant to compute something - ā Prefer arrow functions for short callbacks and expressions
- ā Use function declarations for main, named functions ā they hoist and are easy to find
What's Next?
Excellent work! š Functions are the backbone of everything you'll write in JavaScript from here on.
Next, we're diving into Arrow Functions ā ā the modern, concise way to write functions that you'll be using constantly. You'll learn their syntax, how they differ from regular functions, and when to use them for maximum readability and performance.
You'll learn how to manipulate, search, transform, and format text like a pro. Let's go! šŖ