2.4 Module 2 · Variables, Data Types & Functions

Functions

Learn how to write reusable blocks of code that take inputs, do work, and return outputs — in three different styles: declarations, expressions, and arrow functions.

1

Definition

A function in JavaScript is a reusable block of code designed to perform a specific task. It can be defined once and executed (called) multiple times, optionally taking inputs called parameters and returning an output using the return keyword.

Functions are the foundation of organised, maintainable code — instead of repeating the same logic in multiple places, you write it once inside a function and call it wherever needed.

2

Simple Way

A function is like a machine:

Input You pass values in as arguments
Process The function body runs its logic
Output A value is returned back to the caller

You write the machine once and use it as many times as you need — that's the power of functions.

3

Code Examples

Example 1 — Function Declaration
function greet() {
  console.log("Hello, Aman!");
}

greet(); // Call the function
greet(); // Reuse it — no need to rewrite the logic
Output
Click ▶ Run to execute
Explanation
  • function greet() {} → defines (creates) the function
  • greet() → calls (executes) it — the parentheses are required
  • You can call it as many times as needed without rewriting the code
Example 2 — Function with Parameters
function add(a, b) {
  console.log(a + b);
}

add(5, 3);   // a=5, b=3
add(10, 20); // a=10, b=20 — same function, different inputs
Output
Click ▶ Run to execute
Explanation
  • a and b are parameters — placeholders defined in the function
  • 5 and 3 are arguments — the actual values passed when calling
  • The same function handles different inputs each call
Example 3 — Function Expression
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5));
console.log(multiply(3, 7));
Output
Click ▶ Run to execute
Explanation
  • A function stored inside a const variable — called a function expression
  • return sends the result back to the caller instead of printing it
  • Unlike declarations, expressions are not hoisted — you must define before calling
Example 4 — Arrow Function
// Full arrow function
const subtract = (a, b) => {
  return a - b;
};

console.log(subtract(10, 3));

// Short form — single expression, implicit return
const square = x => x * x;

console.log(square(5));
console.log(square(9));
Output
Click ▶ Run to execute
Explanation
  • Arrow functions use => instead of the function keyword — modern and concise
  • When the body is a single expression, you can drop the curly braces and return — the value is returned implicitly
  • If there is only one parameter, you can also drop the parentheses: x => x * x
4

Real-Life Example

Think of a function like a coffee machine:

Input
Coffee beans + water — the arguments you pass in
Process
Brewing — the logic inside the function body
Output
A cup of coffee — the value the function returns
Reuse
Press the button again — call the function whenever you need it
5

HTML + JavaScript Example

Functions power real UI interactions. Click ▶ Preview, enter two numbers, and watch the function calculate and display the result live.

Live in Browser — Function Calculator
<!DOCTYPE html>
<html>
<head><title>Function Example</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Function Calculator</h2>

  <input id="num1" type="number" placeholder="Number 1"
    style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
           font-size:1rem;width:130px">

  <input id="num2" type="number" placeholder="Number 2"
    style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
           font-size:1rem;width:130px;margin-left:8px">

  <button onclick="calculate()"
    style="margin-left:8px;padding:8px 18px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Add
  </button>

  <div id="output" style="margin-top:16px;font-size:1rem;line-height:2"></div>

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

    function calculate() {
      let a = Number(document.getElementById("num1").value);
      let b = Number(document.getElementById("num2").value);

      if (isNaN(a) || isNaN(b)) {
        document.getElementById("output").innerHTML =
          "<b style='color:red'>Please enter valid numbers.</b>";
        return;
      }

      let result = add(a, b);
      document.getElementById("output").innerHTML =
        "<b>add(" + a + ", " + b + ")</b> → <b style='color:#e07b00'>" + result + "</b>";
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — sayHello function
Starter code
function sayHello() {
  // your code here
}
  • Inside sayHello, print "Welcome to JavaScript" using console.log()
  • Call the function and verify the output
  • Call it a second time — notice how reuse works
Medium Task 2 — Multiply two numbers
Starter code
function multiply(a, b) {
  // return the result
}

console.log(multiply(4, 6));
  • Complete the function so it returns a * b
  • Print the result using console.log()
  • Try rewriting it as an arrow function using const
7

MCQs

Q1
Which keyword is used to create a function in JavaScript?
  • A func
  • B function
  • C def
  • D create
💡 B is correct. JavaScript uses the function keyword for declarations. def is Python, func is Go/Swift — neither exists in JavaScript.
Q2
What is the output?
function test() {
  return 5;
}
console.log(test());
Output
Run it to verify
  • A test
  • B 5
  • C undefined
  • D Error
💡 B is correct. return 5 sends the value 5 back to the caller. console.log(test()) then prints that returned value.
Q3
Which is the correct arrow function syntax?
// Which of these runs without error?
const double = x => x * 2;
console.log(double(6));
Output
Run it to verify
  • A function() {}
  • B () => {}
  • C =>() {}
  • D func => {}
💡 B is correct. Arrow function syntax is (params) => {} or param => expression. The arrow => always comes after the parameters.
8

Pro Tips & Extra Knowledge

  • 01

    Function declarations are hoisted — you can call them before they appear in the file. Function expressions are not:

    Hoisting difference
    // Declaration — hoisted, works before definition
    console.log(add(2, 3));
    function add(a, b) { return a + b; }
    
    // Expression — NOT hoisted
    try {
      console.log(multiply(2, 3)); // Error!
    } catch (e) {
      console.log("Error:", e.message);
    }
    const multiply = (a, b) => a * b;
    Output
    Click ▶ Run to execute
  • 02

    Keep functions small and focused on one task. A function that does too much is hard to test and reuse:

    Single responsibility
    // ✗ Bad — does too many things
    function doEverything(a, b) {
      console.log("Adding...");
      let sum = a + b;
      console.log("Result: " + sum);
      return sum;
    }
    
    // ✓ Good — one focused task
    const add = (a, b) => a + b;
    
    console.log(add(5, 10));
    Output
    Click ▶ Run to execute
  • 03

    Prefer arrow functions for short, single-expression logic — they are more concise and easier to read:

    Arrow function short forms
    // One parameter — no parentheses needed
    const double = x => x * 2;
    
    // Two parameters — parentheses required
    const add = (a, b) => a + b;
    
    // No parameters — empty parentheses required
    const greet = () => "Hello!";
    
    console.log(double(5));
    console.log(add(3, 4));
    console.log(greet());
    Output
    Click ▶ Run to execute
  • 04

    A function without a return statement returns undefined automatically — this is a very common source of bugs:

    Missing return → undefined
    function noReturn(a, b) {
      let sum = a + b; // calculated but not returned!
    }
    
    function withReturn(a, b) {
      return a + b;
    }
    
    console.log(noReturn(2, 3));   // undefined
    console.log(withReturn(2, 3)); // 5
    Output
    Click ▶ Run to execute
Mini Challenge

The function is called and its result stored in a variable — what gets printed? Think carefully before running.

What does this print?
function test() {
  console.log("Hello");
}

let result = test();

console.log(result);
Output
Think first, then run!
Step-by-Step Explanation
// Step 1: test() is called
//         Inside the function: console.log("Hello") runs
//         Output line 1 → "Hello"

// Step 2: test() has no return statement
//         JavaScript automatically returns undefined
//         result = undefined

// Step 3: console.log(result)
//         Output line 2 → undefined

// Final output:
//   Hello
//   undefined

// Key takeaway:
//   console.log() inside a function PRINTS but does not RETURN
//   To capture a value, the function must use return:
//
//   function test() {
//     return "Hello";   // now result = "Hello"
//   }
//   let result = test();
//   console.log(result); // "Hello"