DocsHub
Functions

Function Declaration

Learn what functions are, why they matter, and how to declare and use them in JavaScript.

Function Declaration

So far every piece of code we wrote ran once, top to bottom, and that was it. If you needed the same logic in two places — you had to write it twice.

Functions solve this. A function is a reusable block of code that you define once and can run as many times as you want.

function greet() {
  console.log("Hello, welcome to DocsHub!");
}

greet(); // Hello, welcome to DocsHub!
greet(); // Hello, welcome to DocsHub!
greet(); // Hello, welcome to DocsHub!

One definition. Three calls. The code inside runs every time you call it.


Why Functions Matter

Without functions, code gets repetitive fast.

// Without functions — repeated logic everywhere
console.log("Calculating tax for Ali...");
let price1 = 1200;
let tax1 = price1 * 0.17;
console.log(`Tax: ${tax1}`);

console.log("Calculating tax for Sara...");
let price2 = 850;
let tax2 = price2 * 0.17;
console.log(`Tax: ${tax2}`);

Now imagine needing this in 20 places. And then the tax rate changes from 17% to 18% — you have to update every single copy.

With a function:

function calculateTax(price) {
  let tax = price * 0.17;
  console.log(`Tax: ${tax}`);
}

calculateTax(1200); // Tax: 204
calculateTax(850);  // Tax: 144.5

One change to the function updates everything everywhere. This is the core value of functions — write once, use anywhere, change in one place.


Declaring a Function

A function declaration starts with the function keyword, followed by a name, parentheses, and a block of code.

function functionName() {
  // code to run
}

To run the code inside, you call the function by writing its name followed by ().

function sayHello() {
  console.log("Hello!");
}

sayHello(); // Hello!

Nothing happens until you call it. The function definition just tells JavaScript "this exists and here is what it does". The call tells JavaScript "run it now".


Parameters and Return Values

Parameters — passing data in

Parameters let you pass data into a function so it can work with different values each time.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Ali");  // Hello, Ali!
greet("Sara"); // Hello, Sara!
greet("Zara"); // Hello, Zara!

name is the parameter — a placeholder that gets filled in with a real value when the function is called. The real value you pass in is called an argument.

You can have multiple parameters:

function introduce(name, age, city) {
  console.log(`My name is ${name}, I am ${age} years old and I live in ${city}.`);
}

introduce("Ali", 22, "Lahore");
// My name is Ali, I am 22 years old and I live in Lahore.

Return values — sending data out

A function can also send a value back to wherever it was called using return.

function add(a, b) {
  return a + b;
}

let result = add(10, 5);
console.log(result); // 15

The return keyword does two things — it sends the value back, and it immediately stops the function. Any code after return does not run.

function checkAge(age) {
  if (age >= 18) {
    return "Adult";
  }
  return "Minor"; // only runs if age < 18
}

console.log(checkAge(22)); // Adult
console.log(checkAge(15)); // Minor

How a Function Executes

yes no Call function Jump into function body Execute code line by line return statement? Send value back Reach end of function Return to where it was called

When a function is called, JavaScript jumps into the function body, runs the code, and then comes back to exactly where it was called from — carrying the return value if there is one.


Functions Without return

Not every function needs to return a value. Functions that just do something — print, update, log — don't need return.

function printDivider() {
  console.log("-------------------");
}

console.log("Section 1");
printDivider();
console.log("Section 2");
printDivider();

// Section 1
// -------------------
// Section 2
// -------------------

If a function has no return statement, it returns undefined automatically.

function sayHi() {
  console.log("Hi!");
}

let result = sayHi(); // Hi!
console.log(result);  // undefined

Naming Functions

A good function name tells you exactly what the function does — usually a verb + noun pattern.

// ✅ Clear names — you know what they do
function calculateTotal() {}
function sendEmail() {}
function getUserById() {}
function validatePassword() {}
function formatDate() {}

// ❌ Vague names — tells you nothing
function doStuff() {}
function handle() {}
function run() {}
function func1() {}

If you struggle to name a function, it might be doing too many things. A good function does one thing and does it well.


A Real Example — Shopping Cart

function calculateSubtotal(price, quantity) {
  return price * quantity;
}

function calculateDiscount(subtotal, discountPercent) {
  return subtotal * (discountPercent / 100);
}

function calculateTotal(subtotal, discount) {
  return subtotal - discount;
}

const price = 500;
const quantity = 3;
const discountPercent = 10;

const subtotal = calculateSubtotal(price, quantity);   // 1500
const discount = calculateDiscount(subtotal, discountPercent); // 150
const total = calculateTotal(subtotal, discount);       // 1350

console.log(`Subtotal: Rs. ${subtotal}`);  // Subtotal: Rs. 1500
console.log(`Discount: Rs. ${discount}`);  // Discount: Rs. 150
console.log(`Total:    Rs. ${total}`);     // Total:    Rs. 1350

Each function does exactly one thing. They are reusable, easy to read, and easy to test individually. This is how real code is structured.


Summary

  • A function is a reusable block of code you define once and call many times
  • Declare with function name() {} — call with name()
  • Parameters are the placeholders in the definition — arguments are the real values you pass in
  • return sends a value back and immediately stops the function
  • Functions without return return undefined
  • Name functions clearly — verb + noun — and keep each function focused on one task

On this page