Functions in JavaScript

A function in JavaScript is a reusable block of code designed to perform a specific task.

Think of a function like a machine:

  • You give it some input
  • It processes the input
  • It gives output

Just like:

  • Calculator → numbers in → result out
  • Washing machine → clothes in → clean clothes out

In programming, functions help us:

  • Avoid repeating code
  • Organize logic
  • Make programs readable
  • Build scalable applications

Why Functions Are Important

Without functions:

console.log(5 + 5);
console.log(10 + 10);
console.log(20 + 20);

This becomes repetitive.

With functions:

function add(a, b) {
    console.log(a + b);
}

add(5, 5);
add(10, 10);
add(20, 20);

One logic. Multiple uses.
This is called code reusability.


Real-Life Analogy

Imagine a tea shop.

You say:

  • “1 tea”
  • “2 tea”
  • “Special tea”

The process is already defined.

Function works exactly like that.

Function = Defined Process
Calling Function = Ordering Tea

Syntax of a Function

function functionName(parameters) {
    // code
}

Example:

function greet() {
    console.log("Assalamu Alaikum");
}

Calling (Invoking) a Function

Defining a function does NOT run it.

You must call it.

function greet() {
    console.log("Assalamu Alaikum");
}

greet();

Output

Assalamu Alaikum

Parts of a Function

function add(a, b) {
    return a + b;
}
Part Meaning
function Keyword
add Function name
a, b Parameters
{} Function body
return Sends value back

Function Without Parameters

function welcome() {
    console.log("Welcome to JavaScript");
}

welcome();

Output

Welcome to JavaScript

Function With Parameters

Parameters are variables that receive values.

function greet(name) {
    console.log("Hello " + name);
}

greet("Anas");
greet("Ali");

Output

Hello Anas
Hello Ali

Parameters vs Arguments

Term Meaning
Parameters Variables inside function
Arguments Actual values passed

Example:

function add(x, y) { // parameters
    console.log(x + y);
}

add(5, 10); // arguments

Returning Values

return sends data back from the function.

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

let result = multiply(5, 4);

console.log(result);

Output

20

Difference Between console.log() and return

Using console.log

function add(a, b) {
    console.log(a + b);
}

add(2, 3);

Prints directly.


Using return

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

let result = add(2, 3);

console.log(result);

Returns value for future use.


Why return Is Powerful

function square(num) {
    return num * num;
}

let answer = square(5) + 10;

console.log(answer);

Output

35

Function Logic Flow

Example:

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

let result = add(3, 7);

console.log(result);

Step-by-step Flow

Step 1

Function created.


Step 2

add(3, 7)

Arguments passed:

  • a = 3
  • b = 7

Step 3

return a + b;

Returns:

10

Step 4

result = 10

Step 5

console.log(result)

Prints:

10

Function Expression

Functions can also be stored in variables.

const greet = function() {
    console.log("Hello");
};

greet();

Difference: Function Declaration vs Expression

Function Declaration Function Expression
Starts with function Stored in variable
Hoisted completely Not fully hoisted

Arrow Functions

Modern JavaScript introduced arrow functions.

Syntax

const functionName = () => {
    // code
};

Example:

const greet = () => {
    console.log("Hello");
};

greet();

Arrow Function With Parameters

const add = (a, b) => {
    return a + b;
};

console.log(add(5, 3));

Output

8

Short Arrow Function

If only one line:

const square = num => num * num;

console.log(square(4));

Output

16

Types of Functions

Type Example
Normal Function function test(){}
Function Expression const x = function(){}
Arrow Function const x = () => {}
Anonymous Function function(){}
Callback Function Passed inside another function
Recursive Function Calls itself

Anonymous Function

Function without name.

const x = function() {
    console.log("Anonymous");
};

Callback Functions

A function passed into another function.

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function sayBye() {
    console.log("Goodbye");
}

greet("Anas", sayBye);

Output

Hello Anas
Goodbye

Callbacks are heavily used in:

  • Events
  • APIs
  • Timers
  • Async programming

Recursive Functions

A function calling itself.

function countdown(n) {
    if (n === 0) {
        console.log("Done");
        return;
    }

    console.log(n);
    countdown(n - 1);
}

countdown(5);

Output

5
4
3
2
1
Done

Default Parameters

function greet(name = "Guest") {
    console.log("Hello " + name);
}

greet();
greet("Anas");

Output

Hello Guest
Hello Anas

Scope in Functions

Variables inside function are local.

function test() {
    let x = 10;
    console.log(x);
}

test();
console.log(x);

Output

10
ReferenceError

Because x exists only inside function.


Global vs Local Scope

let globalVar = "I am global";

function test() {
    let localVar = "I am local";

    console.log(globalVar);
    console.log(localVar);
}

test();

Hoisting in Functions

Function declarations are hoisted.

sayHello();

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

Works fine.

But:

greet();

const greet = function() {
    console.log("Hi");
};

Gives error.


Immediately Invoked Function Expression (IIFE)

Runs instantly.

(function() {
    console.log("I run immediately");
})();

Higher-Order Functions

Functions that:

  • Take another function as argument
  • OR return a function

Example:

function calculator(a, b, operation) {
    return operation(a, b);
}

function add(x, y) {
    return x + y;
}

console.log(calculator(5, 3, add));

Output

8

Practical Examples


Example 1 — Even or Odd

function checkEvenOdd(num) {
    if (num % 2 === 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

console.log(checkEvenOdd(7));

Example 2 — Calculator

function calculator(a, b, operator) {

    if (operator === "+") {
        return a + b;
    }

    else if (operator === "-") {
        return a - b;
    }

    else if (operator === "*") {
        return a * b;
    }

    else if (operator === "/") {
        return a / b;
    }

    else {
        return "Invalid Operator";
    }
}

console.log(calculator(10, 5, "*"));

Example 3 — Student Result

function result(marks) {

    if (marks >= 90) {
        return "A Grade";
    }

    else if (marks >= 70) {
        return "B Grade";
    }

    else if (marks >= 50) {
        return "C Grade";
    }

    else {
        return "Fail";
    }
}

console.log(result(85));

Best Practices

1. Use Meaningful Names

❌ Bad

function x(a, b)

✅ Good

function calculateTotal(price, tax)

2. Keep Functions Small

One function → one responsibility.


3. Avoid Repetition

If code repeats → make function.


4. Prefer return

More flexible than direct printing.


Common Beginner Mistakes


Forgetting to Call Function

function hello() {
    console.log("Hi");
}

Nothing happens.

Need:

hello();

Forgetting return

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

console.log(add(2, 3));

Output

undefined

Because no return.


Confusing Parameters and Arguments

function test(x) // parameter
test(5) // argument

Summary Table

Concept Meaning
Function Reusable block of code
Parameter Variable inside function
Argument Value passed
Return Sends value back
Arrow Function Short modern syntax
Callback Function inside another
Scope Variable accessibility
Recursion Function calling itself

Final Thought

Functions are the beating heart of JavaScript.

Variables store data.
Conditions make decisions.
Loops repeat actions.
But functions bring structure, reuse, architecture, and intelligence.

A programmer who understands functions deeply begins to think not line by line… but system by system.

That is where real development begins.

List of Modules