agyanadda@gmail.com

JS Functions

Functions 1 min read Updated Dec 1, 2026 Topic 17 of 38

A function is a reusable block of code. Write it once, call it many times.

Declare and call

function greet(name) {
  return 'Hello ' + name;
}

greet('Asha'); // 'Hello Asha'
  • name is a parameter (a placeholder)
  • 'Asha' is an argument (the real value)
  • return sends a value back and stops the function

Default parameters

function greet(name = 'Guest') { ... }

Function expression

const square = function (n) { return n * n; };

Why use functions?

  • Avoid repeating code
  • Give a name to a task, making code easier to read
  • Test and fix one piece at a time

Example

Example — Function with parameters and return HTML
<pre id="out"></pre>

<script>
  function calcTotal(price, qty = 1, gst = 18) {
    const subtotal = price * qty;
    return subtotal + subtotal * gst / 100;
  }

  document.getElementById('out').textContent =
    'Pen x 1: ₹' + calcTotal(10) + '\n' +
    'Book x 3: ₹' + calcTotal(200, 3) + '\n' +
    'Bag x 2 (12% GST): ₹' + calcTotal(500, 2, 12);
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword sends a value back from a function?

Exercise 2 True / False

A function runs automatically as soon as it is declared.

Exercise 3 Fill in the Blank

In function add(a, b), a and b are called ___.

Frequently Asked Questions

It returns undefined.