In the previous tutorial, you learned how to repeat code using loops. But what if you want to reuse the same code in many different places of your program? This is where JavaScript Functions come in. A function is a block of code with a name. You write it once, and you can run it as many times as you want.

What is a Function?

Think of a function like a tea machine. You press one button (call the function), and the machine does all the steps for you. You do not need to boil water, add tea and add milk again and again. In programming, JavaScript Functions work the same way.

Without a function, you repeat code:

console.log("Welcome to Tutorials Ocean");
console.log("Learn JavaScript step by step");

// ...some other code...

console.log("Welcome to Tutorials Ocean");
console.log("Learn JavaScript step by step");

With a function, you write it one time:

function welcome() {
  console.log("Welcome to Tutorials Ocean");
  console.log("Learn JavaScript step by step");
}

welcome();
welcome();
welcome();

1. Creating and Calling a Function

There are two steps: declare the function (write it), and call the function (run it).

// Syntax
// function functionName() {
//   code to run
// }

// Step 1: Declare
function sayHello() {
  console.log("Hello, student!");
}

// Step 2: Call
sayHello();

Important: a function does nothing until you call it. If you only declare it and never call it, the code inside will not run.

Rules for naming functions

  • Use meaningful names that describe the task: calculateTotal, printReport
  • Use camelCase: first word small, next words start with capital letter
  • Start with a verb: getName, showMessage, checkAge
  • Do not start with a number and do not use spaces

2. Function Parameters and Arguments

Functions become powerful when you send them data. The variables inside the brackets are called parameters. The real values you send when calling are called arguments.

function greet(name) {      // name is a parameter
  console.log("Hello, " + name + "!");
}

greet("Ali");               // "Ali" is an argument
greet("Ayesha");
greet("Bilal");

// Output:
// Hello, Ali!
// Hello, Ayesha!
// Hello, Bilal!

Multiple parameters

function introduce(name, age, city) {
  console.log(name + " is " + age + " years old and lives in " + city);
}

introduce("Ali", 22, "Karachi");
introduce("Sara", 25, "Lahore");

The order matters. The first argument goes to the first parameter, the second to the second, and so on.

Default parameters

You can give a parameter a default value. It is used when no argument is sent.

function welcomeUser(name = "Guest") {
  console.log("Welcome, " + name);
}

welcomeUser("Ahmed");   // Welcome, Ahmed
welcomeUser();          // Welcome, Guest

3. The return Statement

So far our functions only printed something. But most JavaScript Functions calculate a result and give it back. We use return for this.

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

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

console.log(add(3, 4));       // 7
console.log(add(100, 200));   // 300

Important points about return:

  • return sends a value back to the place where the function was called
  • The function stops immediately when it reaches return. Any code after it will not run.
  • If there is no return, the function gives back undefined
function test() {
  return "First";
  console.log("This line never runs");
}

console.log(test()); // First

console.log vs return: what is the difference?

function addPrint(a, b) {
  console.log(a + b);   // only shows the value on screen
}

function addReturn(a, b) {
  return a + b;         // gives the value back, you can use it
}

let x = addPrint(2, 3);   // prints 5, but x is undefined
let y = addReturn(2, 3);  // y is 5

console.log(x); // undefined
console.log(y); // 5
console.log(y * 10); // 50 (we can use the returned value)

4. Function Examples You Will Use Daily

// Calculate area of a rectangle
function rectangleArea(width, height) {
  return width * height;
}
console.log(rectangleArea(5, 10)); // 50

// Check even or odd
function isEven(number) {
  return number % 2 === 0;
}
console.log(isEven(8));  // true
console.log(isEven(7));  // false

// Find the larger number
function getMax(a, b) {
  if (a > b) {
    return a;
  }
  return b;
}
console.log(getMax(15, 40)); // 40

// Calculate discount price
function applyDiscount(price, percent) {
  let discount = price * percent / 100;
  return price - discount;
}
console.log(applyDiscount(2000, 10)); // 1800

// Convert Celsius to Fahrenheit
function toFahrenheit(celsius) {
  return celsius * 9 / 5 + 32;
}
console.log(toFahrenheit(37)); // 98.6

5. Functions With Loops and Conditions

Now we combine everything you learned in this series so far.

// Sum of all numbers in an array
function sumArray(numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}
console.log(sumArray([10, 20, 30, 40])); // 100

// Get grade from marks
function getGrade(marks) {
  if (marks >= 90) {
    return "A+";
  } else if (marks >= 80) {
    return "A";
  } else if (marks >= 70) {
    return "B";
  } else if (marks >= 60) {
    return "C";
  } else if (marks >= 50) {
    return "D";
  }
  return "F";
}
console.log(getGrade(85)); // A
console.log(getGrade(45)); // F

// Print multiplication table
function printTable(number) {
  for (let i = 1; i <= 10; i++) {
    console.log(number + " x " + i + " = " + (number * i));
  }
}
printTable(7);

6. Function Expressions

You can also store a function inside a variable. This is called a function expression.

const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(4, 5)); // 20

Difference from a normal function: hoisting

// Function declaration: can be called BEFORE it is written
sayHi();   // works

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

// Function expression: must be written BEFORE calling
// sayBye();  // Error: Cannot access 'sayBye' before initialization

const sayBye = function () {
  console.log("Bye!");
};

sayBye();  // works

7. Arrow Functions (Modern Way)

Arrow functions are a shorter way to write JavaScript Functions. You will see them everywhere in modern code.

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

// Arrow function
const addArrow = (a, b) => {
  return a + b;
};

// Shorter: one line, return is automatic
const addShort = (a, b) => a + b;

console.log(addShort(5, 3)); // 8
// One parameter: brackets are optional
const square = n => n * n;
console.log(square(6)); // 36

// No parameter: empty brackets are required
const sayHello = () => console.log("Hello!");
sayHello();

// Multiple lines: use curly braces and return
const checkAge = (age) => {
  if (age >= 18) {
    return "Adult";
  }
  return "Minor";
};
console.log(checkAge(20)); // Adult

We will study arrow functions in more detail in our ES6 series. For now, just remember that they are a short way to write the same thing.

8. Variable Scope Inside Functions

A variable created inside a function exists only inside that function. This is called local scope. A variable created outside is available everywhere. This is called global scope.

let siteName = "Tutorials Ocean";   // global

function showInfo() {
  let message = "Learning JavaScript";  // local
  console.log(siteName);                // works
  console.log(message);                 // works
}

showInfo();

console.log(siteName);   // works
console.log(message);    // Error: message is not defined

Tip: keep your variables local whenever possible. It prevents bugs and keeps your code clean.

9. Functions Calling Other Functions

Big problems become easy when you split them into small functions.

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

function calculateTax(amount) {
  return amount * 0.17;
}

function generateBill(price, quantity) {
  let subtotal = calculateTotal(price, quantity);
  let tax = calculateTax(subtotal);
  let finalAmount = subtotal + tax;

  console.log("Subtotal: " + subtotal);
  console.log("Tax (17%): " + tax);
  console.log("Total: " + finalAmount);
}

generateBill(500, 4);

// Output:
// Subtotal: 2000
// Tax (17%): 340
// Total: 2340

10. Functions and Webpage Buttons (Preview)

Functions are also used to run code when a user clicks a button. Try this in an HTML file:

<button onclick="showMessage()">Click Me</button>
<p id="output"></p>

<script>
  function showMessage() {
    document.getElementById("output").innerText = "Button was clicked!";
  }
</script>

Do not worry about the document.getElementById part for now. We will learn it in the DOM tutorials.

Practical Example: Simple Calculator

function calculator(num1, num2, operator) {
  switch (operator) {
    case "+":
      return num1 + num2;
    case "-":
      return num1 - num2;
    case "*":
      return num1 * num2;
    case "/":
      if (num2 === 0) {
        return "Cannot divide by zero";
      }
      return num1 / num2;
    default:
      return "Invalid operator";
  }
}

console.log(calculator(10, 5, "+"));  // 15
console.log(calculator(10, 5, "*"));  // 50
console.log(calculator(10, 0, "/"));  // Cannot divide by zero
console.log(calculator(10, 5, "%"));  // Invalid operator

Common Mistakes to Avoid

// Mistake 1: forgetting the brackets when calling
function hello() {
  console.log("Hello");
}
hello;     // WRONG: nothing happens
hello();   // CORRECT

// Mistake 2: forgetting return
function double(n) {
  n * 2;           // WRONG: result is lost
}
console.log(double(5));   // undefined

function doubleCorrect(n) {
  return n * 2;    // CORRECT
}
console.log(doubleCorrect(5));   // 10

// Mistake 3: wrong number of arguments
function subtract(a, b) {
  return a - b;
}
console.log(subtract(10));   // NaN (b is undefined)

Quick Recap

  • A function is a reusable block of code with a name
  • Declare it with function name() {} and call it with name()
  • Parameters receive data, arguments are the real values you send
  • return gives a result back and stops the function
  • Arrow functions are a short modern syntax: (a, b) => a + b
  • Variables inside a function are local and cannot be used outside
  • Split big tasks into small functions that call each other

Fantastic work! JavaScript Functions are the building block of every real application. From now on, almost every program you write will use them.

Practice Exercises

  1. Create a function sayName that takes a name and prints “My name is …”.
  2. Create a function square that returns the square of a number.
  3. Create a function isPositive that returns true if a number is greater than 0.
  4. Create a function areaOfCircle(radius) that returns 3.14 * radius * radius.
  5. Create a function findSmallest(a, b, c) that returns the smallest of three numbers.
  6. Create a function countVowels(text) that counts the vowels (a, e, i, o, u) in a string using a loop.
  7. Create a function reverseString(text) that returns the text in reverse order.
  8. Rewrite exercise 2 and exercise 3 as arrow functions.

Assignment

Build a Mini Shopping Cart Using Functions:

  1. Create an array of 4 product prices, for example [1200, 850, 2300, 450].
  2. Create a function getTotal(prices) that returns the sum using a loop.
  3. Create a function getDiscount(total) that returns 10% discount if total is above 3000, 5% if above 2000, otherwise 0.
  4. Create a function getDeliveryCharges(total) that returns 0 if total is above 4000, otherwise 200.
  5. Create a function printBill(prices) that calls the three functions above and prints a clean bill:
Total: 4800
Discount: 480
Delivery: 0
Final Amount: 4320

Bonus Challenge

Create a function isPrime(number) that returns true or false. Then create a second function printPrimes(limit) that uses isPrime to print all prime numbers up to the limit. Test with 50.

What’s Next?

In the next tutorial, we will learn JavaScript Arrays. You will learn how to store many values in one variable, and how to use functions and loops to work with them. Your knowledge of JavaScript Functions will be very useful there.

Missed the last tutorial? Go back to JavaScript Loops, or browse the full JavaScript Tutorial Series. For deeper reference, see the MDN guide to functions.

About Author

Arshad Sultan

Arshad Sultan is the Founder of Tutorials Ocean and a Technical Architect & Full-Stack Developer with 15+ years of experience in PHP, Laravel, CRM development, API integrations, and AI-powered automation. He also runs Rapid Code, a software and AI automation agency, and has trained hundreds of students across Karachi's IT institutes since 2010.

Leave a Reply

Your email address will not be published. Required fields are marked *