JavaScript Functions: Declaration, Parameters, Return and Expressions
A function is a reusable block of code with a name. Instead of copying the same login steps, price calculation or date formatting into ten places, you write it once as a function and call it wherever you need it. Every Playwright test is itself a function, and every page object is built from functions. In this lesson you will learn how to declare and call functions, pass data in with parameters, send results back with return, and write small, pure helpers that are easy to test.
📖 What You’ll Learn: what a function is, function declarations, calling functions, parameters versus arguments, return values and early return, functions that return undefined, function expressions, hoisting differences, functions as values, naming and documenting functions, pure functions versus side effects, and writing reusable test helpers.
🧩 What Is a Function?
Definition: a function is a named, reusable block of code that performs a task. It can receive input values (parameters) and send back a result (a return value). Defining a function does not run it; calling it does.
📄 function.js
// 1. Define (declare) the function
function greet(name) {
return `Hello, ${name}!`;
}
// 2. Call it as many times as you like
console.log(greet("Asha"));
console.log(greet("Ravi"));
const message = greet("QA team"); // store the returned value
console.log(message.length);
⌨️ Terminal
node function.js
🖥️ Output
Hello, Asha!
Hello, Ravi!
15
functionis the keyword,greetis the name,nameis a parameter.greet("Asha")calls the function with the argument"Asha".returnsends a value back to the caller, where you can print it, store it or pass it on.
Functions give you three benefits: reuse (write once, call many times), readability (a good name explains the code) and testability (a small function can be checked on its own).
📥 Parameters vs Arguments
Parameters are the names listed in the function definition. Arguments are the actual values you pass when you call it. Arguments are matched to parameters by position.
📄 params.js
function orderSummary(item, qty, price) { // item, qty, price are parameters
return `${qty} x ${item} = ${(qty * price).toFixed(2)}`;
}
console.log(orderSummary("Pen", 3, 10)); // "Pen", 3, 10 are arguments
// Missing arguments are undefined; extra arguments are ignored
console.log(orderSummary("Pen", 3));
console.log(orderSummary("Pen", 3, 10, "ignored"));
⌨️ Terminal
node params.js
🖥️ Output
3 x Pen = 30.00
3 x Pen = NaN
3 x Pen = 30.00
⚠️ Watch out: JavaScript does not check how many arguments you pass. A missing argument silently becomes undefined, which turns arithmetic into NaN. The next lessons show default parameters and validation to protect against this.
Functions receive copies of primitive values but references to objects. Changing an object parameter changes the caller’s object too:
📄 by-reference.js
function addTag(test, tag) {
test.tags.push(tag); // changes the caller's object
tag = "changed"; // only changes the local copy
}
const test = { name: "login", tags: ["smoke"] };
const newTag = "regression";
addTag(test, newTag);
console.log(test.tags, newTag);
⌨️ Terminal
node by-reference.js
🖥️ Output
[ 'smoke', 'regression' ] regression
📤 Return Values
return ends the function immediately and sends a value back. A function without return (or with an empty return;) returns undefined.
📄 return.js
function add(a, b) {
return a + b;
console.log("never runs"); // code after return is unreachable
}
function logOnly(a, b) {
console.log("sum is", a + b); // prints, but returns nothing
}
console.log(add(2, 3));
const result = logOnly(2, 3);
console.log("logOnly returned:", result);
⌨️ Terminal
node return.js
🖥️ Output
5
sum is 5
logOnly returned: undefined
A function can return any value: a number, a string, an object, an array, even another function. Use an object to return several values at once:
📄 return-object.js
function analyse(times) {
const total = times.reduce((sum, t) => sum + t, 0);
return {
count: times.length,
average: total / times.length,
slowest: Math.max(...times),
};
}
const stats = analyse([320, 410, 1290, 250]);
console.log(stats);
console.log(`Slowest response: ${stats.slowest} ms`);
⌨️ Terminal
node return-object.js
🖥️ Output
{ count: 4, average: 567.5, slowest: 1290 }
Slowest response: 1290 ms
Early return
A return inside an if stops the function early. This is the guard-clause pattern from the if/else lesson:
📄 early-return.js
function discountFor(total) {
if (total <= 0) return 0;
if (total >= 5000) return total * 0.1;
if (total >= 1000) return total * 0.05;
return 0;
}
for (const t of [-5, 500, 1200, 8000]) {
console.log(t, "->", discountFor(t));
}
⌨️ Terminal
node early-return.js
🖥️ Output
-5 -> 0
500 -> 0
1200 -> 60
8000 -> 800
📝 Function Expressions
Definition: a function expression creates a function as part of an expression, usually by assigning it to a variable. The function itself can be anonymous (have no name).
📄 expression.js
// Function declaration
function square(n) {
return n * n;
}
// Function expression stored in a constant
const cube = function (n) {
return n * n * n;
};
// Arrow function expression (next lesson)
const double = (n) => n * 2;
console.log(square(4), cube(3), double(5));
console.log(typeof cube);
⌨️ Terminal
node expression.js
🖥️ Output
16 27 10
function
The difference: hoisting
Function declarations are hoisted with their body, so you can call them before the line where they are written. Function expressions follow the rules of the variable that holds them, so calling them early fails:
📄 hoisting.js
console.log(declared(2)); // works: declarations are hoisted
function declared(n) {
return n + 1;
}
console.log(expressed(2)); // fails: the const is in the temporal dead zone
const expressed = function (n) {
return n + 1;
};
⌨️ Terminal
node hoisting.js
🖥️ Output
3
/home/you/js-course/hoisting.js:7
console.log(expressed(2)); // fails: the const is in the temporal dead zone
^
ReferenceError: Cannot access 'expressed' before initialization
at Object.<anonymous> (/home/you/js-course/hoisting.js:7:13)
Node.js v26.13.0
| Declaration | Expression | |
|---|---|---|
| Syntax | function name() {} | const name = function () {}; |
| Hoisted with body | Yes | No |
| Can be anonymous | No | Yes |
| Typical use | Top-level helpers | Callbacks, values stored in objects |
🎁 Functions Are Values
In JavaScript, functions are first-class values: you can store them in variables, put them in objects and arrays, pass them to other functions and return them from functions.
📄 values.js
const checks = {
isPositive: function (n) { return n > 0; },
isEven: (n) => n % 2 === 0,
};
console.log(checks.isPositive(5), checks.isEven(5));
const steps = [
() => console.log("open page"),
() => console.log("fill form"),
() => console.log("submit"),
];
for (const step of steps) step();
function runTwice(action) { // a function as an argument
action();
action();
}
runTwice(() => console.log("ping"));
⌨️ Terminal
node values.js
🖥️ Output
true false
open page
fill form
submit
ping
ping
Passing functions to other functions is the foundation of callbacks, array methods like map and filter, and every Playwright test('name', async () => {...}) call. The Higher-Order Functions lesson covers it in depth.
✨ Pure Functions vs Side Effects
Definition: a pure function always returns the same output for the same input and changes nothing outside itself. A function with side effects changes something else: a global variable, an object argument, a file, the page, or the console.
📄 pure.js
let runCount = 0;
// Impure: depends on and changes outside state
function nextRunName() {
runCount++;
return `run-${runCount}`;
}
// Pure: depends only on its inputs
function runName(n) {
return `run-${n}`;
}
console.log(nextRunName(), nextRunName()); // different results each call
console.log(runName(1), runName(1)); // always the same
⌨️ Terminal
node pure.js
🖥️ Output
run-1 run-2
run-1 run-1
💡 Tip: Keep calculations (formatting, parsing, validation) in pure functions, and keep side effects (clicking, writing files, calling APIs) in a few clearly named functions. Pure functions are trivial to unit test.
🏷️ Naming and Documenting Functions
- Start with a verb that says what the function does:
calculateTotal,getUser,isValidEmail,formatDate. - Use
is/has/canfor functions that return a boolean. - Keep functions small and focused on one job. If you need “and” to describe it, split it.
- Prefer at most three parameters; for more, pass one options object (covered in the Parameters lesson).
Document public helpers with JSDoc so editors show hints and catch mistakes:
📄 jsdoc.js
/**
* Formats an amount as Indian rupees.
* @param {number} amount - The amount in rupees
* @returns {string} The formatted price, for example "₹1,299.50"
*/
function formatINR(amount) {
return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount);
}
console.log(formatINR(1299.5));
⌨️ Terminal
node jsdoc.js
🖥️ Output
₹1,299.50
🧪 Tester Scenario: Reusable Test-Data Helpers
Test suites share many small tasks: building users, generating unique emails, checking responses. Putting them into functions keeps every test short and consistent:
📄 helpers.js
function uniqueEmail(prefix = "qa") {
return `${prefix}+${Date.now()}@sqatools.in`;
}
function buildUser(overrides) {
return {
name: "Test User",
email: uniqueEmail(),
role: "tester",
active: true,
...overrides, // override only what a test cares about
};
}
function expectStatus(response, expected) {
if (response.status !== expected) {
throw new Error(`Expected status ${expected} but got ${response.status}`);
}
return true;
}
const admin = buildUser({ role: "admin" });
const disabled = buildUser({ active: false, name: "Old Account" });
console.log(admin.role, admin.active, /^qa\+\d+@sqatools\.in$/.test(admin.email));
console.log(disabled.name, disabled.active);
console.log(expectStatus({ status: 201 }, 201));
try {
expectStatus({ status: 500 }, 201);
} catch (e) {
console.log(e.message);
}
⌨️ Terminal
node helpers.js
🖥️ Output
admin true true
Old Account false
true
Expected status 201 but got 500
prefix = "qa"is a default parameter, used when no argument is passed....overridescopies the properties passed in over the defaults (spread syntax, covered in Module 6).expectStatusthrows an error with a clear message, which is how assertions fail a test.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write celsiusToFahrenheit(c) that returns c * 9 / 5 + 32, and print the results for 0, 37 and 100.
Show answer
📄 practice1.js
function celsiusToFahrenheit(c) {
return (c * 9) / 5 + 32;
}
for (const c of [0, 37, 100]) {
console.log(`${c}°C = ${celsiusToFahrenheit(c)}°F`);
}🖥️ Output
0°C = 32°F
37°C = 98.6°F
100°C = 212°FQ2. Write isEven(n) that returns a boolean, then use it to print the even numbers in [3, 8, 11, 14, 20].
Show answer
📄 practice2.js
function isEven(n) {
return n % 2 === 0;
}
for (const n of [3, 8, 11, 14, 20]) {
if (isEven(n)) console.log(n);
}🖥️ Output
8
14
20Q3. What does this print, and why?
function total(a, b) {
a + b;
}
console.log(total(2, 3));Show answer
📄 practice3.js
function total(a, b) {
a + b;
}
console.log(total(2, 3));🖥️ Output
undefinedThe function calculates a + b but never returns it, so it returns undefined. Write return a + b;.
Q4. Write minMax(numbers) that returns an object with the smallest and largest number of an array.
Show answer
📄 practice4.js
function minMax(numbers) {
return { min: Math.min(...numbers), max: Math.max(...numbers) };
}
console.log(minMax([42, 7, 19, 88, 3]));🖥️ Output
{ min: 3, max: 88 }Q5. Write passRate(passed, total) that returns the pass percentage rounded to one decimal, and returns 0 when total is 0 (no division by zero).
Show answer
📄 practice5.js
function passRate(passed, total) {
if (total === 0) return 0;
return Math.round((passed / total) * 1000) / 10;
}
console.log(passRate(17, 20), passRate(2, 3), passRate(0, 0));🖥️ Output
85 66.7 0Q6. Make this function pure: it should not change the array it receives.
function addItem(cart, item) {
cart.push(item);
return cart;
}Show answer
📄 practice6.js
function addItem(cart, item) {
return [...cart, item]; // new array; the original is untouched
}
const cart = ["pen"];
const updated = addItem(cart, "book");
console.log(cart, updated);🖥️ Output
[ 'pen' ] [ 'pen', 'book' ]🧠 MCQ Quiz: Functions
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does a function return if it has no return statement?Answer:
undefined. Without return, a function returns undefined. - In
function add(a, b) {}andadd(2, 3), what are 2 and 3?Answer: Arguments. Parameters are the names in the definition; arguments are the values passed in a call. - What is the value of a parameter when no argument is passed?Answer:
undefined. Missing arguments become undefined unless a default is given. - Which can be called before the line where it is defined?Answer: A function declaration. Function declarations are hoisted together with their body.
- What happens to code after a
returnstatement in the same block?Answer: It never runs. return ends the function immediately. - Which describes a pure function?Answer: Same input always gives the same output, with no side effects. Pure functions do not read or change outside state.
- What is the result?
function f(obj) { obj.n = 2; } const o = { n: 1 }; f(o); console.log(o.n);Answer: 2. The parameter refers to the same object as o. - How can a function return two values?Answer: Return an object or an array.
return a, buses the comma operator and returns only b. - Which name best follows conventions for a function that checks a login state?Answer:
isLoggedIn. Boolean-returning functions usually start with is/has/can, in camelCase. - What does
typeof function () {}return?Answer:"function". Functions are objects, but typeof reports them as “function”.
💼 Interview Questions and Answers
Q1. What is the difference between a function declaration and a function expression?
A declaration (function name() {}) is a statement that creates a named binding hoisted with its body, so it can be called anywhere in its scope. An expression (const name = function () {} or an arrow function) creates the function as a value when that line runs; it follows the hoisting rules of the variable (TDZ for let/const) and can be anonymous. Expressions are used for callbacks and conditional definitions.
Q2. Are arguments passed by value or by reference in JavaScript?
Always by value, but for objects the value is a reference. Reassigning the parameter inside the function does not affect the caller, while mutating the object it points to does. That is why helpers that modify shared test data can cause flaky tests, and why pure functions return new objects instead.
Q3. What are first-class functions?
A language has first-class functions when functions are values like any other: they can be assigned to variables, stored in data structures, passed as arguments and returned from other functions. JavaScript supports all of this, which enables callbacks, higher-order functions such as map, closures and the test(name, fn) style of test frameworks.
Q4. Why are small pure functions valuable in test automation?
They are deterministic, so their results can be checked with simple unit tests and they never cause flakiness. They can be reused across UI and API tests (formatting prices, parsing tables, building payloads) and composed into larger helpers. Keeping side effects in a few places (page objects, API clients) makes failures easier to locate.
Q5. What does this code print?
📄 interview.js
function f() {
return
{ ok: true };
}
console.log(f());
console.log(typeof f, f.length, f.name);
⌨️ Terminal
node interview.js
🖥️ Output
undefined
function 0 f
Automatic semicolon insertion ends the return at the line break, so f() returns undefined. f.length is the number of declared parameters (0) and f.name is the function’s name.
❓ Frequently Asked Questions
🤔 What are the types of functions in JavaScript?
Function declarations, function expressions, arrow functions, methods (functions stored in objects), constructor functions and classes, async functions and generator functions. This module covers the first three in detail.
🤔 Can a JavaScript function return multiple values?
Not directly, but it can return an array or object containing several values, which the caller can unpack with destructuring: const { min, max } = minMax(list);.
🤔 What is the difference between a function and a method?
A method is a function stored as a property of an object and usually called on that object, for example "text".toUpperCase() or page.click().
🤔 How many parameters should a function have?
Ideally three or fewer. For more, pass a single options object such as createUser({ name, role, active }), which also makes calls self-documenting.
🏁 Summary
- A function is reusable code: declare it once, call it many times; it runs only when called.
- Parameters are names in the definition; arguments are the values passed; missing arguments are
undefined. returnsends a value back and ends the function; without it the result isundefined.- Function declarations are hoisted with their body; function expressions are not.
- Functions are values; keep calculations pure and side effects in clearly named helpers.
Next, continue with Lesson 18: Arrow Functions. For extra practice, solve the JavaScript function practice programs.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in