Functions are the building blocks of JavaScript. They let you write code once and use it many times, organize complex programs, and encapsulate logic. Master functions and you can build anything.
Day 25 / 180
Beginner Phase
🕐14 min read
💻8 code examples
🎯3 practice tasks
📝5 quiz questions
Here is the problem that functions solve:
Why functions are essential
// ❌ Without functions — repeating the same codelet num1 = 5, num2 = 3;
let sum1 = num1 + num2;
console.log(`Sum is ${sum1}`);
let num3 = 10, num4 = 7;
let sum2 = num3 + num4;
console.log(`Sum is ${sum2}`);
let num5 = 20, num6 = 15;
let sum3 = num5 + num6;
console.log(`Sum is ${sum3}`);
// Every time you need to add, you write the same code again!// ✅ With functions — write once, use everywherefunctionaddAndLog(a, b) {
let sum = a + b;
console.log(`Sum is ${sum}`);
}
addAndLog(5, 3); // Sum is 8
addAndLog(10, 7); // Sum is 17
addAndLog(20, 15); // Sum is 35// One function, infinite uses!
Functions are the foundation of reusable code. Instead of writing the same logic multiple times, you write a function once and call it whenever you need it. Functions also help organize your code into logical, manageable pieces. Today, I'll teach you everything about function declarations — how to create them, how to pass data to them, how to get data back from them, and how to use them effectively in your programs.
1. The Problem — Repetitive Code and Poor Organization
As your programs grow, you'll find yourself writing the same code over and over. This violates the DRY principle (Don't Repeat Yourself) and makes your code harder to maintain. If you need to change how something works, you have to find and update every copy of that code. Functions solve this by letting you define a block of code once and reuse it anywhere.
Think of functions like recipes. A recipe for chocolate cake tells you exactly what ingredients to use and what steps to follow. Once you have the recipe, you can make cake any time you want without rewriting the instructions. Similarly, a JavaScript function defines a set of instructions that you can execute whenever you need that specific behavior.
The DRY Principle — Don't Repeat Yourself
// ❌ BAD: Repeating the same logic multiple timeslet product1 = 100;
let tax1 = product1 * 0.1;
let total1 = product1 + tax1;
console.log(`Total: $${total1}`);
let product2 = 50;
let tax2 = product2 * 0.1;
let total2 = product2 + tax2;
console.log(`Total: $${total2}`);
let product3 = 200;
let tax3 = product3 * 0.1;
let total3 = product3 + tax3;
console.log(`Total: $${total3}`);
// If tax rate changes from 10% to 15%, you must change EVERY line!// ✅ GOOD: One function, reusable everywherefunctioncalculateTotal(price, taxRate = 0.1) {
let tax = price * taxRate;
let total = price + tax;
console.log(`Total: $${total}`);
return total;
}
calculateTotal(100); // Total: $110
calculateTotal(50); // Total: $55
calculateTotal(200); // Total: $220// If tax rate changes, update ONE place — the function!
💡 The insight: Functions embody the "write once, run anywhere" philosophy. They help you avoid repetition, make your code more maintainable, and allow you to build complex programs from simple, reusable building blocks. Every time you find yourself copying and pasting code, that's a sign you should create a function.
2. Function Declarations — The Basic Building Block
A function declaration (also called a function definition or function statement) uses the function keyword, followed by a name, parentheses (), and curly braces {} containing the code to execute. Function declarations are hoisted, meaning you can call them before they appear in your code.
The syntax follows this pattern: function functionName(parameters) { // code to execute }. The name should be descriptive, typically starting with a verb (like calculate, get, set, is) to indicate what the function does. Function names use camelCase, just like variables.
Function Declaration Examples
// Basic function declaration syntaxfunctionsayHello() {
console.log("Hello, World!");
}
// Calling (invoking) the function
sayHello(); // Output: Hello, World!// Function with one parameterfunctiongreetUser(name) {
console.log(`Hello, ${name}! Welcome to JavaScript.`);
}
greetUser("Ali"); // Hello, Ali! Welcome to JavaScript.
greetUser("Sara"); // Hello, Sara! Welcome to JavaScript.
greetUser("Waheed"); // Hello, Waheed! Welcome to JavaScript.// Function with multiple parametersfunctionintroduce(name, age, city) {
console.log(`My name is ${name}, I am ${age} years old, and I live in ${city}.`);
}
introduce("Ahmed", 25, "Lahore");
introduce("Fatima", 30, "Karachi");
// Functions can be called multiple times with different valuesfunctiondouble(number) {
console.log(`Double of ${number} is ${number * 2}`);
}
double(4); // Double of 4 is 8
double(10); // Double of 10 is 20
double(25); // Double of 25 is 50// Hoisting example — functions can be called before declaration
sayGoodbye(); // This works because of hoisting!functionsayGoodbye() {
console.log("Goodbye! See you next time.");
}
📝 QUIZ 1 & 2Test Your Understanding
Question 1: What keyword is used to declare a function in JavaScript?
Question 2: What does it mean that function declarations are "hoisted"?
3. Parameters and Arguments — Passing Data to Functions
Parameters are placeholders defined in the function declaration. Arguments are the actual values you pass when calling the function. Think of parameters as variables that exist only inside the function — they receive the values of the arguments you pass.
JavaScript is flexible with parameters. If you pass more arguments than parameters, the extra ones are ignored (but accessible via the arguments object). If you pass fewer, the missing parameters become undefined. You can also set default parameters (ES6+) to provide fallback values.
Parameters and Arguments
// Parameters: a and b are placeholdersfunctionadd(a, b) {
return a + b;
}
// Arguments: 5 and 3 are actual values passedlet result = add(5, 3); // 5 and 3 are arguments// Default parameters (ES6) — provides fallback valuesfunctiongreet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
greet("Ali"); // Hello, Ali!
greet("Sara", "Assalam-o-Alaikum"); // Assalam-o-Alaikum, Sara!
greet(); // Hello, Guest! (both defaults used)// Function with flexible parameters (rest parameter)functionsumAll(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sumAll(1, 2, 3)); // 6
console.log(sumAll(5, 10, 15, 20)); // 50// What happens with wrong number of arguments?functionmultiply(x, y) {
console.log(`x=${x}, y=${y}, product=${x * y}`);
}
multiply(4, 5); // x=4, y=5, product=20
multiply(4); // x=4, y=undefined, product=NaN
multiply(4, 5, 6); // x=4, y=5, product=20 (extra argument ignored)
4. The Return Statement — Getting Values Back
The return statement does two things: it immediately exits the function, and it sends a value back to the code that called the function. If a function doesn't have a return statement, it returns undefined by default.
Think of return as the function's output. You can store this output in a variable, use it in an expression, or pass it to another function. Once JavaScript hits a return statement, it exits the function immediately — no code after the return will execute.
Return Statement Examples
// Basic return — function returns a valuefunctionsquare(num) {
return num * num;
}
let result = square(5);
console.log(result); // 25
console.log(square(10)); // 100 (directly using returned value)// Return stops function execution immediatelyfunctionearlyExit() {
console.log("This will print");
return"Done!";
console.log("This will NEVER print"); // ❌ Unreachable code
}
let message = earlyExit();
console.log(message); // "Done!"// Function without return returns undefinedfunctionsayHi(name) {
console.log(`Hi ${name}`);
}
let output = sayHi("Ali");
console.log(output); // undefined (no return statement)// Return can be used for early exit based on conditionfunctiondivide(a, b) {
if (b === 0) {
return"Error: Cannot divide by zero"; // Early return
}
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // "Error: Cannot divide by zero"// Functions can return any data typefunctiongetUser(id) {
return { id: id, name: "Waheed", active: true }; // Returns an object
}
functiongetNumbers() {
return [1, 2, 3, 4, 5]; // Returns an array
}
functionisEven(num) {
return num % 2 === 0; // Returns a boolean
}
📝 QUIZ 3 & 4Test Your Understanding
Question 3: What does a function return if there is no return statement?
Question 4: What happens when JavaScript encounters a return statement inside a function?
5. Common Mistakes to Avoid
Mistakes & Fixes
// ❌ MISTAKE 1: Forgetting to call the function (missing parentheses)functionsayHello() {
console.log("Hello!");
}
sayHello; // ❌ This doesn't call the function — no parentheses!
sayHello(); // ✅ Correct — parentheses call the function// ❌ MISTAKE 2: Putting code after return (unreachable code)functiongetValue() {
return42;
console.log("This will never run"); // ❌ Unreachable code
}
// ✅ FIX: Put code before return, or remove unreachable codefunctiongetValue() {
console.log("Getting value...");
return42;
}
// ❌ MISTAKE 3: Confusing parameters with argumentsfunctiondouble(num) { // num is a PARAMETERreturn num * 2;
}
double; // ❌ This doesn't work — missing argument
double(5); // ✅ 5 is the ARGUMENT// ❌ MISTAKE 4: Not storing or using the return valuefunctionadd(a, b) {
return a + b;
}
add(3, 4); // This calculates 7 but does nothing with it!// ✅ FIX: Store or use the returned valuelet sum = add(3, 4);
console.log(sum); // 7// ❌ MISTAKE 5: Using = instead of === in conditions inside functionsfunctionisAdult(age) {
if (age = 18) { // ❌ Assignment, not comparison!returntrue;
}
returnfalse;
}
// ✅ FIX: Use === for comparisonfunctionisAdult(age) {
if (age >= 18) {
returntrue;
}
returnfalse;
}
6. Best Practices — Writing Clean Functions
🎯 Use Descriptive Function Names
Function names should clearly indicate what they do. Use verbs: calculateTotal(), getUserData(), isValidEmail(), formatDate(). Avoid vague names like doIt() or stuff().
📏 Keep Functions Small and Focused
A function should do ONE thing and do it well. If your function is more than 20-30 lines, consider breaking it into smaller functions. This makes testing and debugging much easier.
🔄 Use Default Parameters Instead of Manual Checks
Instead of writing if (name === undefined) name = "Guest", use default parameters: function greet(name = "Guest"). It's cleaner and less error-prone.
📦 Return Early for Validation
Use early returns to handle invalid inputs at the start of your function. This reduces nesting and makes your code more readable. Check for errors first, then run the main logic.
📝 Don't Modify Parameters (Avoid Side Effects)
Functions should ideally not modify the values passed to them. This is called "pure functions" — they produce the same output for the same input and don't cause side effects. This makes code more predictable and easier to test.
7. Try It Yourself — Function Playground
Experiment with functions below. Write your own function and see it in action!
✏️ Function Playground
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Try different numbers and operations!
8. Practice Tasks
Task 1 — Easy: Temperature Converter
Write a function celsiusToFahrenheit(celsius) that converts Celsius to Fahrenheit using the formula: F = (C × 9/5) + 32. Test with 0°C (should return 32°F) and 100°C (should return 212°F).
Task 2 — Medium: Password Validator
Write a function isValidPassword(password) that returns true if the password is at least 8 characters long and contains at least one number, otherwise returns false. Test with "hello123" (true) and "hello" (false).
Task 3 — Hard: Array Statistics
Write three functions: getSum(arr) returns sum of all numbers, getAverage(arr) returns average, and getMax(arr) returns the largest number. Test with [5, 10, 15, 20] — sum should be 50, average 12.5, max 20.
📝 FINAL QUIZTest Your Mastery
Question 5: What will be the output of the following code?
function test(x) {
if (x > 5) {
return "Big";
}
return "Small";
}
console.log(test(10));
Next Lesson
Day 26 — Function Expressions — Functions as Values