OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 8

Functions: Declarations, Expressions, and Parameters

By Ratan Updated: 16 Oct 2026

Write reusable blocks of code using function declarations, expressions, default parameters, and rest args.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Give one operation a reusable interface

A function receives arguments, performs an operation and can return a result. Keep input assumptions explicit. A function returning a calculated value is easier to test than one that silently modifies unrelated page state.

function percentage(earned, maximum = 100) {
  if (!Number.isFinite(earned) || !Number.isFinite(maximum) || maximum <= 0) {
    throw new RangeError('Use finite numbers and a positive maximum');
  }
  return (earned / maximum) * 100;
}
const formatResult = function (value) {
  return value.toFixed(1) + '%';
};
console.log(formatResult(percentage(42, 50))); // 84.0%

The declaration names percentage. The expression creates a function and stores it in formatResult. A default parameter applies when the supplied argument is undefined or omitted, not when it is null. A missing return normally produces undefined.

Rest parameters

function sum(...values) {
  return values.reduce((total, value) => total + value, 0);
}
console.log(sum(2, 3, 4)); // 9
console.log(sum()); // 0

Rest collects remaining arguments into a real array. This small sum assumes numeric inputs; add validation if untrusted values can reach it. Rest must be the last parameter.

Arguments and mutation

Arguments are passed as values. When that value is an object reference, a function can mutate the same object the caller observes. Reassigning a parameter to a new object does not reassign the caller's variable. Prefer returning a new object when mutation is unnecessary, and document intentional updates.

Declaration timing

A function declaration can generally be called earlier in its scope. A function expression assigned to const cannot be called before that binding is initialized. This affects code organization but is not a reason to depend on confusing ordering.

Practice

  1. Write a function returning the larger of two numbers and test equal values.
  2. Call percentage with maximum zero and confirm its error path.
  3. Explain the difference between passing a function and calling it: handler versus handler().
  4. Write a function that returns a result rather than printing it, then test the return value separately from UI rendering.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat