JavaScript Regular Expressions (Regex): Patterns, Flags, Groups and Examples

A regular expression (regex) is a small pattern language for finding and checking text. One line of regex can validate an email, pull every order number out of a log, or check that a URL matches /orders/123. Playwright uses regexes everywhere: toHaveURL(/dashboard/), getByText(/welcome/i), toHaveTitle(/SQA Tools/). In this lesson you will learn to read and write regexes step by step, use them with JavaScript string methods, and avoid the classic traps.

📖 What You’ll Learn: creating regexes with literals and RegExp, test, character classes, quantifiers and greedy versus lazy matching, anchors and word boundaries, flags (g, i, m, s, u, y, d), capturing and named groups, alternation, match, matchAll and exec, replace with groups and functions, split with regex, lookahead and lookbehind, escaping special characters, the lastIndex trap, and regexes in Playwright tests.


🔎 What Is a Regular Expression?

Definition: a regular expression is a pattern that describes a set of strings. JavaScript regexes are objects of type RegExp. You can create one in two ways:

📄 create.js

// 1. Literal: between slashes, with optional flags after the last slash
const orderPattern = /ORD-\d+/;

// 2. Constructor: from a string, useful when the pattern is built at runtime
const word = "checkout";
const dynamic = new RegExp(`${word}-\\d+`, "i");

console.log(orderPattern.test("Your order ORD-451 is ready"));
console.log(orderPattern.test("No order yet"));
console.log(dynamic.test("CHECKOUT-7 failed"), dynamic.source, dynamic.flags);

⌨️ Terminal

node create.js

🖥️ Output

true
false
true checkout-\d+ i
  • regex.test(text) returns true if the pattern is found anywhere in the text.
  • \d means “any digit” and + means “one or more”, so /ORD-\d+/ matches ORD- followed by digits.
  • In the RegExp string form, backslashes must be doubled ("\\d"), because the string itself processes escapes first.

🔤 Character Classes

A character class matches one character from a set:

PatternMatches
.Any character except a line break
\d / \DA digit 0–9 / anything that is not a digit
\w / \WA word character (letter, digit, _) / anything else
\s / \SWhitespace (space, tab, line break) / anything else
[abc]One of a, b or c
[a-z], [A-Z0-9]A range of characters
[^0-9]Any character NOT in the set

📄 classes.js

console.log(/\d\d\d/.test("Room 404"));       // three digits in a row
console.log(/[aeiou]/.test("rhythm"));         // any vowel?
console.log(/^[A-Z]/.test("Playwright"));      // starts with a capital?
console.log("Tel: +91 98765-43210".replace(/\D/g, ""));   // keep only digits
console.log("a1 b2_c3!".match(/\w/g).join(""));

⌨️ Terminal

node classes.js

🖥️ Output

true
false
true
919876543210
a1b2_c3

🔢 Quantifiers: How Many Times

QuantifierMeaningExample
*0 or more/ab*/ matches a, ab, abbb
+1 or more/\d+/ matches 7, 2026
?0 or 1 (optional)/colou?r/ matches color and colour
{n}Exactly n/\d{6}/ a 6-digit PIN code
{n,}n or more/\w{8,}/ 8+ word characters
{n,m}Between n and m/\d{2,4}/ 2 to 4 digits

📄 quantifiers.js

console.log(/^\d{6}$/.test("411001"), /^\d{6}$/.test("41100"));
console.log(/colou?r/.test("color"), /colou?r/.test("colour"));
console.log("Error!!!!".match(/!+/)[0]);

⌨️ Terminal

node quantifiers.js

🖥️ Output

true false
true true
!!!!

Greedy vs lazy

Quantifiers are greedy: they match as much as possible. Adding ? after them makes them lazy: as little as possible.

📄 greedy.js

const html = '<b>Pass</b> and <b>Fail</b>';
console.log(html.match(/<b>.*<\/b>/)[0]);    // greedy: from the first <b> to the last </b>
console.log(html.match(/<b>.*?<\/b>/)[0]);   // lazy: stops at the first </b>

⌨️ Terminal

node greedy.js

🖥️ Output

<b>Pass</b> and <b>Fail</b>
<b>Pass</b>

⚓ Anchors and Word Boundaries

Anchors match a position, not a character:

  • ^: start of the string (or line, with the m flag).
  • $: end of the string (or line, with m).
  • \b: a word boundary, between a word character and a non-word character.

📄 anchors.js

console.log(/\d{4}/.test("abc12345xyz"));      // found somewhere inside
console.log(/^\d{4}$/.test("abc12345xyz"));    // whole string must be 4 digits
console.log(/^\d{4}$/.test("2026"));

console.log(/cat/.test("concatenate"));       // substring match
console.log(/\bcat\b/.test("concatenate"));   // whole word only
console.log(/\bcat\b/.test("the cat sat"));

⌨️ Terminal

node anchors.js

🖥️ Output

true
false
true
true
false
true

⚠️ Watch out: For validation, always anchor the pattern with ^...$. Without anchors, /\d{6}/ also accepts “abc1234567xyz”, because six digits appear somewhere inside it.


🚩 Flags

FlagNameEffect
gglobalFind all matches, not just the first
iignore caseUpper and lower case are equal
mmultiline^ and $ match at each line
sdotAll. also matches line breaks
uunicodeCorrect handling of emoji and Unicode escapes
ystickyMatch only at lastIndex
dindicesReport start/end positions of groups

📄 flags.js

const log = "ERROR db down\nINFO retry\nerror cache miss";

console.log(log.match(/error/g));          // case-sensitive: 1 match
console.log(log.match(/error/gi));         // case-insensitive: 2 matches
console.log(log.match(/^\w+/gm));         // first word of every line
console.log(/down.INFO/.test(log), /down.INFO/s.test(log));   // . and line breaks

⌨️ Terminal

node flags.js

🖥️ Output

[ 'error' ]
[ 'ERROR', 'error' ]
[ 'ERROR', 'INFO', 'error' ]
false true

🎯 Groups, Named Groups and Alternation

Parentheses ( ) create a capturing group. Groups let you extract parts of a match and apply quantifiers to several characters. (?<name>...) creates a named group, and | means “or” (alternation).

📄 groups.js

const line = "Order ORD-2026-451 placed on 2026-11-23 by asha@sqatools.in";

const m = line.match(/ORD-(\d{4})-(\d+)/);
console.log(m[0], "| year:", m[1], "| number:", m[2]);

const date = line.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(date.groups);
const { day, month, year } = date.groups;
console.log(`${day}/${month}/${year}`);

console.log(/^(GET|POST|PUT|DELETE)$/.test("POST"), /^(GET|POST)$/.test("PATCH"));
console.log("hahaha".match(/(ha)+/)[0]);       // quantifier on a group
console.log("2026-11-23".match(/(?:\d+)-(\d+)/)[1]);   // (?:...) groups without capturing

⌨️ Terminal

node groups.js

🖥️ Output

ORD-2026-451 | year: 2026 | number: 451
[Object: null prototype] { year: '2026', month: '11', day: '23' }
23/11/2026
true false
hahaha
11

🧰 Regex Methods: match, matchAll, exec, search

MethodReturns
regex.test(str)true/false
str.match(regex) without gFirst match with groups, or null
str.match(regex) with gArray of all matched strings (no groups), or null
str.matchAll(regex) (needs g)Iterator of every match, each with groups
regex.exec(str)Next match with groups, or null
str.search(regex)Index of the first match, or -1

📄 methods.js

const log = "user=asha status=200 ms=320; user=ravi status=500 ms=1290";

console.log(log.match(/status=\d+/));          // first match + details
console.log(log.match(/status=\d+/g));         // all matches, strings only
console.log("no numbers here".match(/\d+/));   // null when nothing matches

for (const m of log.matchAll(/user=(?<user>\w+) status=(?<status>\d+)/g)) {
  console.log(m.groups.user, m.groups.status);
}
console.log(log.search(/ravi/));

⌨️ Terminal

node methods.js

🖥️ Output

[
  'status=200',
  index: 10,
  input: 'user=asha status=200 ms=320; user=ravi status=500 ms=1290',
  groups: undefined
]
[ 'status=200', 'status=500' ]
null
asha 200
ravi 500
34

⚠️ Watch out: match returns null, not an empty array, when nothing matches. text.match(/\d+/)[0] then throws “Cannot read properties of null”. Use text.match(/\d+/)?.[0] or check for null first.


🔁 replace and split with Regex

In replace, the replacement string can refer to groups with $1, $2 or $<name>. You can also pass a function that computes each replacement.

📄 replace.js

console.log("2026-11-23".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
console.log("2026-11-23".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<d>.$<m>.$<y>"));

// Mask every email address in a log line
const log = "Sent to asha@sqatools.in and ravi.k@example.com";
console.log(log.replace(/([\w.]+)@([\w.]+)/g, (match, user, domain) => `${user[0]}***@${domain}`));

// Collapse whitespace and split on several separators
console.log("  Welcome   back \n Asha ".replace(/\s+/g, " ").trim());
console.log("pen, book;lamp | mug".split(/\s*[,;|]\s*/));

⌨️ Terminal

node replace.js

🖥️ Output

23/11/2026
23.11.2026
Sent to a***@sqatools.in and r***@example.com
Welcome back Asha
[ 'pen', 'book', 'lamp', 'mug' ]

👀 Lookahead and Lookbehind

Lookarounds check what comes before or after a position without including it in the match:

SyntaxMeaning
X(?=Y)X followed by Y (positive lookahead)
X(?!Y)X not followed by Y (negative lookahead)
(?<=Y)XX preceded by Y (positive lookbehind)
(?<!Y)XX not preceded by Y (negative lookbehind)

📄 lookaround.js

const prices = "Pen ₹10, Book ₹250, Lamp $40";
console.log(prices.match(/(?<=₹)\d+/g));       // numbers after ₹ only

// Password rule: 8+ characters with at least one digit and one uppercase letter
const strong = /^(?=.*\d)(?=.*[A-Z]).{8,}$/;
for (const pw of ["password", "Password", "Passw0rd", "P0rt"]) {
  console.log(pw.padEnd(9), strong.test(pw));
}

⌨️ Terminal

node lookaround.js

🖥️ Output

[ '10', '250' ]
password  false
Password  false
Passw0rd  true
P0rt      false

⚠️ Special Characters and Common Traps

Escaping special characters

These characters have special meanings and must be escaped with \ to match them literally: . * + ? ^ $ { } ( ) | [ ] \ /.

📄 escape.js

console.log(/sqatools.in/.test("sqatoolsXin"));     // . matches any character!
console.log(/sqatools\.in/.test("sqatoolsXin"));    // escaped: literal dot

// Escape user input before putting it into a RegExp
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const userInput = "price (USD)?";
console.log(new RegExp(escapeRegex(userInput)).test("What is the price (USD)?"));

⌨️ Terminal

node escape.js

🖥️ Output

true
false
true

The g flag and lastIndex trap

A regex with the g or y flag remembers where its last match ended (lastIndex). Reusing the same regex with test() then gives alternating results:

📄 lastindex.js

const hasDigit = /\d/g;
console.log(hasDigit.test("a1"), hasDigit.test("b2"), hasDigit.test("c3"));

const hasDigitFixed = /\d/;   // no g flag for a yes/no check
console.log(hasDigitFixed.test("a1"), hasDigitFixed.test("b2"), hasDigitFixed.test("c3"));

⌨️ Terminal

node lastindex.js

🖥️ Output

true false true
true true true

💡 Tip: Use the g flag only with match, matchAll, replace and replaceAll. For test() checks, leave it off.

Catastrophic backtracking

Nested quantifiers such as /(a+)+$/ can take exponential time on some inputs and freeze a program. Keep patterns simple, avoid nested +/*, and limit input length when validating user data.


🧪 Tester Scenario: Validate and Extract Data

A small validation table checks common formats, and the second part extracts structured data from a log for a report:

📄 validate-extract.js

const rules = {
  email: /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,
  indianMobile: /^(\+91[- ]?)?[6-9]\d{9}$/,
  pinCode: /^[1-9]\d{5}$/,
  isoDate: /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,
};

const samples = {
  email: ["qa@sqatools.in", "qa@sqatools", "a b@c.com"],
  indianMobile: ["9876543210", "+91 9876543210", "1234567890"],
  pinCode: ["411001", "011001", "41100"],
  isoDate: ["2026-11-23", "2026-13-01", "2026-02-31"],
};

for (const [rule, values] of Object.entries(samples)) {
  console.log(rule.padEnd(13), values.map((v) => `${v}:${rules[rule].test(v) ? "✓" : "✗"}`).join("  "));
}

const log = `2026-11-23T10:01:02Z GET /api/orders/451 200 320ms
2026-11-23T10:01:05Z POST /api/cart 500 1290ms
2026-11-23T10:01:09Z GET /api/orders/452 200 210ms`;

const requests = [...log.matchAll(/(?<method>GET|POST) (?<path>\S+) (?<status>\d{3}) (?<ms>\d+)ms/g)]
  .map((m) => ({ ...m.groups, status: Number(m.groups.status), ms: Number(m.groups.ms) }));
console.table(requests);
console.log("server errors:", requests.filter((r) => r.status >= 500).map((r) => r.path));

⌨️ Terminal

node validate-extract.js

🖥️ Output

email         qa@sqatools.in:✓  qa@sqatools:✗  a b@c.com:✗
indianMobile  9876543210:✓  +91 9876543210:✓  1234567890:✗
pinCode       411001:✓  011001:✗  41100:✗
isoDate       2026-11-23:✓  2026-13-01:✗  2026-02-31:✓
┌─────────┬────────┬───────────────────┬────────┬──────┐
│ (index) │ method │ path              │ status │ ms   │
├─────────┼────────┼───────────────────┼────────┼──────┤
│ 0       │ 'GET'  │ '/api/orders/451' │ 200    │ 320  │
│ 1       │ 'POST' │ '/api/cart'       │ 500    │ 1290 │
│ 2       │ 'GET'  │ '/api/orders/452' │ 200    │ 210  │
└─────────┴────────┴───────────────────┴────────┴──────┘
server errors: [ '/api/cart' ]

📌 Note: Regex format checks are not full validation: “2026-02-31” passes the date pattern although the date does not exist. Combine a regex with a real check (for example parsing the date) when correctness matters.

In Playwright, the same patterns go straight into assertions, for example:

📄 checkout.spec.js (Playwright, for reference)

await expect(page).toHaveURL(/\/orders\/\d+$/);
await expect(page.getByTestId("order-id")).toHaveText(/^ORD-\d{4}-\d+$/);
await page.getByRole("button", { name: /place order/i }).click();

📝 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 a regex that checks whether a string is exactly a 4-digit OTP, and test it with "1234", "12a4" and "12345".

Show answer

📄 practice1.js

const otp = /^\d{4}$/;
for (const v of ["1234", "12a4", "12345"]) console.log(v, otp.test(v));

🖥️ Output

1234 true
12a4 false
12345 false

Q2. Extract all numbers from "Order 12 has 3 items costing 450 rupees" as an array of numbers.

Show answer

📄 practice2.js

const text = "Order 12 has 3 items costing 450 rupees";
const numbers = (text.match(/\d+/g) ?? []).map(Number);
console.log(numbers);

🖥️ Output

[ 12, 3, 450 ]

Q3. Check whether a sentence contains the whole word "test" (any case) but not as part of another word. Try "Run the TEST now" and "latest build".

Show answer

📄 practice3.js

const wordTest = /\btest\b/i;
console.log(wordTest.test("Run the TEST now"), wordTest.test("latest build"));

🖥️ Output

true false

Q4. Convert dates from DD/MM/YYYY to YYYY-MM-DD in "Start 05/11/2026, end 23/11/2026".

Show answer

📄 practice4.js

const text = "Start 05/11/2026, end 23/11/2026";
console.log(text.replace(/(\d{2})\/(\d{2})\/(\d{4})/g, "$3-$2-$1"));

🖥️ Output

Start 2026-11-05, end 2026-11-23

Q5. Use named groups to extract the key and value from each key=value pair in "env=qa; browser=firefox; workers=4" into an object.

Show answer

📄 practice5.js

const text = "env=qa; browser=firefox; workers=4";
const config = {};
for (const m of text.matchAll(/(?<key>\w+)=(?<value>\w+)/g)) {
  config[m.groups.key] = m.groups.value;
}
console.log(config);

🖥️ Output

{ env: 'qa', browser: 'firefox', workers: '4' }

Q6. This check gives true, false, true for three valid inputs. Explain and fix it.

const isNumber = /^\d+$/g;
console.log(isNumber.test("10"), isNumber.test("20"), isNumber.test("30"));
Show answer

With the g flag, test starts searching at lastIndex, which is left at the end of the previous match. Remove the g flag:

📄 practice6.js

const isNumber = /^\d+$/;
console.log(isNumber.test("10"), isNumber.test("20"), isNumber.test("30"));

🖥️ Output

true true true

🧠 MCQ Quiz: Regular Expressions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does \d match?
  2. What does /^abc$/ require?
  3. Which flag makes a regex case-insensitive?
  4. What does "a1b22c333".match(/\d+/g) return?
  5. What does "abc".match(/\d/) return?
  6. How do you match a literal dot?
  7. What is the difference between .* and .*??
  8. In "2026-11-23".replace(/(\d+)-(\d+)-(\d+)/, "$3"), what is the result?
  9. Why can /x/g.test() give different results on repeated calls?
  10. What does (?<year>\d{4}) create?

💼 Interview Questions and Answers

Q1. What is the difference between test(), match() and matchAll()?

regex.test(str) returns a boolean. str.match(regex) without g returns the first match with groups and index; with g it returns an array of matched strings without groups; it returns null if nothing matches. str.matchAll(regex) requires g and returns an iterator of every match with its groups, which is the best choice for extracting structured data.

Q2. How would you validate an email address with a regex, and what are the limits?

A practical pattern is /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/: something without spaces or @, an @, a domain with a dot and a TLD. Fully RFC-compliant email regexes are huge and still cannot prove the mailbox exists. In tests, use a simple pattern for format checks and verify real delivery separately (for example via a test inbox API).

Q3. Explain greedy and lazy quantifiers with an example.

📄 greedy-lazy.js

const s = '"a" and "b"';
console.log(s.match(/".*"/)[0]);
console.log(s.match(/".*?"/)[0]);
console.log(s.match(/"[^"]*"/g));

⌨️ Terminal

node greedy-lazy.js

🖥️ Output

"a" and "b"
"a"
[ '"a"', '"b"' ]

The greedy .* runs to the last quote, swallowing both values. The lazy .*? stops at the first closing quote. A negated class [^"]* is often the clearest and fastest alternative.

Q4. Why might a regex built with new RegExp(userInput) be dangerous?

User input can contain special characters that change the pattern (for example . or (), causing wrong matches or syntax errors, and crafted input can create patterns with catastrophic backtracking that freeze the process (ReDoS). Escape input before building a RegExp, limit input length, and prefer plain string methods such as includes when you do not need a pattern.

Q5. How are regular expressions used in Playwright tests?

Many Playwright APIs accept a RegExp wherever they accept a string: expect(page).toHaveURL(/\/dashboard$/), toHaveTitle(/SQA Tools/), toHaveText(/Order #\d+ confirmed/), getByText(/welcome/i), getByRole("button", { name: /submit/i }) and page.route(/\/api\/orders/). Regexes make assertions tolerant of dynamic parts such as IDs and dates while still checking the structure.


❓ Frequently Asked Questions

🤔 What does /g mean in JavaScript regex?

The global flag: find all matches instead of stopping at the first. It changes what match returns and makes replace replace every match.

🤔 How do I test a regex quickly?

Use the browser console or Node.js REPL with /pattern/.test("text"), or an online tester such as regex101 with the ECMAScript (JavaScript) flavour selected.

🤔 Should I use regex or string methods?

Use string methods (includes, startsWith, split) for fixed text; they are clearer. Use regex for patterns: “digits”, “optional parts”, “any of these words”, and extraction with groups.

🤔 What is the difference between a regex literal and new RegExp()?

A literal (/abc/i) is written directly in code and is checked when the file loads. new RegExp("abc", "i") builds the pattern from a string at runtime, which is needed for dynamic patterns but requires doubled backslashes.


🏁 Summary

  • A regex is a text pattern: create it with /pattern/flags or new RegExp() and check it with test().
  • Character classes (\d \w \s [a-z]), quantifiers (* + ? {n,m}) and anchors (^ $ \b) build most patterns.
  • Flags change behaviour: g all matches, i ignore case, m multiline, s dot matches newlines.
  • Groups and named groups extract parts with match/matchAll, and replace can reuse them.
  • Anchor validation patterns, escape special characters, and do not use g with test().

Next, continue with Lesson 28: Arrays Basics. This completes Module 5 and the Beginner level. Module 6 starts the Intermediate level with arrays.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Template Literals: Interpolation, Multi-Line Strings and Tagged Templates

Joining text with + quickly becomes hard to read: "Order " + id + " for " + name + " costs ₹" + total. Template literals, written with back-ticks, let you put values straight into a string with ${...}, write strings over several lines, and even process strings with a custom function (tagged templates). In this lesson you will use them to build messages, URLs, test data and reports, and learn the pitfalls such as printing [object Object] or unsafe values.

📖 What You’ll Learn: template literal syntax, interpolation with ${}, expressions and function calls inside placeholders, multi-line strings and indentation, nested templates, formatting values (numbers, dates, objects), building URLs and file names safely, String.raw, tagged templates, and practical uses in test automation.


🔤 Template Literal Syntax

Definition: a template literal is a string written between back-ticks `...`. It can contain placeholders ${expression} whose values are converted to strings and inserted. This is called string interpolation.

📄 syntax.js

const name = "Asha";
const passed = 18;
const total = 20;

const oldWay = "Hi " + name + ", " + passed + " of " + total + " tests passed.";
const newWay = `Hi ${name}, ${passed} of ${total} tests passed.`;

console.log(oldWay);
console.log(newWay);
console.log(oldWay === newWay);

⌨️ Terminal

node syntax.js

🖥️ Output

Hi Asha, 18 of 20 tests passed.
Hi Asha, 18 of 20 tests passed.
true

💡 Tip: The back-tick key is usually at the top left of the keyboard, below Esc. Template literals were added in ES2015 and work everywhere today.


🧮 Expressions Inside ${}

A placeholder accepts any expression: arithmetic, function calls, ternaries, property access, method calls. It does not accept statements such as if or for.

📄 expressions.js

const price = 249.5;
const qty = 3;
const user = { name: "Ravi", isPremium: true };

console.log(`Subtotal: ₹${price * qty}`);
console.log(`Total with tax: ₹${(price * qty * 1.18).toFixed(2)}`);
console.log(`Customer: ${user.name.toUpperCase()}`);
console.log(`Shipping: ${user.isPremium ? "free" : "₹49"}`);
console.log(`Items: ${["pen", "book"].join(", ")}`);
console.log(`Pass rate: ${Math.round((18 / 20) * 100)}%`);

⌨️ Terminal

node expressions.js

🖥️ Output

Subtotal: ₹748.5
Total with tax: ₹883.23
Customer: RAVI
Shipping: free
Items: pen, book
Pass rate: 90%

Keep placeholders short. If an expression gets long, calculate it in a variable first and put only the variable in the template.


📄 Multi-Line Strings

Line breaks inside back-ticks are kept exactly, so you no longer need \n for multi-line text:

📄 multiline.js

const report = `Test Run Summary
----------------
Passed:  18
Failed:   2
Skipped:  1`;

console.log(report);
console.log(report.split("\n").length, "lines");

⌨️ Terminal

node multiline.js

🖥️ Output

Test Run Summary
----------------
Passed:  18
Failed:   2
Skipped:  1
5 lines

⚠️ Watch out: The indentation inside the back-ticks is part of the string. If you indent a template literal to match the surrounding code, those spaces appear in the output. Start the lines at the left margin, or remove the indentation afterwards.

📄 indent.js

function emailBody(name) {
  return `
    Hello ${name},
    Your test run has finished.
  `;
}
console.log(JSON.stringify(emailBody("Asha")));

const dedent = (text) => text.trim().split("\n").map((line) => line.trim()).join("\n");
console.log(dedent(emailBody("Asha")));

⌨️ Terminal

node indent.js

🖥️ Output

"\n    Hello Asha,\n    Your test run has finished.\n  "
Hello Asha,
Your test run has finished.

🎨 Formatting Values in Templates

Every placeholder value is converted with String(). That is fine for strings and numbers, but objects and some values need formatting first:

📄 formatting.js

const order = { id: 451, items: 2 };
const missing = undefined;
const tags = ["smoke", "p1"];

console.log(`Order: ${order}`);                       // [object Object]
console.log(`Order: ${JSON.stringify(order)}`);       // readable
console.log(`Coupon: ${missing}`);                    // "undefined" in the text
console.log(`Coupon: ${missing ?? "none"}`);          // default
console.log(`Tags: ${tags}`);                         // arrays join with commas
console.log(`Price: ${(1299.5).toLocaleString("en-IN", { style: "currency", currency: "INR" })}`);
console.log(`Date: ${new Date(Date.UTC(2026, 10, 23)).toISOString().slice(0, 10)}`);

⌨️ Terminal

node formatting.js

🖥️ Output

Order: [object Object]
Order: {"id":451,"items":2}
Coupon: undefined
Coupon: none
Tags: smoke,p1
Price: ₹1,299.50
Date: 2026-11-23

⚠️ Watch out: Seeing [object Object] or undefined in a log, file name or error message means a placeholder received an object or a missing value. Use JSON.stringify for objects and ?? for possibly missing values.


🪆 Nesting Templates and Building Lists

A placeholder can contain another template literal. Combined with map and join, this builds lists and tables from arrays:

📄 nested.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "search", status: "failed", ms: 1430 },
  { test: "cart", status: "passed", ms: 610 },
];

const lines = results
  .map((r) => `${r.status === "passed" ? "✅" : "❌"} ${r.test.padEnd(8)} ${String(r.ms).padStart(5)} ms`)
  .join("\n");

console.log(`Results (${results.length} tests)
${lines}
Failures: ${results.filter((r) => r.status === "failed").map((r) => r.test).join(", ") || "none"}`);

⌨️ Terminal

node nested.js

🖥️ Output

Results (3 tests)
✅ login      820 ms
❌ search    1430 ms
✅ cart       610 ms
Failures: search

The same technique builds simple HTML snippets, Markdown summaries for CI comments, or Slack messages.


🔗 Building URLs, Paths and File Names

Template literals are perfect for URLs, but user-supplied values must be encoded so spaces and special characters do not break the URL:

📄 urls.js

const baseURL = "https://qa.example.com";
const term = "usb cable & charger";
const page = 2;

console.log(`${baseURL}/search?q=${term}&page=${page}`);                     // broken URL
console.log(`${baseURL}/search?q=${encodeURIComponent(term)}&page=${page}`); // safe

const params = new URLSearchParams({ q: term, page: String(page) });
console.log(`${baseURL}/search?${params}`);

const testName = "Checkout: pay with UPI";
const stamp = "2026-11-23T10-30-00";
const fileName = `${testName.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${stamp}.png`;
console.log(fileName);

⌨️ Terminal

node urls.js

🖥️ Output

https://qa.example.com/search?q=usb cable & charger&page=2
https://qa.example.com/search?q=usb%20cable%20%26%20charger&page=2
https://qa.example.com/search?q=usb+cable+%26+charger&page=2
checkout-pay-with-upi-2026-11-23T10-30-00.png

⚠️ Watch out: Never build SQL queries, shell commands or HTML from user input with template literals. Values containing quotes or tags can change the meaning (SQL injection, XSS). Use parameterised queries, argument arrays and proper escaping.


📐 String.raw: Keep Backslashes

In a normal template literal, \n becomes a line break and \\ becomes one backslash. String.raw keeps the backslashes exactly as written, which is handy for Windows paths and regular expression source text:

📄 raw.js

console.log(`C:\\tests\\new`);                // escapes are processed
console.log(String.raw`C:\tests\new`);           // kept as written
console.log(String.raw`\d+\.\d{2}`);            // regex source, readable
console.log(new RegExp(String.raw`^\d+\.\d{2}$`).test("19.99"));

⌨️ Terminal

node raw.js

🖥️ Output

C:\tests\new
C:\tests\new
\d+\.\d{2}
true

🏷️ Tagged Templates

Definition: a tagged template is a template literal preceded by a function name: tag`text ${value}`. Instead of producing a string directly, JavaScript calls the function with the literal text parts as an array and the placeholder values as further arguments. The function decides what to return.

📄 tag-basics.js

function inspect(strings, ...values) {
  console.log("strings:", strings);
  console.log("values:", values);
  return "done";
}

const user = "Asha";
const count = 3;
console.log(inspect`User ${user} has ${count} open bugs`);

⌨️ Terminal

node tag-basics.js

🖥️ Output

strings: [ 'User ', ' has ', ' open bugs' ]
values: [ 'Asha', 3 ]
done

There is always one more string part than values. A tag can rebuild the string with changes, for example highlighting every value:

📄 tags.js

function highlight(strings, ...values) {
  return strings.reduce((out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""), "");
}

const test = "login";
const ms = 1430;
console.log(highlight`Test ${test} took ${ms} ms`);

function currency(strings, ...values) {
  const fmt = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
  return strings.reduce((out, str, i) => out + str + (i < values.length ? fmt.format(values[i]) : ""), "");
}
console.log(currency`Subtotal ${1299.5}, tax ${233.91}`);

⌨️ Terminal

node tags.js

🖥️ Output

Test [login] took [1430] ms
Subtotal ₹1,299.50, tax ₹233.91

Libraries use tags for safe SQL (sql`SELECT * FROM users WHERE id = ${id}` sends id as a parameter), for GraphQL queries and for CSS-in-JS. You will mostly use tags rather than write them, but now you know how they work.


🧪 Tester Scenario: Generate Test Data and a Bug Report

📄 test-data.js

const runId = "nightly-1123";
const users = Array.from({ length: 3 }, (_, i) => ({
  name: `Test User ${i + 1}`,
  email: `qa+${runId}-${i + 1}@sqatools.in`,
  password: `Pass@${1000 + i}`,
}));
console.table(users);

const failure = {
  test: "checkout › pay with card",
  expected: "Order confirmed",
  actual: "Payment declined",
  url: "https://qa.example.com/checkout/pay",
  browser: "chromium",
};

const bugReport = `### Bug: ${failure.test}
**Environment:** QA, ${failure.browser}
**URL:** ${failure.url}

**Expected:** ${failure.expected}
**Actual:** ${failure.actual}

_Found by run ${runId}_`;

console.log(bugReport);

⌨️ Terminal

node test-data.js

🖥️ Output

┌─────────┬───────────────┬─────────────────────────────────┬─────────────┐
│ (index) │ name          │ email                           │ password    │
├─────────┼───────────────┼─────────────────────────────────┼─────────────┤
│ 0       │ 'Test User 1' │ 'qa+nightly-1123-1@sqatools.in' │ 'Pass@1000' │
│ 1       │ 'Test User 2' │ 'qa+nightly-1123-2@sqatools.in' │ 'Pass@1001' │
│ 2       │ 'Test User 3' │ 'qa+nightly-1123-3@sqatools.in' │ 'Pass@1002' │
└─────────┴───────────────┴─────────────────────────────────┴─────────────┘
### Bug: checkout › pay with card
**Environment:** QA, chromium
**URL:** https://qa.example.com/checkout/pay

**Expected:** Order confirmed
**Actual:** Payment declined

_Found by run nightly-1123_
  • Array.from({ length: 3 }, (_, i) => ...) creates three users, and template literals give each unique, predictable values.
  • The bug report is Markdown built with one multi-line template literal, ready to paste into Jira or a GitHub issue.

📝 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. Rewrite with a template literal: "Hello " + first + " " + last + ", you have " + n + " messages", using first = “Asha”, last = “Rao”, n = 5.

Show answer

📄 practice1.js

const first = "Asha", last = "Rao", n = 5;
console.log(`Hello ${first} ${last}, you have ${n} messages`);

🖥️ Output

Hello Asha Rao, you have 5 messages

Q2. Print 1 item or N items using a ternary inside a template literal, for counts 1 and 7.

Show answer

📄 practice2.js

for (const count of [1, 7]) {
  console.log(`${count} item${count === 1 ? "" : "s"}`);
}

🖥️ Output

1 item
7 items

Q3. Build an API URL for user ID 42 with the query parameters include=orders and sort=date desc, making sure the space is encoded.

Show answer

📄 practice3.js

const id = 42;
const params = new URLSearchParams({ include: "orders", sort: "date desc" });
console.log(`https://api.example.com/users/${id}?${params}`);

🖥️ Output

https://api.example.com/users/42?include=orders&sort=date+desc

URLSearchParams encodes the space as +, which is valid in query strings.

Q4. Print a three-line address using one template literal: name, street, city with PIN code.

Show answer

📄 practice4.js

const addr = { name: "Asha Rao", street: "12 MG Road", city: "Pune", pin: "411001" };
console.log(`${addr.name}
${addr.street}
${addr.city} - ${addr.pin}`);

🖥️ Output

Asha Rao
12 MG Road
Pune - 411001

Q5. Fix the output so it shows the object’s contents instead of [object Object].

const payload = { email: "qa@sqatools.in", role: "tester" };
console.log(`Sending ${payload}`);
Show answer

📄 practice5.js

const payload = { email: "qa@sqatools.in", role: "tester" };
console.log(`Sending ${JSON.stringify(payload)}`);

🖥️ Output

Sending {"email":"qa@sqatools.in","role":"tester"}

Q6. Write a tag function upper that upper-cases every interpolated value but leaves the literal text unchanged.

Show answer

📄 practice6.js

function upper(strings, ...values) {
  return strings.reduce((out, s, i) => out + s + (i < values.length ? String(values[i]).toUpperCase() : ""), "");
}
const env = "qa", browser = "firefox";
console.log(upper`Running on ${env} with ${browser}`);

🖥️ Output

Running on QA with FIREFOX

🧠 MCQ Quiz: Template Literals

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which characters delimit a template literal?
  2. What does `2 + 3 = ${2 + 3}` produce?
  3. What does "Total: ${10}" (double quotes) produce?
  4. What appears for `${{ a: 1 }}`?
  5. Can you put an if statement inside ${}?
  6. What does String.raw`a\nb` return?
  7. In a tagged template with two placeholders, how many string parts does the tag receive?
  8. Why use encodeURIComponent inside a URL template?
  9. What is printed?
    const x = undefined;
    console.log(`Value: ${x ?? "n/a"}`);
  10. Why can indentation be a problem in multi-line template literals?

💼 Interview Questions and Answers

Q1. What are template literals and what advantages do they have over string concatenation?

Template literals are back-tick strings (ES2015) that support ${expression} interpolation, real multi-line strings and tagged templates. Compared with + concatenation they are easier to read, avoid missing-space bugs, avoid accidental numeric addition versus string joining, and make multi-line text (reports, emails, Markdown) simple.

Q2. What is a tagged template, and where is it used in practice?

A tagged template calls a function with the literal string parts and the interpolated values separately: tag`a ${x} b` calls tag(["a ", " b"], x). The tag can escape, transform or reinterpret the values. Real uses: parameterised SQL (preventing injection), GraphQL query definitions, CSS-in-JS, internationalisation and String.raw.

Q3. Predict the output.

📄 predict.js

const a = 5, b = "5";
console.log(`${a + b}`, `${a}${b}`, `${a + Number(b)}`);
console.log(`${[1, 2, 3]}`, `${null}`, `${() => 1}`);

⌨️ Terminal

node predict.js

🖥️ Output

55 55 10
1,2,3 null () => 1

a + b joins a number and a string, giving “55”. Placeholders call String(), so the array becomes “1,2,3”, null becomes “null”, and a function becomes its source text.

Q4. Is it safe to build SQL or HTML with template literals?

Not with untrusted values. A plain template inserts values as-is, so `... WHERE name = '${input}'` allows SQL injection and `<div>${input}</div>` allows XSS. Use parameterised queries (or an SQL tag that sends parameters separately), and escape HTML or set textContent instead of innerHTML.


❓ Frequently Asked Questions

🤔 What is the difference between template literals and normal strings?

Template literals use back-ticks and support ${} interpolation, multi-line text and tags. Normal strings in single or double quotes do not.

🤔 How do I write a back-tick inside a template literal?

Escape it with a backslash: `Use \` for templates`. Use \${ to write a literal dollar-brace.

🤔 Are template literals slower than concatenation?

No meaningful difference. Choose them for readability.

🤔 Can template literals be used as object keys or in JSON?

They are just strings once evaluated, so obj[`key_${id}`] works. JSON itself must use double-quoted strings, but you can build JSON text with JSON.stringify.


🏁 Summary

  • Template literals use back-ticks and insert values with ${expression}.
  • Placeholders accept any expression (maths, calls, ternaries), but not statements.
  • Line breaks are kept, so multi-line text is easy; indentation is kept too.
  • Format objects with JSON.stringify, defaults with ??, and URL values with encodeURIComponent/URLSearchParams.
  • String.raw keeps backslashes; tagged templates pass text parts and values to a function.

Next, continue with Lesson 27: Regular Expressions.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Closures Explained: Private State, Factories and Common Pitfalls

A closure is a function that remembers the variables from the place where it was created, even after that place has finished running. It sounds abstract, but you already rely on closures every time a callback uses a variable from outside, and they power counters, caches, retry helpers and every test fixture that “remembers” its setup. In this lesson you will see exactly how closures work, use them to build private state and function factories, and learn the classic closure bugs interviewers love to ask about.

📖 What You’ll Learn: the definition of a closure, how closures keep variables alive, private state with closures, function factories, practical helpers (once, memoize, retry counters), closures in callbacks and timers, the var-in-a-loop closure bug, closures and memory, and how closures appear in test code.


🔒 What Is a Closure?

Definition: a closure is a function together with the variables from its surrounding (lexical) scope that it uses. Because of lexical scope (see the Scope lesson), an inner function can read the outer function’s variables, and it keeps that access even after the outer function has returned.

📄 closure.js

function makeGreeter(greeting) {
  // greeting lives in makeGreeter's scope
  return function (name) {
    return `${greeting}, ${name}!`;   // the inner function uses greeting
  };
}

const hello = makeGreeter("Hello");
const welcome = makeGreeter("Welcome back");

// makeGreeter has already returned, but greeting is still remembered
console.log(hello("Asha"));
console.log(welcome("Ravi"));

⌨️ Terminal

node closure.js

🖥️ Output

Hello, Asha!
Welcome back, Ravi!
  • Each call to makeGreeter creates a new scope with its own greeting.
  • The returned function “closes over” that scope, so hello remembers "Hello" and welcome remembers "Welcome back".
  • Normally local variables disappear when a function returns; a closure keeps them alive as long as the inner function exists.

🔢 Closures Keep State Between Calls

Because the remembered variables are live (not copies), a closure can change them, and the change is kept for the next call:

📄 counter.js

function createCounter() {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}

const nextId = createCounter();
console.log(nextId(), nextId(), nextId());

const other = createCounter();       // a separate count
console.log(other(), nextId());

⌨️ Terminal

node counter.js

🖥️ Output

1 2 3
1 4

Nothing outside createCounter can reach count directly. The only way to change it is to call the returned function. This is how closures give you private state.


🛡️ Private State: A Module with Methods

Return an object whose methods share the same closed-over variables. The variables act like private fields:

📄 private-state.js

function createTestRun(name) {
  const results = [];                         // private

  return {
    record(test, passed) {
      results.push({ test, passed });
    },
    summary() {
      const passed = results.filter((r) => r.passed).length;
      return `${name}: ${passed}/${results.length} passed`;
    },
    failures() {
      return results.filter((r) => !r.passed).map((r) => r.test);
    },
  };
}

const run = createTestRun("Nightly");
run.record("login", true);
run.record("search", false);
run.record("checkout", true);

console.log(run.summary());
console.log(run.failures());
console.log(run.results);   // not accessible from outside

⌨️ Terminal

node private-state.js

🖥️ Output

Nightly: 2/3 passed
[ 'search' ]
undefined

Classes can do the same with #private fields (Module 8); closures were the original way and are still common in functional code.


🏭 Function Factories

Definition: a function factory is a function that creates and returns customised functions. Each returned function is a closure over the factory’s arguments.

📄 factory.js

function makeValidator(min, max) {
  return (value) => value >= min && value <= max;
}

const isValidAge = makeValidator(18, 65);
const isValidRating = makeValidator(1, 5);

console.log(isValidAge(30), isValidAge(70));
console.log(isValidRating(5), isValidRating(0));

const makeUrl = (base) => (path) => `${base}${path}`;
const qaUrl = makeUrl("https://qa.example.com");
console.log(qaUrl("/login"), qaUrl("/cart"));

⌨️ Terminal

node factory.js

🖥️ Output

true false
true false
https://qa.example.com/login https://qa.example.com/cart

makeUrl uses two arrow functions in a row: calling it with a base returns a function that is waiting for a path. Configuring once and reusing many times is a very common pattern in test helpers.


🧰 Practical Helpers Built with Closures

once: run a function only the first time

📄 once.js

function once(fn) {
  let called = false;
  let result;
  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const setupDatabase = once(() => {
  console.log("seeding test database...");
  return "db-ready";
});

console.log(setupDatabase());
console.log(setupDatabase());   // no second seeding

⌨️ Terminal

node once.js

🖥️ Output

seeding test database...
db-ready
db-ready

memoize: cache results of slow calls

📄 memoize.js

function memoize(fn) {
  const cache = new Map();
  return (key) => {
    if (cache.has(key)) return `${cache.get(key)} (cached)`;
    const value = fn(key);
    cache.set(key, value);
    return value;
  };
}

const getToken = memoize((user) => {
  console.log(`logging in as ${user}...`);
  return `token-for-${user}`;
});

console.log(getToken("admin"));
console.log(getToken("admin"));
console.log(getToken("tester"));

⌨️ Terminal

node memoize.js

🖥️ Output

logging in as admin...
token-for-admin
token-for-admin (cached)
logging in as tester...
token-for-tester

Logging in once per user and reusing the token is a real speed-up for API test suites; Playwright’s storageState applies the same idea to browser logins.


⏲️ Closures in Callbacks and Timers

Every callback that uses an outer variable is a closure. The callback runs later, but still sees the variable:

📄 timers.js

function scheduleReminder(task, delayMs) {
  const createdAt = "09:00";
  setTimeout(() => {
    console.log(`Reminder (set at ${createdAt}): ${task}`);
  }, delayMs);
}

scheduleReminder("rerun flaky tests", 20);
scheduleReminder("check CI report", 10);
console.log("reminders scheduled");

⌨️ Terminal

node timers.js

🖥️ Output

reminders scheduled
Reminder (set at 09:00): check CI report
Reminder (set at 09:00): rerun flaky tests

The callbacks run after scheduleReminder has returned, yet each still remembers its own task and createdAt.


⚠️ The Classic Closure-in-a-Loop Bug

Closures capture variables, not values. With var, a loop has a single shared variable, so every closure created in the loop sees its final value:

📄 loop-bug.js

const handlers = [];
for (var i = 1; i <= 3; i++) {
  handlers.push(() => `button ${i} clicked`);
}
console.log(handlers.map((h) => h()));

⌨️ Terminal

node loop-bug.js

🖥️ Output

[ 'button 4 clicked', 'button 4 clicked', 'button 4 clicked' ]

Fix 1 (modern): use let, which creates a new binding for each iteration.

📄 loop-let.js

const handlers = [];
for (let i = 1; i <= 3; i++) {
  handlers.push(() => `button ${i} clicked`);
}
console.log(handlers.map((h) => h()));

⌨️ Terminal

node loop-let.js

🖥️ Output

[ 'button 1 clicked', 'button 2 clicked', 'button 3 clicked' ]

Fix 2 (older code): pass the value into a function so each closure gets its own parameter, an approach you may see as an IIFE (immediately invoked function expression).

📄 loop-iife.js

const handlers = [];
for (var i = 1; i <= 3; i++) {
  handlers.push(((n) => () => `button ${n} clicked`)(i));
}
console.log(handlers.map((h) => h()));

⌨️ Terminal

node loop-iife.js

🖥️ Output

[ 'button 1 clicked', 'button 2 clicked', 'button 3 clicked' ]

🧠 Closures and Memory

A closure keeps its outer variables alive for as long as the closure itself can be reached. That is the point, but it means a long-lived closure (an event listener, a cache, a timer) that references a large object keeps that object in memory too.

  • Remove event listeners and clear intervals (clearInterval) when they are no longer needed.
  • Do not let caches grow forever; limit their size or clear them between test runs.
  • Avoid closing over huge objects when you only need one value from them; copy the value into a small variable first.

Memory and performance are covered in more depth in Module 13.


🧪 Tester Scenario: A Retry Helper with Attempt Tracking

This helper wraps an action. The closure remembers the configuration and an attempt history, which is printed when the action finally fails:

📄 retry.js

function withRetry(action, { attempts = 3, label = "action" } = {}) {
  const history = [];                               // remembered between calls
  return () => {
    for (let i = 1; i <= attempts; i++) {
      try {
        const result = action(i);
        history.push(`attempt ${i}: ok`);
        return result;
      } catch (e) {
        history.push(`attempt ${i}: ${e.message}`);
      }
    }
    throw new Error(`${label} failed after ${attempts} attempts\n  ${history.join("\n  ")}`);
  };
}

const flakyLogin = withRetry((n) => {
  if (n < 3) throw new Error("timeout");
  return "logged in";
}, { label: "login" });
console.log(flakyLogin());

const brokenApi = withRetry(() => { throw new Error("500 Server Error"); }, { attempts: 2, label: "GET /orders" });
try {
  brokenApi();
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node retry.js

🖥️ Output

logged in
GET /orders failed after 2 attempts
  attempt 1: 500 Server Error
  attempt 2: 500 Server Error

⚠️ Watch out: Retries hide real problems if used everywhere. Use them for known external flakiness (network, third-party services), log every attempt as this helper does, and fix the root cause of flaky UI tests instead of retrying them.


📝 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 makeMultiplier(factor) that returns a function multiplying its input by factor. Create double and triple and print double(5) and triple(5).

Show answer

📄 practice1.js

function makeMultiplier(factor) {
  return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5), triple(5));

🖥️ Output

10 15

Q2. Write createBankAccount(start) with methods deposit(amount), withdraw(amount) (refuse if the balance would go below 0) and balance(), keeping the balance private.

Show answer

📄 practice2.js

function createBankAccount(start = 0) {
  let balance = start;
  return {
    deposit(amount) { balance += amount; return balance; },
    withdraw(amount) {
      if (amount > balance) throw new Error("Insufficient funds");
      balance -= amount;
      return balance;
    },
    balance: () => balance,
  };
}

const acc = createBankAccount(100);
acc.deposit(50);
acc.withdraw(30);
console.log(acc.balance());
try { acc.withdraw(500); } catch (e) { console.log(e.message); }
console.log(acc.balance);   // a function, not the number

🖥️ Output

120
Insufficient funds
[Function: balance]

Q3. Predict the output, then fix the code so it prints 0, 1, 2.

var fns = [];
for (var i = 0; i < 3; i++) {
  fns.push(() => i);
}
console.log(fns.map((f) => f()));
Show answer

📄 practice3.js

var fns = [];
for (var i = 0; i < 3; i++) {
  fns.push(() => i);
}
console.log(fns.map((f) => f()));

const fixed = [];
for (let j = 0; j < 3; j++) {
  fixed.push(() => j);
}
console.log(fixed.map((f) => f()));

🖥️ Output

[ 3, 3, 3 ]
[ 0, 1, 2 ]

Q4. Write createIdGenerator(prefix) that returns IDs like "user-1", "user-2", with an independent counter per prefix.

Show answer

📄 practice4.js

function createIdGenerator(prefix) {
  let n = 0;
  return () => `${prefix}-${++n}`;
}
const userId = createIdGenerator("user");
const orderId = createIdGenerator("order");
console.log(userId(), userId(), orderId(), userId());

🖥️ Output

user-1 user-2 order-1 user-3

Q5. Write limitCalls(fn, max) that lets fn run at most max times, then returns "limit reached".

Show answer

📄 practice5.js

function limitCalls(fn, max) {
  let calls = 0;
  return (...args) => {
    if (calls >= max) return "limit reached";
    calls++;
    return fn(...args);
  };
}

const ping = limitCalls((host) => `pinged ${host}`, 2);
console.log(ping("a"), "|", ping("b"), "|", ping("c"));

🖥️ Output

pinged a | pinged b | limit reached

Q6. Explain in one sentence why count below is not reset to 0 on each call of next.

const next = (() => {
  let count = 0;
  return () => ++count;
})();
console.log(next(), next());
Show answer

📄 practice6.js

const next = (() => {
  let count = 0;
  return () => ++count;
})();
console.log(next(), next());

🖥️ Output

1 2

The outer arrow function runs only once (it is called immediately), creating one count; next is the inner function, which closes over that single variable and changes it on every call.


🧠 MCQ Quiz: Closures

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is a closure?
  2. What is printed?
    function f() {
      let x = 1;
      return () => ++x;
    }
    const g = f();
    console.log(g(), g());
  3. Do closures capture values or variables?
  4. How do you fix callbacks in a for (var i ...) loop that all see the last i?
  5. Two counters are made with const a = createCounter(); const b = createCounter();. Do they share a count?
  6. Which helper typically uses a closure?
  7. What is a function factory?
  8. How can a closure cause a memory leak?
  9. What is printed?
    let msg = "a";
    const show = () => msg;
    msg = "b";
    console.log(show());
  10. How does the closure in createTestRun() make results private?

💼 Interview Questions and Answers

Q1. What is a closure? Give a practical example.

A closure is a function bundled with references to the variables of the scope it was defined in, so it can use them after that scope has finished. Practical uses: private counters and state, function factories (validators, URL builders), once/memoize/debounce helpers, and callbacks that remember context, such as a test fixture remembering a created user to delete it in teardown.

Q2. Explain the output and fix it.

📄 interview-loop.js

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}

⌨️ Terminal

node interview-loop.js

🖥️ Output

var: 3
var: 3
var: 3
let: 0
let: 1
let: 2

All callbacks run after the loops finish. The var loop has one shared i (3 at the end), so it logs 3 three times. let gives each iteration its own j, so the second loop logs 0, 1, 2. Fixes for the first loop: use let, or pass i into a function (an IIFE) or as the third argument of setTimeout.

Q3. How are closures related to data privacy, and how does that compare with #private class fields?

Variables in a closure are reachable only through the functions that close over them, so they are private by construction; this is the “module pattern”. Class #private fields (ES2022) give the same guarantee with class syntax and work better with inheritance and tooling. Closures create new method functions for each instance, while class methods are shared on the prototype.

Q4. Can closures cause memory leaks? How do you avoid them?

Yes, indirectly. A closure keeps its captured scope alive; if the closure is stored somewhere long-lived (a global cache, an event listener, an interval), everything it captured stays in memory. Avoid it by removing listeners, clearing timers, bounding caches, and capturing only the small values you need instead of whole objects (for example a page object or a large response).


❓ Frequently Asked Questions

🤔 Is every function in JavaScript a closure?

Technically every function closes over its outer scope. In practice, people say “closure” when a function uses outer variables after the outer function has returned.

🤔 Why are closures important for testers?

Callbacks in tests, hooks and fixtures, retry helpers and test-data builders all rely on closures to remember configuration and state. Understanding them explains shared-state bugs and the var-in-loop problem.

🤔 What is an IIFE?

An immediately invoked function expression, such as (() => { ... })(). It runs once and creates a private scope. It was widely used before modules and let/const existed.

🤔 Do arrow functions create closures?

Yes. Arrow functions and regular functions close over their surrounding variables in the same way.


🏁 Summary

  • A closure is a function that keeps access to the variables of the scope where it was defined.
  • Closed-over variables are live and private: only the closure can read or change them.
  • Function factories, once, memoize, counters and retry helpers are built with closures.
  • Closures capture variables, not values: use let in loops to give each callback its own value.
  • Long-lived closures keep their captured data in memory, so clean up listeners, timers and caches.

Next, continue with Lesson 22: Callbacks and Higher-Order Functions.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Callbacks and Higher-Order Functions with Examples

In JavaScript you can hand a function to another function and say “call this when you need to”. That passed-in function is a callback, and the function that accepts or returns functions is a higher-order function. Array methods, timers, event listeners, Playwright’s test() and page.on() all work this way. In this lesson you will learn to write and use callbacks, build your own higher-order functions, compose small functions into pipelines, and wrap functions with logging and timing for test diagnostics.

📖 What You’ll Learn: callbacks, synchronous versus asynchronous callbacks, higher-order functions that take functions, higher-order functions that return functions, built-in higher-order methods (map, filter, find, sort, reduce), passing named functions versus inline arrows, function composition and pipelines, wrapper functions for logging and timing, and callback pitfalls.


📞 What Is a Callback?

Definition: a callback is a function passed as an argument to another function, which calls it (“calls it back”) at the right moment.

📄 callback.js

function processOrder(orderId, onDone) {
  console.log(`processing order ${orderId}...`);
  const status = "shipped";
  onDone(orderId, status);      // call the callback when the work is finished
}

function notify(id, status) {
  console.log(`order ${id} is ${status}`);
}

processOrder(101, notify);                                // pass a named function
processOrder(102, (id) => console.log(`log: ${id} done`)); // or an inline arrow

⌨️ Terminal

node callback.js

🖥️ Output

processing order 101...
order 101 is shipped
processing order 102...
log: 102 done

⚠️ Watch out: Pass the function, do not call it. processOrder(101, notify) passes the function; processOrder(101, notify()) calls notify immediately and passes its return value (undefined), which then fails with “onDone is not a function”.


⏱️ Synchronous vs Asynchronous Callbacks

A synchronous callback runs right away, before the outer function returns (array methods). An asynchronous callback runs later, after some event or delay (timers, events, network responses).

📄 sync-async.js

console.log("1. start");

[10, 20].forEach((n) => console.log(`2. sync callback: ${n}`));

setTimeout(() => console.log("5. async callback after 0 ms"), 0);

process.nextTick(() => console.log("4. nextTick callback"));

console.log("3. end of script");

⌨️ Terminal

node sync-async.js

🖥️ Output

1. start
2. sync callback: 10
2. sync callback: 20
3. end of script
4. nextTick callback
5. async callback after 0 ms

Even with a 0 ms delay, the timer callback runs only after the current code finishes. Module 10 explains the event loop that decides this order; for now, remember that an async callback never runs in the middle of your current code.


🔼 Higher-Order Functions

Definition: a higher-order function is a function that does at least one of these: takes a function as an argument, or returns a function. Ordinary functions that only work with numbers, strings and objects are called first-order functions.

Taking a function as an argument

📄 takes-function.js

function repeat(times, action) {
  for (let i = 1; i <= times; i++) {
    action(i);
  }
}

repeat(3, (n) => console.log(`run ${n}`));

function measure(label, fn) {
  const start = performance.now();
  const result = fn();
  const ms = (performance.now() - start).toFixed(1);
  console.log(`${label} took ${ms < 50 ? "under 50" : ms} ms`);
  return result;
}

const total = measure("sum to 100000", () => {
  let s = 0;
  for (let i = 1; i <= 100000; i++) s += i;
  return s;
});
console.log(total);

⌨️ Terminal

node takes-function.js

🖥️ Output

run 1
run 2
run 3
sum to 100000 took under 50 ms
5000050000

Returning a function

📄 returns-function.js

function greaterThan(limit) {
  return (value) => value > limit;
}

const slowerThan1s = greaterThan(1000);
console.log([450, 1200, 980, 3100].filter(slowerThan1s));

⌨️ Terminal

node returns-function.js

🖥️ Output

[ 1200, 3100 ]

Functions that return functions rely on closures (see the Closures lesson): slowerThan1s remembers limit.


🧰 Built-in Higher-Order Array Methods

The array methods you will use most are higher-order functions. Each takes a callback that receives (item, index, array):

MethodCallback returnsResult
mapA new valueA new array of the same length
filtertrue/falseA new array with the items that passed
findtrue/falseThe first matching item or undefined
some / everytrue/falseA boolean
sortA negative, zero or positive numberThe same array, sorted in place
reduceThe new accumulatorOne combined value
forEachNothingundefined (side effects only)

📄 array-hofs.js

const tests = [
  { name: "login", ms: 820, tags: ["smoke"] },
  { name: "export", ms: 4300, tags: ["slow"] },
  { name: "search", ms: 1430, tags: ["smoke", "api"] },
];

console.log(tests.map((t) => t.name));
console.log(tests.filter((t) => t.tags.includes("smoke")).map((t) => t.name));
console.log(tests.find((t) => t.ms > 4000)?.name);
console.log(tests.every((t) => t.ms < 5000));
console.log([...tests].sort((a, b) => b.ms - a.ms).map((t) => `${t.name}:${t.ms}`));
console.log(tests.reduce((sum, t) => sum + t.ms, 0));

⌨️ Terminal

node array-hofs.js

🖥️ Output

[ 'login', 'export', 'search' ]
[ 'login', 'search' ]
export
true
[ 'export:4300', 'search:1430', 'login:820' ]
6550

Module 6 covers map, filter and reduce in full depth.


🏷️ Named Functions vs Inline Arrows

You can pass an inline arrow or a named function. Named functions are reusable, testable on their own, and make chains read like sentences:

📄 named.js

const isFailed = (r) => r.status === "failed";
const toName = (r) => r.test;
const byName = (a, b) => a.localeCompare(b);

const results = [
  { test: "search", status: "failed" },
  { test: "cart", status: "passed" },
  { test: "auth", status: "failed" },
];

const failedNames = results.filter(isFailed).map(toName).sort(byName);
console.log(failedNames);

⌨️ Terminal

node named.js

🖥️ Output

[ 'auth', 'search' ]

⚠️ Watch out: Be careful passing existing functions that accept extra parameters. ["1", "2", "3"].map(parseInt) calls parseInt("2", 1) and parseInt("3", 2), because map passes the index as the second argument.

📄 parseint-trap.js

console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
console.log(["1", "2", "3"].map(Number));

⌨️ Terminal

node parseint-trap.js

🖥️ Output

[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

🔗 Function Composition and Pipelines

Definition: composition combines small functions so the output of one becomes the input of the next. A pipe helper applies functions left to right:

📄 pipe.js

const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);

const trim = (s) => s.trim();
const collapseSpaces = (s) => s.replace(/\s+/g, " ");
const lower = (s) => s.toLowerCase();

const normaliseText = pipe(trim, collapseSpaces, lower);

console.log(JSON.stringify(normaliseText("   Welcome   BACK,\n  Asha  ")));
console.log(normaliseText("  Order   CONFIRMED ") === "order confirmed");

⌨️ Terminal

node pipe.js

🖥️ Output

"welcome back, asha"
true

normaliseText is a reusable function built from three tiny ones. Text normalisation like this is exactly what you need before comparing UI text in tests.


🎁 Wrapper Functions: Logging, Timing and Error Context

A higher-order function can wrap another function to add behaviour before and after it, without changing the original code. This is sometimes called a decorator.

📄 wrapper.js

function withLogging(name, fn) {
  return (...args) => {
    console.log(`→ ${name}(${args.map((a) => JSON.stringify(a)).join(", ")})`);
    try {
      const result = fn(...args);
      console.log(`← ${name} returned ${JSON.stringify(result)}`);
      return result;
    } catch (e) {
      console.log(`✖ ${name} threw: ${e.message}`);
      throw e;
    }
  };
}

const applyDiscount = withLogging("applyDiscount", (price, code) => {
  if (code !== "SAVE10") throw new Error(`Invalid code ${code}`);
  return price * 0.9;
});

applyDiscount(200, "SAVE10");
try {
  applyDiscount(200, "FREE");
} catch {}

⌨️ Terminal

node wrapper.js

🖥️ Output

→ applyDiscount(200, "SAVE10")
← applyDiscount returned 180
→ applyDiscount(200, "FREE")
✖ applyDiscount threw: Invalid code FREE

Test frameworks use the same idea: Playwright’s test.step("name", async () => {...}) wraps your function so the report shows each step with its duration and result.


🧪 Tester Scenario: A Mini Test Runner

A test runner is a higher-order program: you register callbacks, and it decides when to call them. This 25-line version shows how test(), hooks and reporting work under the hood:

📄 mini-runner.js

const registry = [];
const hooks = { beforeEach: [] };

const test = (name, fn) => registry.push({ name, fn });
const beforeEach = (fn) => hooks.beforeEach.push(fn);

function run() {
  let passed = 0;
  for (const { name, fn } of registry) {
    const context = {};
    try {
      hooks.beforeEach.forEach((hook) => hook(context));
      fn(context);
      passed++;
      console.log(`  ✓ ${name}`);
    } catch (e) {
      console.log(`  ✗ ${name}: ${e.message}`);
    }
  }
  console.log(`${passed}/${registry.length} passed`);
}

// --- tests ---
beforeEach((ctx) => { ctx.cart = []; });

test("cart starts empty", (ctx) => {
  if (ctx.cart.length !== 0) throw new Error("cart not empty");
});
test("adds an item", (ctx) => {
  ctx.cart.push("pen");
  if (ctx.cart.length !== 1) throw new Error("expected 1 item");
});
test("total is calculated", () => {
  const total = [10, 20].reduce((a, b) => a + b, 0);
  if (total !== 40) throw new Error(`expected 40, got ${total}`);
});

run();

⌨️ Terminal

node mini-runner.js

🖥️ Output

  ✓ cart starts empty
  ✓ adds an item
  ✗ total is calculated: expected 40, got 30
2/3 passed
  • test and beforeEach are higher-order functions: they store your callbacks for later.
  • run calls each callback with a fresh context object, which is how fixtures give each test isolated state.
  • A test fails when its callback throws, exactly as in Playwright and Jest.

📝 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 applyToAll(numbers, fn) that returns a new array with fn applied to each number (without using map). Test it with a squaring callback.

Show answer

📄 practice1.js

function applyToAll(numbers, fn) {
  const result = [];
  for (const n of numbers) result.push(fn(n));
  return result;
}
console.log(applyToAll([1, 2, 3, 4], (n) => n * n));

🖥️ Output

[ 1, 4, 9, 16 ]

Q2. Write makeLogger(prefix) that returns a function which logs messages with that prefix. Create info and error loggers.

Show answer

📄 practice2.js

const makeLogger = (prefix) => (message) => console.log(`[${prefix}] ${message}`);
const info = makeLogger("INFO");
const error = makeLogger("ERROR");
info("suite started");
error("login failed");

🖥️ Output

[INFO] suite started
[ERROR] login failed

Q3. From [{ name: "a", price: 30 }, { name: "b", price: 120 }, { name: "c", price: 75 }], get the names of items costing more than 50, sorted by price from high to low.

Show answer

📄 practice3.js

const items = [{ name: "a", price: 30 }, { name: "b", price: 120 }, { name: "c", price: 75 }];
const result = items
  .filter((i) => i.price > 50)
  .sort((x, y) => y.price - x.price)
  .map((i) => i.name);
console.log(result);

🖥️ Output

[ 'b', 'c' ]

Q4. Write compose2(f, g) that returns a function computing f(g(x)). Use it to build shout from toUpper and addExclamation.

Show answer

📄 practice4.js

const compose2 = (f, g) => (x) => f(g(x));
const toUpper = (s) => s.toUpperCase();
const addExclamation = (s) => s + "!";
const shout = compose2(addExclamation, toUpper);
console.log(shout("test passed"));

🖥️ Output

TEST PASSED!

Q5. Write timed(fn) that returns a wrapped function which prints how many calls have been made so far each time it is called, then returns the original result.

Show answer

📄 practice5.js

function timed(fn) {
  let calls = 0;
  return (...args) => {
    calls++;
    console.log(`call #${calls}`);
    return fn(...args);
  };
}
const add = timed((a, b) => a + b);
console.log(add(1, 2));
console.log(add(5, 5));

🖥️ Output

call #1
3
call #2
10

Q6. Why does ["10", "10", "10"].map(parseInt) not return [10, 10, 10]? Print the result and a correct version.

Show answer

📄 practice6.js

console.log(["10", "10", "10"].map(parseInt));
console.log(["10", "10", "10"].map((s) => parseInt(s, 10)));

🖥️ Output

[ 10, NaN, 2 ]
[ 10, 10, 10 ]

map passes (item, index), so the calls are parseInt("10", 0) (base 10 by default), parseInt("10", 1) (invalid base: NaN) and parseInt("10", 2) (binary: 2).


🧠 MCQ Quiz: Callbacks and Higher-Order 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.

  1. What is a callback?
  2. Which is a higher-order function?
  3. What is wrong with setTimeout(sendReport(), 1000)?
  4. In which order is this printed?
    setTimeout(() => console.log("A"), 0);
    console.log("B");
  5. What does [1, 2, 3].filter((n) => n > 1) return?
  6. Which method changes the original array?
  7. What does pipe(f, g)(x) compute?
  8. What arguments does map pass to its callback?
  9. What is a wrapper (decorator) function?
  10. In a test runner, why is test("name", fn) a higher-order function?

💼 Interview Questions and Answers

Q1. What is the difference between a callback and a higher-order function?

They are two sides of the same relationship. The higher-order function is the one that accepts (or returns) a function, for example array.map or setTimeout. The callback is the function that is passed in, for example (x) => x * 2. A function can be both: a callback that itself takes a callback.

Q2. What is callback hell, and how is it avoided?

When asynchronous steps are chained with nested callbacks (each step inside the previous step’s callback), code drifts right, error handling is repeated at every level, and the flow is hard to follow. It is avoided with named functions, and in modern code with promises and async/await, which flatten the sequence into ordinary-looking statements (Module 10).

Q3. Write a function that retries another function until it returns true or a limit is reached.

📄 until.js

function until(check, { max = 5 } = {}) {
  for (let attempt = 1; attempt <= max; attempt++) {
    if (check(attempt)) return attempt;
  }
  throw new Error(`Condition not met after ${max} attempts`);
}

console.log(until((n) => n === 3));
try { until(() => false, { max: 2 }); } catch (e) { console.log(e.message); }

⌨️ Terminal

node until.js

🖥️ Output

3
Condition not met after 2 attempts

In real tests the check would be asynchronous and include a delay; Playwright offers expect.poll() and expect(...).toPass() for this.

Q4. Why might passing an object method as a callback break it?

When you pass obj.method as a callback, only the function is passed; when the higher-order function calls it, this is no longer obj. Fix it with an arrow wrapper () => obj.method() or obj.method.bind(obj). The next lesson covers this and bind.


❓ Frequently Asked Questions

🤔 Are callbacks always asynchronous?

No. Array method callbacks run synchronously. Timer, event and I/O callbacks run asynchronously.

🤔 What are examples of higher-order functions in JavaScript?

map, filter, reduce, sort, forEach, setTimeout, addEventListener, Promise.then, and in testing test(), describe(), beforeEach().

🤔 Should I pass named functions or inline arrows?

Inline arrows for short, one-off logic; named functions when the logic is reused, needs tests, or makes a chain easier to read.

🤔 What is function composition used for?

Building complex transformations from small, tested functions, for example normalising text, transforming API data or building test-data variations.


🏁 Summary

  • A callback is a function passed to another function; pass the function itself, not its result.
  • Synchronous callbacks run immediately (array methods); asynchronous ones run later (timers, events, I/O).
  • Higher-order functions take functions as arguments or return them; map, filter, sort and reduce are built-in examples.
  • Named callbacks, pipe/compose and wrapper functions keep code small, reusable and testable.
  • Test runners are higher-order programs: they store your test callbacks and call them with fresh context.

Next, continue with Lesson 23: this, call, apply and bind.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Recursion: Base Case, Call Stack and Real Examples

Some problems contain smaller copies of themselves: a folder holds folders, a JSON response holds nested objects, a menu holds sub-menus. Recursion solves them by letting a function call itself on the smaller piece until it reaches a piece simple enough to answer directly. In this lesson you will learn how recursive functions work, how the call stack runs them, how to avoid the “Maximum call stack size exceeded” error, and how to use recursion on real nested data such as API responses and test configuration.

📖 What You’ll Learn: what recursion is, the base case and the recursive case, tracing calls on the call stack, classic examples (factorial, sum, countdown), stack overflow and RangeError, recursion versus loops, recursion on nested arrays and objects (flatten, deep search, deep count), memoizing slow recursion, and when not to use recursion.


🪞 What Is Recursion?

Definition: recursion is when a function calls itself. Every recursive function needs two parts:

  • A base case: a simple input the function answers directly, without calling itself. This is what stops the recursion.
  • A recursive case: the function calls itself with a smaller or simpler input that moves towards the base case.

📄 countdown.js

function countdown(n) {
  if (n === 0) {              // base case
    console.log("Liftoff!");
    return;
  }
  console.log(n);
  countdown(n - 1);           // recursive case: a smaller problem
}

countdown(3);

⌨️ Terminal

node countdown.js

🖥️ Output

3
2
1
Liftoff!

Each call handles one number and hands the rest of the work to a call with n - 1, until n reaches 0.


🧮 Classic Examples: Sum and Factorial

The sum of the numbers from 1 to n is n plus the sum from 1 to n - 1:

📄 classic.js

function sumTo(n) {
  if (n <= 1) return n;          // base case
  return n + sumTo(n - 1);       // recursive case
}

function factorial(n) {
  if (n <= 1) return 1;          // 0! and 1! are 1
  return n * factorial(n - 1);
}

console.log(sumTo(5), sumTo(100));
console.log(factorial(5), factorial(10));

⌨️ Terminal

node classic.js

🖥️ Output

15 5050
120 3628800

Read factorial(5) as: 5 × factorial(4) = 5 × 4 × factorial(3) = … = 5 × 4 × 3 × 2 × 1 = 120.


📚 How It Runs: The Call Stack

Definition: the call stack is the list of function calls that have started but not finished. Each call is pushed on top of the stack; when it returns, it is popped off and the call below it continues.

This version prints each step so you can watch the stack grow and shrink:

📄 trace.js

function factorial(n, depth = 0) {
  const pad = "  ".repeat(depth);
  console.log(`${pad}factorial(${n}) called`);
  if (n <= 1) {
    console.log(`${pad}base case -> 1`);
    return 1;
  }
  const result = n * factorial(n - 1, depth + 1);
  console.log(`${pad}factorial(${n}) returns ${result}`);
  return result;
}

factorial(4);

⌨️ Terminal

node trace.js

🖥️ Output

factorial(4) called
  factorial(3) called
    factorial(2) called
      factorial(1) called
      base case -> 1
    factorial(2) returns 2
  factorial(3) returns 6
factorial(4) returns 24
  • The calls go down until the base case: 4 → 3 → 2 → 1. All of them are waiting on the stack at that moment.
  • Then the results come back up: 1, then 2 × 1, then 3 × 2, then 4 × 6.
  • Every waiting call uses memory, which is why very deep recursion can run out of stack space.

💥 Stack Overflow: Maximum Call Stack Size Exceeded

If the base case is missing or never reached, the function calls itself until the stack is full, and JavaScript throws a RangeError:

📄 overflow.js

let calls = 0;

function brokenCountdown(n) {
  calls++;
  brokenCountdown(n - 1);   // no base case: never stops
}

try {
  brokenCountdown(3);
} catch (e) {
  console.log(`${e.name}: ${e.message}`);
  console.log("more than 1,000 nested calls before it failed?", calls > 1000);
}

⌨️ Terminal

node overflow.js

🖥️ Output

RangeError: Maximum call stack size exceeded
more than 1,000 nested calls before it failed? true

The exact number of calls before the crash depends on the engine and the machine, typically around ten thousand. Common causes:

  • No base case, or a base case that cannot be reached (for example checking n === 0 when n can go negative or be a decimal).
  • The recursive call does not make the problem smaller (calling f(n) instead of f(n - 1)).
  • Data with a cycle, such as an object that references itself, when walking nested objects.
  • Legitimately very deep input (hundreds of thousands of levels). Use a loop instead.

💡 Tip: Make base cases defensive: if (n <= 0) is safer than if (n === 0), because it also stops for negative input.


🔁 Recursion vs Loops

Anything written recursively can also be written with a loop, and the reverse. Choose the one that matches the shape of the problem:

📄 vs-loop.js

// Same result, two styles
const sumRecursive = (n) => (n <= 0 ? 0 : n + sumRecursive(n - 1));

function sumLoop(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
}

console.log(sumRecursive(1000), sumLoop(1000));

try {
  sumRecursive(100000);       // too deep for the default stack
} catch (e) {
  console.log("recursive:", e.name);
}
console.log("loop:", sumLoop(100000));

⌨️ Terminal

node vs-loop.js

🖥️ Output

500500 500500
recursive: RangeError
loop: 5000050000
UseWhen
A loopFlat repetition: counting, walking an array, retrying. Very large or unknown depth.
RecursionNested, tree-shaped data: folders, menus, nested JSON, DOM trees, comment threads. Divide-and-conquer algorithms.

📌 Note: JavaScript engines in practice do not optimise “tail calls”, so even a recursive call in the last position still uses a stack frame. Do not rely on recursion for depths in the tens of thousands.


🌳 Recursion on Nested Data

Recursion is the natural tool when data can contain more of the same data at any depth. Three common jobs:

Flatten a nested array

📄 flatten.js

function flatten(list) {
  const result = [];
  for (const item of list) {
    if (Array.isArray(item)) {
      result.push(...flatten(item));   // recurse into the nested array
    } else {
      result.push(item);
    }
  }
  return result;
}

const suites = ["login", ["cart", ["add", "remove"]], [["checkout"]]];
console.log(flatten(suites));
console.log(suites.flat(Infinity));   // built-in equivalent

⌨️ Terminal

node flatten.js

🖥️ Output

[ 'login', 'cart', 'add', 'remove', 'checkout' ]
[ 'login', 'cart', 'add', 'remove', 'checkout' ]

Find all values of a key anywhere in a JSON object

📄 find-all.js

function findAll(data, key, found = []) {
  if (Array.isArray(data)) {
    for (const item of data) findAll(item, key, found);
  } else if (data !== null && typeof data === "object") {
    for (const [k, v] of Object.entries(data)) {
      if (k === key) found.push(v);
      findAll(v, key, found);
    }
  }
  return found;
}

const response = {
  order: { id: 501, items: [
    { id: 1, sku: "PEN-1", options: { colour: { id: "c-blue" } } },
    { id: 2, sku: "BOOK-9" },
  ] },
  customer: { id: 77 },
};

console.log(findAll(response, "id"));
console.log(findAll(response, "sku"));

⌨️ Terminal

node find-all.js

🖥️ Output

[ 501, 1, 'c-blue', 2, 77 ]
[ 'PEN-1', 'BOOK-9' ]

Count items in a nested menu

📄 menu.js

const menu = [
  { label: "Tutorials", children: [
    { label: "JavaScript", children: [{ label: "Basics" }, { label: "Async" }] },
    { label: "Playwright" },
  ] },
  { label: "Practice" },
];

function countItems(items) {
  let count = 0;
  for (const item of items) {
    count += 1;
    if (item.children) count += countItems(item.children);
  }
  return count;
}

function printTree(items, depth = 0) {
  for (const item of items) {
    console.log(`${"  ".repeat(depth)}- ${item.label}`);
    if (item.children) printTree(item.children, depth + 1);
  }
}

printTree(menu);
console.log("menu items:", countItems(menu));

⌨️ Terminal

node menu.js

🖥️ Output

- Tutorials
  - JavaScript
    - Basics
    - Async
  - Playwright
- Practice
menu items: 6

A UI test can use the same function to check that every menu link was rendered, whatever the depth of the menu.


⚡ Making Slow Recursion Fast: Memoization

Some recursive functions call themselves with the same input many times. The Fibonacci sequence is the classic example: fib(n) = fib(n - 1) + fib(n - 2).

📄 fibonacci.js

let calls = 0;
function fib(n) {
  calls++;
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}
console.log(fib(25), "calls:", calls);

const memo = new Map();
let memoCalls = 0;
function fibMemo(n) {
  memoCalls++;
  if (n <= 1) return n;
  if (memo.has(n)) return memo.get(n);
  const value = fibMemo(n - 1) + fibMemo(n - 2);
  memo.set(n, value);
  return value;
}
console.log(fibMemo(25), "calls:", memoCalls);
console.log(fibMemo(70));   // instant with memoization

⌨️ Terminal

node fibonacci.js

🖥️ Output

75025 calls: 242785
75025 calls: 49
190392490709135

Storing results that were already calculated (memoization, see the Closures lesson) turns hundreds of thousands of calls into a few dozen.


🧪 Tester Scenario: Compare Two Nested Objects and Report Differences

When an API response differs from the expected data, a test should say exactly where. This recursive function walks both objects and reports each different path:

📄 diff.js

function diff(expected, actual, path = "$") {
  const isObj = (v) => v !== null && typeof v === "object";
  if (!isObj(expected) || !isObj(actual)) {
    return Object.is(expected, actual) ? [] : [`${path}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`];
  }
  const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
  const problems = [];
  for (const key of keys) {
    const childPath = Array.isArray(expected) ? `${path}[${key}]` : `${path}.${key}`;
    problems.push(...diff(expected[key], actual[key], childPath));
  }
  return problems;
}

const expected = { id: 7, user: { name: "Asha", roles: ["tester", "admin"] }, active: true };
const actual = { id: 7, user: { name: "Asha", roles: ["tester"] }, active: "true", extra: 1 };

const problems = diff(expected, actual);
console.log(problems.length === 0 ? "objects match" : problems.join("\n"));

⌨️ Terminal

node diff.js

🖥️ Output

$.user.roles[1]: expected "admin", got undefined
$.active: expected true, got "true"
$.extra: expected undefined, got 1

Test frameworks do this for you (toEqual prints a diff), but writing it once shows how recursion handles data of any shape.


📝 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 a recursive power(base, exp) for whole, non-negative exponents.

Show answer

📄 practice1.js

function power(base, exp) {
  if (exp <= 0) return 1;
  return base * power(base, exp - 1);
}
console.log(power(2, 10), power(5, 0), power(3, 4));

🖥️ Output

1024 1 81

Q2. Write a recursive reverse(str) that reverses a string.

Show answer

📄 practice2.js

function reverse(str) {
  if (str.length <= 1) return str;
  return reverse(str.slice(1)) + str[0];
}
console.log(reverse("recursion"));

🖥️ Output

noisrucer

Q3. Write a recursive sumDigits(n) that adds the digits of a positive integer, e.g. sumDigits(4096) is 19.

Show answer

📄 practice3.js

function sumDigits(n) {
  if (n < 10) return n;
  return (n % 10) + sumDigits(Math.floor(n / 10));
}
console.log(sumDigits(4096), sumDigits(7));

🖥️ Output

19 7

Q4. Write a recursive isPalindrome(s) that ignores case.

Show answer

📄 practice4.js

function isPalindrome(s) {
  s = s.toLowerCase();
  if (s.length <= 1) return true;
  if (s[0] !== s[s.length - 1]) return false;
  return isPalindrome(s.slice(1, -1));
}
console.log(isPalindrome("Level"), isPalindrome("Racecar"), isPalindrome("Tester"));

🖥️ Output

true true false

Q5. Write depth(value) that returns how deeply nested an array is: depth(5) is 0, depth([1]) is 1, depth([1, [2, [3]]]) is 3.

Show answer

📄 practice5.js

function depth(value) {
  if (!Array.isArray(value)) return 0;
  if (value.length === 0) return 1;
  return 1 + Math.max(...value.map(depth));
}
console.log(depth(5), depth([1]), depth([1, [2, [3]]]), depth([]));

🖥️ Output

0 1 3 1

Q6. This function never stops for countdown(2.5). Explain why and make the base case safe.

function countdown(n) {
  if (n === 0) return "done";
  return countdown(n - 1);
}
Show answer

2.5 → 1.5 → 0.5 → -0.5 … never equals 0, so the base case is never reached. Use a range check:

📄 practice6.js

function countdown(n) {
  if (n <= 0) return "done";
  return countdown(n - 1);
}
console.log(countdown(2.5), countdown(3), countdown(-4));

🖥️ Output

done done done

🧠 MCQ Quiz: Recursion

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What two parts must every recursive function have?
  2. What is factorial(4) with f(n) = n <= 1 ? 1 : n * f(n - 1)?
  3. Which error is thrown when recursion never stops?
  4. What is the call stack?
  5. Which problem is the most natural fit for recursion?
  6. Why is if (n <= 0) often safer than if (n === 0) as a base case?
  7. What does memoization do for recursive functions?
  8. What does [1, [2, [3, [4]]]].flat(Infinity) return?
  9. For summing numbers up to 1,000,000, which is safer?
  10. In sumTo(n) = n + sumTo(n - 1), which happens first?

💼 Interview Questions and Answers

Q1. What is recursion, and what is a base case?

Recursion is a technique where a function solves a problem by calling itself on a smaller instance of the same problem. The base case is the condition under which the function returns a result directly without recursing; it guarantees termination. Each recursive call must move the input closer to the base case.

Q2. What causes “Maximum call stack size exceeded”, and how do you fix it?

Each pending call occupies a stack frame; when too many accumulate, the engine throws a RangeError. Causes: a missing or unreachable base case, a recursive call that does not shrink the input, cyclic data, or genuinely huge depth. Fixes: correct the base case (use ranges like <= 0), track visited objects for cyclic data, or rewrite the algorithm with a loop and an explicit stack.

Q3. Rewrite a recursive tree walk iteratively.

📄 iterative.js

const tree = { name: "root", children: [
  { name: "a", children: [{ name: "a1" }] },
  { name: "b" },
] };

function namesIterative(root) {
  const stack = [root];
  const names = [];
  while (stack.length > 0) {
    const node = stack.pop();
    names.push(node.name);
    for (const child of [...(node.children ?? [])].reverse()) stack.push(child);
  }
  return names;
}
console.log(namesIterative(tree));

⌨️ Terminal

node iterative.js

🖥️ Output

[ 'root', 'a', 'a1', 'b' ]

An explicit array replaces the call stack, so depth is limited only by memory. Pushing children in reverse keeps the same order as the recursive version.

Q4. When would you use recursion in test automation?

For any nested structure of unknown depth: comparing or searching nested JSON responses, walking nested menus or tree views to check every node, traversing folders of test data files, or flattening nested test configuration. For flat repetition such as retries and polling, a loop is simpler and safer.


❓ Frequently Asked Questions

🤔 Is recursion slower than a loop in JavaScript?

Usually a little, because each call has overhead and uses stack memory. For tree-shaped data the clarity is worth it; for large flat repetition use a loop.

🤔 How deep can recursion go in JavaScript?

It depends on the engine, stack size and how much each call stores; typically around ten thousand frames. Do not design code that relies on a specific limit.

🤔 Does JavaScript support tail call optimisation?

It is in the ES2015 specification, but V8 (Chrome and Node.js) and most engines do not implement it, so treat every recursive call as using a stack frame.

🤔 What is the difference between recursion and iteration?

Iteration repeats with a loop and keeps state in variables. Recursion repeats by calling the function again and keeps state on the call stack. Both can solve the same problems.


🏁 Summary

  • A recursive function calls itself; it needs a base case that stops and a recursive case that makes the problem smaller.
  • Calls wait on the call stack until the base case returns; results then flow back up.
  • A missing or unreachable base case causes RangeError: Maximum call stack size exceeded.
  • Use loops for flat or very deep repetition, and recursion for nested data such as JSON, menus and folders.
  • Memoization removes repeated work in recursive functions such as Fibonacci.

Next, continue with Lesson 25: Strings and String Methods. This completes Module 4. Module 5 continues with strings and regular expressions.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript this Keyword, call, apply and bind Explained

this is the most misunderstood keyword in JavaScript, because its value is not fixed where a function is written but decided by how the function is called. That is why a page-object method works when called as loginPage.open() and breaks when passed as a callback. In this lesson you will learn the simple rules that decide this, how arrow functions differ, and how call, apply and bind let you control it.

📖 What You’ll Learn: what this is, the four binding rules (method call, plain call, explicit binding, new), this in strict mode, this in arrow functions, this in classes, losing this in callbacks and how to fix it, call, apply and bind, borrowing methods, and a page-object style example.


🎯 What Is this?

Definition: this is a special value available inside a (non-arrow) function. It refers to the object the function is working on, and it is set each time the function is called, based on how it is called.

Four rules decide it, checked in this order:

Call styleExamplethis is
With newnew User()The newly created object
Explicit bindingfn.call(obj), fn.apply(obj), fn.bind(obj)()obj
Method callobj.fn()The object before the dot: obj
Plain callfn()undefined in strict mode; the global object in sloppy mode

Arrow functions ignore all four rules: they use the this of the surrounding code (lexical this).


📍 Rule 1: Method Calls

When a function is called as a property of an object, this is that object:

📄 method-call.js

const loginPage = {
  url: "/login",
  attempts: 0,
  open() {
    this.attempts++;
    return `opening ${this.url} (attempt ${this.attempts})`;
  },
};

console.log(loginPage.open());
console.log(loginPage.open());

const cartPage = { url: "/cart", attempts: 0, open: loginPage.open };
console.log(cartPage.open());   // same function, different object before the dot

⌨️ Terminal

node method-call.js

🖥️ Output

opening /login (attempt 1)
opening /login (attempt 2)
opening /cart (attempt 1)

The same function gives different results depending on which object it is called on. this belongs to the call, not to the function.


🕳️ Rule 2: Plain Calls and Strict Mode

If you take a method out of its object and call it on its own, there is no object before the dot. In strict mode (ES modules, classes, "use strict") this is then undefined, so reading a property throws:

📄 plain-call.js

"use strict";

const loginPage = {
  url: "/login",
  open() {
    return `opening ${this.url}`;
  },
};

const open = loginPage.open;   // copy the function out of the object
console.log(typeof open);
console.log(open());           // plain call: this is undefined

⌨️ Terminal

node plain-call.js

🖥️ Output

function
/home/you/js-course/plain-call.js:6
    return `opening ${this.url}`;
                           ^

TypeError: Cannot read properties of undefined (reading 'url')
    at open (/home/you/js-course/plain-call.js:6:28)
    at Object.<anonymous> (/home/you/js-course/plain-call.js:12:13)

Node.js v26.13.0

In sloppy mode this would be the global object instead, so this.url would quietly be undefined. Strict mode turns the silent bug into a clear error, which is one more reason to prefer it.


🔁 Losing this in Callbacks

The same problem happens whenever you pass a method as a callback, because the receiving function calls it as a plain function:

📄 lost-this.js

"use strict";

const reporter = {
  prefix: "[REPORT]",
  log(message) {
    return `${this.prefix} ${message}`;
  },
};

try {
  console.log(["login ok", "cart ok"].map(reporter.log));
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

// Fix 1: wrap in an arrow function so it is still a method call
console.log(["login ok", "cart ok"].map((m) => reporter.log(m)));

// Fix 2: bind this permanently
console.log(["login ok", "cart ok"].map(reporter.log.bind(reporter)));

⌨️ Terminal

node lost-this.js

🖥️ Output

TypeError: Cannot read properties of undefined (reading 'prefix')
[ '[REPORT] login ok', '[REPORT] cart ok' ]
[ '[REPORT] login ok', '[REPORT] cart ok' ]

💡 Tip: When you see “Cannot read properties of undefined” inside a method that works elsewhere, check how it was called. A method passed to map, setTimeout, addEventListener or a test hook has usually lost its this.


➡️ this in Arrow Functions

Arrow functions do not have their own this; they use the this of the code where they are written. Inside a method, that is exactly what you want for callbacks:

📄 arrow-this.js

const suite = {
  name: "Checkout",
  tests: ["add item", "pay"],
  list() {
    return this.tests.map((t) => `${this.name} › ${t}`);   // arrow uses list's this
  },
};
console.log(suite.list());

const broken = {
  name: "Broken",
  list: () => typeof this,   // arrow at object level: not the object
};
console.log(broken.list());

⌨️ Terminal

node arrow-this.js

🖥️ Output

[ 'Checkout › add item', 'Checkout › pay' ]
object

Rule of thumb: use method shorthand for methods, and arrow functions for callbacks inside methods. The Arrow Functions lesson has more examples.


🏗️ Rule 3: this with new and in Classes

When a function is called with new (or a class is instantiated), JavaScript creates a new object and sets this to it. In class methods, this is the instance the method is called on:

📄 class-this.js

class Counter {
  count = 0;
  increment() {
    this.count++;
    return this.count;
  }
}

const c = new Counter();
console.log(c.increment(), c.increment());

const inc = c.increment;   // detached method
try {
  inc();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node class-this.js

🖥️ Output

1 2
TypeError: Cannot read properties of undefined (reading 'count')

Class bodies are always strict, so a detached method gets this === undefined. A common fix in classes is an arrow-function field, which captures the instance:

📄 arrow-field.js

class Button {
  label = "Save";
  click = () => `clicked ${this.label}`;   // arrow field: this is the instance
}
const handler = new Button().click;
console.log(handler());

⌨️ Terminal

node arrow-field.js

🖥️ Output

clicked Save

Classes are covered fully in Module 8.


📞 call and apply: Choose this for One Call

Definition: fn.call(thisArg, arg1, arg2, ...) calls fn once with this set to thisArg. fn.apply(thisArg, [arg1, arg2]) does the same but takes the arguments as an array.

📄 call-apply.js

function describe(env, browser) {
  return `${this.name} on ${env} using ${browser}`;
}

const smoke = { name: "Smoke suite" };
const regression = { name: "Regression suite" };

console.log(describe.call(smoke, "qa", "chromium"));
console.log(describe.apply(regression, ["staging", "firefox"]));

⌨️ Terminal

node call-apply.js

🖥️ Output

Smoke suite on qa using chromium
Regression suite on staging using firefox

💡 Tip: Memory aid: Apply takes an Array, Call takes Commas. With spread syntax, fn.call(obj, ...args) can replace apply in modern code.

Borrowing methods

call lets you use a method from one object on another object, for example array methods on array-like objects:

📄 borrow.js

function joinArgs() {
  // arguments is array-like, not a real array, so it has no join method
  return Array.prototype.join.call(arguments, " | ");
}
console.log(joinArgs("login", "search", "cart"));

const arrayLike = { 0: "a", 1: "b", length: 2 };
console.log(Array.prototype.map.call(arrayLike, (x) => x.toUpperCase()));
console.log(Array.from(arrayLike));   // modern alternative: convert first

⌨️ Terminal

node borrow.js

🖥️ Output

login | search | cart
[ 'A', 'B' ]
[ 'a', 'b' ]

🔗 bind: Fix this Permanently

Definition: fn.bind(thisArg, ...presetArgs) does not call fn. It returns a new function whose this is permanently set to thisArg, optionally with some arguments filled in already (partial application).

📄 bind.js

const api = {
  baseURL: "https://qa.example.com",
  get(path) {
    return `GET ${this.baseURL}${path}`;
  },
};

const get = api.get.bind(api);          // safe to pass around
console.log(get("/users"));
console.log(["/orders", "/cart"].map(get)); // still works as a callback

function multiply(a, b) {
  return a * b;
}
const double = multiply.bind(null, 2);  // preset the first argument
console.log(double(21));

const bound = api.get.bind(api);
console.log(bound.call({ baseURL: "https://evil.example" }, "/x"));   // bind wins over call

⌨️ Terminal

node bind.js

🖥️ Output

GET https://qa.example.com/users
[
  'GET https://qa.example.com/orders',
  'GET https://qa.example.com/cart'
]
42
GET https://qa.example.com/x
MethodCalls the function now?ArgumentsReturns
callYesOne by oneThe function’s result
applyYesAs an arrayThe function’s result
bindNoOptional preset argumentsA new bound function

🧪 Tester Scenario: A Page Object Used Safely in Callbacks

Page objects are classes or objects whose methods use this to reach their URL, locators and helpers. This simulated page object shows a failing callback and the two standard fixes:

📄 page-object.js

class SearchPage {
  constructor(baseURL) {
    this.baseURL = baseURL;
    this.history = [];
  }
  search(term) {
    const url = `${this.baseURL}/search?q=${encodeURIComponent(term)}`;
    this.history.push(url);
    return url;
  }
}

const page = new SearchPage("https://qa.example.com");
const terms = ["laptop", "usb cable"];

try {
  terms.forEach(page.search);              // this is undefined inside search
} catch (e) {
  console.log("broken:", e.message);
}

terms.forEach((t) => page.search(t));     // fix 1: arrow wrapper
terms.forEach(page.search.bind(page));    // fix 2: bind
console.log(page.history);

⌨️ Terminal

node page-object.js

🖥️ Output

broken: Cannot read properties of undefined (reading 'baseURL')
[
  'https://qa.example.com/search?q=laptop',
  'https://qa.example.com/search?q=usb%20cable',
  'https://qa.example.com/search?q=laptop',
  'https://qa.example.com/search?q=usb%20cable'
]

In Playwright, page objects are usually called directly inside an async test (await loginPage.login(user)), which is a method call and keeps this. The problem appears when methods are passed to helpers, array methods or event handlers.


📝 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. Create an object user with name and a method greet() that returns "Hi, I am <name>" using this.

Show answer

📄 practice1.js

const user = {
  name: "Asha",
  greet() {
    return `Hi, I am ${this.name}`;
  },
};
console.log(user.greet());

🖥️ Output

Hi, I am Asha

Q2. Use call to run function intro(role) { return `${this.name} is a ${role}`; } for { name: "Ravi" } with the role "tester", then use apply for { name: "Meera" } with "developer".

Show answer

📄 practice2.js

function intro(role) {
  return `${this.name} is a ${role}`;
}
console.log(intro.call({ name: "Ravi" }, "tester"));
console.log(intro.apply({ name: "Meera" }, ["developer"]));

🖥️ Output

Ravi is a tester
Meera is a developer

Q3. This prints undefined items. Fix it in two different ways.

const cart = {
  items: 3,
  report() { return `${this.items} items`; },
};
const show = cart.report;
console.log(show());
Show answer

📄 practice3.js

const cart = {
  items: 3,
  report() { return `${this.items} items`; },
};
const show1 = () => cart.report();      // fix 1: call it as a method
const show2 = cart.report.bind(cart);   // fix 2: bind
console.log(show1(), "|", show2());

🖥️ Output

3 items | 3 items

Q4. Use bind to create addTax from function withRate(rate, amount) { return amount * (1 + rate); } with the rate fixed at 0.18, and print addTax(1000).

Show answer

📄 practice4.js

function withRate(rate, amount) {
  return amount * (1 + rate);
}
const addTax = withRate.bind(null, 0.18);
console.log(addTax(1000));

🖥️ Output

1180

null is passed as this because the function does not use this.

Q5. Predict the output, then run it.

const obj = {
  name: "obj",
  regular() { return this.name; },
  arrow: () => typeof this,
  nested() { return (() => this.name)(); },
};
console.log(obj.regular(), obj.arrow(), obj.nested());
Show answer

📄 practice5.js

const obj = {
  name: "obj",
  regular() { return this.name; },
  arrow: () => typeof this,
  nested() { return (() => this.name)(); },
};
console.log(obj.regular(), obj.arrow(), obj.nested());

🖥️ Output

obj object obj

regular is a method call. arrow takes this from the module scope (an empty module.exports object in CommonJS), not from obj. The arrow inside nested uses nested‘s this, which is obj.

Q6. Use Array.prototype.filter.call to get the even numbers from the array-like object { 0: 4, 1: 7, 2: 10, length: 3 }.

Show answer

📄 practice6.js

const arrayLike = { 0: 4, 1: 7, 2: 10, length: 3 };
console.log(Array.prototype.filter.call(arrayLike, (n) => n % 2 === 0));

🖥️ Output

[ 4, 10 ]

🧠 MCQ Quiz: this, call, apply and bind

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What decides the value of this in a regular function?
  2. In user.save(), what is this inside save?
  3. In strict mode, what is this in a plain call fn()?
  4. Why does [1, 2].map(obj.method) often fail?
  5. What is the difference between call and apply?
  6. What does bind return?
  7. Can call change the this of a function created with bind?
  8. Where does an arrow function get this?
  9. What is this inside a constructor called with new?
  10. Which is a good way to keep this in a class method used as an event handler?

💼 Interview Questions and Answers

Q1. Explain how this is determined in JavaScript.

For regular functions it depends on the call: with new it is the new object; with call/apply/bind it is the given object; called as obj.method() it is obj; called as a plain function it is undefined in strict mode (global object in sloppy mode). Arrow functions have no own this and use the this of the enclosing scope. Class bodies and ES modules are strict.

Q2. What is the difference between call, apply and bind?

call(thisArg, a, b) and apply(thisArg, [a, b]) invoke the function immediately with a chosen this; they differ only in how arguments are passed. bind(thisArg, ...preset) returns a new function with this (and optionally leading arguments) permanently fixed, to be called later, typically as a callback.

Q3. Predict the output.

📄 predict.js

"use strict";
const counter = {
  value: 10,
  get() { return this?.value; },
};
const { get } = counter;
console.log(counter.get(), get(), get.call({ value: 99 }), get.bind(counter)());

⌨️ Terminal

node predict.js

🖥️ Output

10 undefined 99 10

counter.get() is a method call (10). Destructuring copies the function out, so get() is a plain strict-mode call where this is undefined (the ?. avoids a crash and gives undefined). call supplies { value: 99 }, and bind(counter) restores 10.

Q4. How do you fix “Cannot read properties of undefined” inside a class method used as a callback?

The method was called without its instance. Options: wrap the call in an arrow function (items.forEach((i) => this.process(i))), bind it (this.process = this.process.bind(this) in the constructor), or define it as an arrow-function class field (process = (i) => {...}). Choose one convention per project.


❓ Frequently Asked Questions

🤔 What is this in the global scope?

In a browser classic script it is window. In an ES module it is undefined. In a Node.js CommonJS file it is module.exports (an empty object by default).

🤔 Can I change this in an arrow function with call or bind?

No. Arrow functions ignore the thisArg of call, apply and bind, because they have no this of their own.

🤔 Is bind still needed with arrow functions available?

Less often. Arrow functions solve most callback cases, but bind is still useful for partial application and for passing existing methods as callbacks.

🤔 Why does this behave differently in strict mode?

Strict mode stops plain function calls from defaulting this to the global object, so mistakes throw errors instead of silently reading or writing global properties.


🏁 Summary

  • this is set by how a regular function is called: new, explicit binding, method call, or plain call.
  • In strict code (modules, classes) a plain call has this === undefined; passing a method as a callback loses its this.
  • Arrow functions use lexical this: great for callbacks inside methods, wrong for object methods.
  • call and apply invoke a function with a chosen this; bind returns a new function with this fixed.
  • Fix lost this with an arrow wrapper, bind, or an arrow-function class field.

Next, continue with Lesson 24: Recursion.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Arrow Functions: Syntax, Implicit Return and this

Arrow functions (=>) are the short way to write a function, and they are everywhere in modern JavaScript and in every Playwright test: test("login", async ({ page }) => { ... }). In this lesson you will learn the arrow syntax in all its forms, the implicit return and its object trap, why arrow functions are perfect for callbacks, how they handle this differently, and when you should still use a regular function.

📖 What You’ll Learn: arrow function syntax, parameters with and without parentheses, implicit versus block body returns, returning object literals, arrow functions as callbacks, async arrow functions, lexical this, no arguments object, no new, differences from regular functions, and when not to use arrows.


➡️ Arrow Function Syntax

Definition: an arrow function is a compact function expression written with =>. It is always anonymous, so you usually store it in a variable or pass it directly as an argument.

📄 syntax.js

// Regular function expression
const addRegular = function (a, b) {
  return a + b;
};

// Arrow function with a block body
const addArrow = (a, b) => {
  return a + b;
};

// Arrow function with an implicit return
const add = (a, b) => a + b;

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

⌨️ Terminal

node syntax.js

🖥️ Output

5 5 5
FormExample
No parameters() => "ready"
One parameter (parentheses optional)n => n * 2 or (n) => n * 2
Several parameters(a, b) => a + b
Block body(a, b) => { const s = a + b; return s; }
Return an object(name) => ({ name, active: true })
Asyncasync (url) => await fetch(url)

💡 Tip: Prettier adds parentheses around a single parameter by default ((n) => ...). It looks consistent and makes adding a second parameter easier, so this course uses that style.


↩️ Implicit Return vs Block Body

If the part after => is an expression, its value is returned automatically (an implicit return). If it is a block in braces, you must write return yourself:

📄 implicit.js

const double = (n) => n * 2;              // implicit return
const doubleBlock = (n) => { n * 2; };     // block without return: returns undefined
const doubleFixed = (n) => { return n * 2; };

console.log(double(4), doubleBlock(4), doubleFixed(4));

⌨️ Terminal

node implicit.js

🖥️ Output

8 undefined 8

The object-literal trap

Braces after => always start a block, never an object. To return an object with an implicit return, wrap it in parentheses:

📄 object-return.js

const makeUserWrong = (name) => { name: name };      // a block with a label!
const makeUser = (name) => ({ name: name, role: "tester" });

console.log(makeUserWrong("Asha"));
console.log(makeUser("Asha"));

⌨️ Terminal

node object-return.js

🖥️ Output

undefined
{ name: 'Asha', role: 'tester' }

In the first version, name: is read as a statement label inside a block, so the function returns undefined without any error. This is one of the most common arrow function bugs.


🔁 Arrow Functions as Callbacks

Arrow functions shine when you pass a small function to another function, such as array methods, timers and event handlers:

📄 callbacks.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "search", status: "failed", ms: 1430 },
  { test: "cart", status: "passed", ms: 610 },
];

const names = results.map((r) => r.test);
const failed = results.filter((r) => r.status === "failed");
const totalMs = results.reduce((sum, r) => sum + r.ms, 0);
const sorted = [...results].sort((a, b) => a.ms - b.ms).map((r) => `${r.test}:${r.ms}`);

console.log(names);
console.log(failed.map((r) => r.test));
console.log(totalMs);
console.log(sorted);

setTimeout(() => console.log("timer done"), 0);

⌨️ Terminal

node callbacks.js

🖥️ Output

[ 'login', 'search', 'cart' ]
[ 'search' ]
2860
[ 'cart:610', 'login:820', 'search:1430' ]
timer done

Compare the same filter call written with a regular function: results.filter(function (r) { return r.status === "failed"; }). The arrow version says the same thing in a third of the space.


⏳ Async Arrow Functions

Put async before the parameters to create an async arrow function. This is exactly the form Playwright tests use:

📄 example.spec.js (Playwright, for reference)

import { test, expect } from "@playwright/test";

test("home page has a title", async ({ page }) => {
  await page.goto("https://sqatools.in/");
  await expect(page).toHaveTitle(/SQA Tools/);
});

Here async ({ page }) => { ... } is an async arrow function whose single parameter is destructured to get page. A runnable Node.js example:

📄 async-arrow.js

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const runStep = async (name, ms) => {
  await wait(ms);
  return `${name} done after ${ms} ms`;
};

const main = async () => {
  console.log(await runStep("login", 20));
  console.log(await runStep("search", 10));
};

main();

⌨️ Terminal

node async-arrow.js

🖥️ Output

login done after 20 ms
search done after 10 ms

Promises and async/await are explained fully in Module 10.


🎯 Arrow Functions and this

The biggest technical difference: an arrow function has no this of its own. It uses the this of the code around it where it was written (this is called lexical this). A regular function gets its this from how it is called.

📄 this.js

const suite = {
  name: "Checkout",
  tests: ["add item", "pay"],

  printRegular() {
    this.tests.forEach(function (t) {
      // a regular callback has its own this (not suite), so this.name is undefined
      console.log(`${this?.name} > ${t}`);
    });
  },

  printArrow() {
    this.tests.forEach((t) => {
      // the arrow uses printArrow's this, which is suite
      console.log(`${this.name} > ${t}`);
    });
  },
};

suite.printRegular();
suite.printArrow();

⌨️ Terminal

node this.js

🖥️ Output

undefined > add item
undefined > pay
Checkout > add item
Checkout > pay

This makes arrow functions ideal for callbacks inside methods. But it also means an arrow function should not be used as an object method that needs this:

📄 method.js

const page = {
  url: "/login",
  openArrow: () => `opening ${this.url}`,     // this is not page here
  open() {
    return `opening ${this.url}`;             // method shorthand: this is page
  },
};

console.log(page.openArrow());
console.log(page.open());

⌨️ Terminal

node method.js

🖥️ Output

opening undefined
opening /login

In the arrow version, this comes from the surrounding module code, where it does not refer to page, so this.url is undefined. The this, call, apply and bind lesson explains the rules in full.


⚖️ Arrow vs Regular Functions

FeatureRegular functionArrow function
Syntaxfunction (a) { return a; }(a) => a
Own thisYes (depends on the call)No (lexical)
arguments objectYesNo
Can be used with newYesNo (TypeError)
Hoisted (declaration form)YesNo
Implicit returnNoYes, for expression bodies

📄 differences.js

function regular() {
  return arguments.length;
}
const arrow = (...args) => args.length;   // use rest parameters instead of arguments

console.log(regular(1, 2, 3), arrow(1, 2, 3));

const Person = (name) => { this.name = name; };
try {
  new Person("Asha");
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node differences.js

🖥️ Output

3 3
TypeError: Person is not a constructor

🚫 When Not to Use Arrow Functions

  • Object methods that use this: use method shorthand open() { ... }.
  • Constructors: use a class (arrows cannot be called with new).
  • DOM event handlers that rely on this being the element: use a regular function, or read event.currentTarget.
  • Top-level named helpers you want to call before their definition: a function declaration is hoisted and appears with its name in stack traces.

Everywhere else, especially short callbacks, arrow functions are the modern default.


🧪 Tester Scenario: Build a Mini Report with Arrow Functions

📄 report.js

const runs = [
  { suite: "smoke", passed: 12, failed: 0, ms: 41000 },
  { suite: "cart", passed: 18, failed: 2, ms: 98000 },
  { suite: "api", passed: 40, failed: 1, ms: 22000 },
];

const total = (r) => r.passed + r.failed;
const rate = (r) => ((r.passed / total(r)) * 100).toFixed(1) + "%";
const seconds = (ms) => (ms / 1000).toFixed(0) + "s";
const icon = (r) => (r.failed === 0 ? "✅" : "❌");

const lines = runs
  .map((r) => `${icon(r)} ${r.suite.padEnd(6)} ${rate(r).padStart(6)}  ${seconds(r.ms)}`)
  .join("\n");

console.log(lines);
console.log("suites with failures:", runs.filter((r) => r.failed > 0).map((r) => r.suite).join(", "));

⌨️ Terminal

node report.js

🖥️ Output

✅ smoke  100.0%  41s
❌ cart    90.0%  98s
❌ api     97.6%  22s
suites with failures: cart, api

Each arrow function does one small, named job, and map/filter combine them. This style is common in custom Playwright reporters and CI summary scripts.


📝 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. Rewrite as an arrow function with an implicit return.

function square(n) {
  return n * n;
}
Show answer

📄 practice1.js

const square = (n) => n * n;
console.log(square(9));

🖥️ Output

81

Q2. Write an arrow function toUser(name, email) that returns { name, email, active: true } using an implicit return.

Show answer

📄 practice2.js

const toUser = (name, email) => ({ name, email, active: true });
console.log(toUser("Asha", "asha@sqatools.in"));

🖥️ Output

{ name: 'Asha', email: 'asha@sqatools.in', active: true }

The parentheses around the object are required; { name, email } is shorthand for { name: name, email: email }.

Q3. Use map with an arrow function to convert [10, 25, 40] rupee prices to strings like "₹10.00".

Show answer

📄 practice3.js

const prices = [10, 25, 40];
console.log(prices.map((p) => `₹${p.toFixed(2)}`));

🖥️ Output

[ '₹10.00', '₹25.00', '₹40.00' ]

Q4. Find the bug: this function returns undefined.

const isAdult = (age) => {
  age >= 18;
};
Show answer

The braces create a block body, so the comparison is calculated but not returned. Remove the braces or add return:

📄 practice4.js

const isAdult = (age) => age >= 18;
console.log(isAdult(20), isAdult(15));

🖥️ Output

true false

Q5. Use filter and map with arrow functions to get the names of tests slower than 1000 ms from [{ name: "a", ms: 400 }, { name: "b", ms: 1500 }, { name: "c", ms: 2200 }].

Show answer

📄 practice5.js

const tests = [{ name: "a", ms: 400 }, { name: "b", ms: 1500 }, { name: "c", ms: 2200 }];
const slow = tests.filter((t) => t.ms > 1000).map((t) => t.name);
console.log(slow);

🖥️ Output

[ 'b', 'c' ]

Q6. This object method prints undefined. Fix it so it prints Base URL: https://qa.example.com.

const env = {
  baseURL: "https://qa.example.com",
  show: () => console.log("Base URL: " + this.baseURL),
};
env.show();
Show answer

Arrow functions do not get this from the object. Use method shorthand:

📄 practice6.js

const env = {
  baseURL: "https://qa.example.com",
  show() {
    console.log("Base URL: " + this.baseURL);
  },
};
env.show();

🖥️ Output

Base URL: https://qa.example.com

🧠 MCQ Quiz: Arrow 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.

  1. What does const f = (n) => n + 1; return for f(4)?
  2. What does const f = (n) => { n + 1; }; return for f(4)?
  3. How do you return an object literal with an implicit return?
  4. Where does an arrow function get its this?
  5. What happens with new ((x) => x)()?
  6. Which is valid arrow syntax for a function with no parameters?
  7. Do arrow functions have an arguments object?
  8. Why is an arrow function a poor choice for an object method that uses this?
  9. Which signature is used for a Playwright test body?
  10. Why are arrow functions good callbacks inside class methods?

💼 Interview Questions and Answers

Q1. What are the differences between arrow functions and regular functions?

  • Arrow functions have lexical this; regular functions get this from the call site.
  • Arrow functions have no arguments object, no prototype, and cannot be called with new.
  • Arrow functions support an implicit return for expression bodies.
  • Arrow functions are always expressions, so they are not hoisted like function declarations.

Q2. Explain this output.

📄 counter.js

const counter = {
  count: 0,
  incArrow: () => { this.count++; return this.count; },
  inc() { this.count++; return this.count; },
};

console.log(counter.inc(), counter.inc());
console.log(counter.incArrow());
console.log(counter.count);

⌨️ Terminal

node counter.js

🖥️ Output

1 2
NaN
2

inc is a method, so this is counter and the count goes 1, 2. incArrow takes this from the module scope, where it is an empty object (module.exports in CommonJS), so this.count++ works on undefined and gives NaN, while counter.count stays 2.

Q3. Why does items.map(i => { id: i }) produce an array of undefined?

The braces are parsed as a function body, and id: as a label before the expression i. The body has no return, so every call returns undefined. Wrap the object in parentheses: items.map((i) => ({ id: i })).

Q4. When would you still use a regular function instead of an arrow function?

For object methods and class methods that use this (method syntax), for constructors (use class), for DOM handlers that rely on this being the element, for generator functions (function*, which have no arrow form), and for named top-level functions where hoisting and clear stack-trace names help.


❓ Frequently Asked Questions

🤔 When were arrow functions added to JavaScript?

In ES2015 (ES6). They work in every modern browser and every supported Node.js version.

🤔 Are arrow functions faster than regular functions?

Not in a way that matters. Choose them for brevity and lexical this, not for speed.

🤔 Can arrow functions be async?

Yes: const load = async () => { await ... }. This is the form used for Playwright test bodies and hooks.

🤔 Should single parameters have parentheses?

It is optional (n => n * 2 is valid). Many teams, and Prettier by default, always add them for consistency.


🏁 Summary

  • Arrow functions use (params) => expression or (params) => { statements }.
  • An expression body returns its value implicitly; a block body needs return; wrap returned objects in parentheses.
  • Arrow functions are ideal for callbacks (map, filter, timers) and async test bodies.
  • They have lexical this, no arguments, and cannot be used with new.
  • Use method shorthand for object methods that need this, and classes for constructors.

Next, continue with Lesson 19: Default, Rest and Spread Parameters.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Function Parameters: Default, Rest, Spread and Options Objects

Real functions need flexible input: an optional timeout, any number of tags, or a configuration with ten settings where you only change two. Modern JavaScript gives you default parameters, rest parameters, spread arguments and destructured options objects for exactly these cases, and Playwright’s own API uses all of them. In this lesson you will learn each one, how they interact with undefined and null, and how to validate parameters so bad input fails with a clear message.

📖 What You’ll Learn: default parameter values and when they apply, defaults that use earlier parameters, rest parameters, the legacy arguments object, spreading arrays into arguments, the options-object pattern with destructuring and defaults, required parameters and validation, and function length.


🎛️ Default Parameters

Definition: a default parameter gives a parameter a value to use when the caller does not pass one (or passes undefined). Write it with = in the parameter list.

📄 defaults.js

function greet(name = "guest", greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

console.log(greet());
console.log(greet("Asha"));
console.log(greet("Asha", "Welcome back"));
console.log(greet(undefined, "Hi"));   // undefined triggers the default
console.log(greet(null));             // null does NOT trigger it

⌨️ Terminal

node defaults.js

🖥️ Output

Hello, guest!
Hello, Asha!
Welcome back, Asha!
Hi, guest!
Hello, null!

⚠️ Watch out: Defaults apply only to undefined. If an API or form gives you null or an empty string, the default is not used. Normalise such values first, for example with value ?? fallback.

Before ES2015, people wrote name = name || "guest" inside the function. That also replaced 0, "" and false, which is why default parameters are safer.


🔗 Defaults That Use Other Parameters or Expressions

A default can be any expression. It is evaluated each time the function is called without that argument, and it can use parameters listed before it:

📄 default-expr.js

function createRun(suite, startedAt = new Date().toISOString().slice(0, 10), id = `${suite}-${startedAt}`) {
  return { suite, startedAt, id };
}

console.log(createRun("smoke", "2026-11-23"));
console.log(createRun("smoke", "2026-11-23", "custom-id"));

function addTag(tag, list = []) {   // a fresh array on every call
  list.push(tag);
  return list;
}
console.log(addTag("ui"), addTag("api"));

⌨️ Terminal

node default-expr.js

🖥️ Output

{ suite: 'smoke', startedAt: '2026-11-23', id: 'smoke-2026-11-23' }
{ suite: 'smoke', startedAt: '2026-11-23', id: 'custom-id' }
[ 'ui' ] [ 'api' ]

💡 Tip: Because the default [] is created again on every call, the two addTag calls do not share an array. (Python developers will know this is different in Python.)


🧺 Rest Parameters (…args)

Definition: a rest parameter, written ...name, collects all remaining arguments into a real array. It must be the last parameter.

📄 rest.js

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(), sum(5), sum(1, 2, 3, 4));

function logStep(level, ...messages) {
  console.log(`[${level.toUpperCase()}]`, messages.join(" "));
}

logStep("info", "Opening", "login", "page");
logStep("warn", "Retrying", "attempt", 2);

⌨️ Terminal

node rest.js

🖥️ Output

0 5 10
[INFO] Opening login page
[WARN] Retrying attempt 2

Putting the rest parameter anywhere but last is a syntax error:

📄 rest-error.js

function bad(...items, last) {
  return items;
}

⌨️ Terminal

node rest-error.js

🖥️ Output

/home/you/js-course/rest-error.js:1
function bad(...items, last) {
                     ^

SyntaxError: Rest parameter must be last formal parameter

Node.js v26.13.0

📜 The arguments Object (Legacy)

Regular functions also have a built-in arguments object containing every argument. It is array-like (it has length and indexes) but it is not an array, and arrow functions do not have it.

📄 arguments.js

function legacySum() {
  console.log(arguments.length, Array.isArray(arguments));
  let total = 0;
  for (let i = 0; i < arguments.length; i++) total += arguments[i];
  return total;
}
console.log(legacySum(2, 4, 6));

const modernSum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(modernSum(2, 4, 6));

⌨️ Terminal

node arguments.js

🖥️ Output

3 false
12
12

You will meet arguments in older code. In new code, always use rest parameters.


🌊 Spread Arguments

Spread is the opposite of rest: ...array in a function call expands an array into separate arguments.

📄 spread.js

const responseTimes = [320, 1290, 450, 980];

console.log(Math.max(responseTimes));      // an array is one argument: NaN
console.log(Math.max(...responseTimes));   // spread into four arguments

function fullName(first, last) {
  return `${first} ${last}`;
}
const parts = ["Asha", "Rao"];
console.log(fullName(...parts));

console.log(Math.min(0, ...responseTimes, 2000));   // mix with other arguments

⌨️ Terminal

node spread.js

🖥️ Output

NaN
1290
Asha Rao
0
SyntaxWhereWhat it does
function f(...args)Parameter listRest: collects arguments into an array
f(...arr)Function callSpread: expands an array into arguments
[...a, ...b], { ...obj }Array/object literalsSpread: copies items or properties

🧰 The Options Object Pattern

Long parameter lists are hard to read: in launch("chromium", true, 3, 30000, false), what does 3 mean? The options object pattern passes one object with named properties instead. Destructuring with defaults unpacks it in the parameter list:

📄 options.js

function launch({ browser = "chromium", headless = true, retries = 0, timeout = 30000 } = {}) {
  return `${browser} headless=${headless} retries=${retries} timeout=${timeout}`;
}

console.log(launch());
console.log(launch({ retries: 2 }));
console.log(launch({ browser: "firefox", headless: false }));

⌨️ Terminal

node options.js

🖥️ Output

chromium headless=true retries=0 timeout=30000
chromium headless=true retries=2 timeout=30000
firefox headless=false retries=0 timeout=30000
  • The call sites are self-documenting: { retries: 2 } says what 2 means.
  • Callers pass only the options they want to change, in any order.
  • The = {} at the end lets you call launch() with no argument at all. Without it, destructuring undefined throws a TypeError.

📄 options-error.js

function launchNoDefault({ browser = "chromium" }) {
  return browser;
}
console.log(launchNoDefault({}));
console.log(launchNoDefault());

⌨️ Terminal

node options-error.js

🖥️ Output

chromium
/home/you/js-course/options-error.js:1
function launchNoDefault({ browser = "chromium" }) {
                           ^

TypeError: Cannot read properties of undefined (reading 'browser')
    at launchNoDefault (/home/you/js-course/options-error.js:1:28)
    at Object.<anonymous> (/home/you/js-course/options-error.js:5:13)

Node.js v26.13.0

Playwright uses this pattern everywhere, for example page.click(selector, { timeout: 5000 }) and page.screenshot({ path: "home.png", fullPage: true }).


✅ Required Parameters and Validation

JavaScript does not enforce required parameters. Validate important inputs at the start of the function and throw a clear error:

📄 validate.js

function required(name) {
  throw new Error(`Missing required parameter: ${name}`);
}

function createUser(email = required("email"), role = "tester") {
  if (typeof email !== "string" || !email.includes("@")) {
    throw new TypeError(`Invalid email: ${JSON.stringify(email)}`);
  }
  return { email, role };
}

console.log(createUser("qa@sqatools.in"));
for (const bad of [undefined, 42, "no-at-sign"]) {
  try {
    createUser(bad);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

⌨️ Terminal

node validate.js

🖥️ Output

{ email: 'qa@sqatools.in', role: 'tester' }
Error: Missing required parameter: email
TypeError: Invalid email: 42
TypeError: Invalid email: "no-at-sign"

email = required("email") uses a default expression that throws: it runs only when the argument is missing.

💡 Tip: TypeScript or JSDoc types catch many parameter mistakes before the code runs. In plain JavaScript, validating at the boundary (public helpers, API clients) gives fast, readable failures.


📏 Function length

A function’s length property is the number of parameters declared before the first default or rest parameter. Some libraries use it to decide how to call a function.

📄 length.js

function a(x, y) {}
function b(x, y = 1) {}
function c(...rest) {}
const d = ({ timeout } = {}) => {};

console.log(a.length, b.length, c.length, d.length);

⌨️ Terminal

node length.js

🖥️ Output

2 1 0 0

🧪 Tester Scenario: A Flexible API Request Helper

📄 request.js

function buildRequest(path, { method = "GET", headers = {}, body, retries = 1, ...extra } = {}) {
  if (!path.startsWith("/")) throw new Error(`Path must start with "/": ${path}`);
  return {
    url: `https://api.example.com${path}`,
    method,
    headers: { "content-type": "application/json", ...headers },
    body: body === undefined ? undefined : JSON.stringify(body),
    retries,
    extra,
  };
}

console.log(buildRequest("/users"));
console.log(buildRequest("/users", {
  method: "POST",
  body: { name: "Asha" },
  headers: { authorization: "Bearer test-token" },
  timeout: 5000,
}));

⌨️ Terminal

node request.js

🖥️ Output

{
  url: 'https://api.example.com/users',
  method: 'GET',
  headers: { 'content-type': 'application/json' },
  body: undefined,
  retries: 1,
  extra: {}
}
{
  url: 'https://api.example.com/users',
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer test-token'
  },
  body: '{"name":"Asha"}',
  retries: 1,
  extra: { timeout: 5000 }
}
  • The options object is destructured with defaults, and ...extra collects any options the helper does not know about (here timeout), so they are not silently lost.
  • { "content-type": "application/json", ...headers } merges caller headers over the default header.
  • The path check is a guard clause that turns a common mistake into a clear error.

📝 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 power(base, exponent = 2) and print power(5) and power(2, 10).

Show answer

📄 practice1.js

function power(base, exponent = 2) {
  return base ** exponent;
}
console.log(power(5), power(2, 10));

🖥️ Output

25 1024

Q2. Write average(...numbers) that returns the average of any number of arguments, or 0 when called with none.

Show answer

📄 practice2.js

function average(...numbers) {
  if (numbers.length === 0) return 0;
  return numbers.reduce((a, b) => a + b, 0) / numbers.length;
}
console.log(average(), average(10), average(2, 4, 9));

🖥️ Output

0 10 5

Q3. Print the largest and smallest value of [17, 3, 99, 42] with Math.max and Math.min using spread.

Show answer

📄 practice3.js

const values = [17, 3, 99, 42];
console.log(Math.max(...values), Math.min(...values));

🖥️ Output

99 3

Q4. Predict the output, then run it.

function f(a = 1, b = a + 1) {
  return [a, b];
}
console.log(f(), f(5), f(5, 0), f(undefined, 9), f(null));
Show answer

📄 practice4.js

function f(a = 1, b = a + 1) {
  return [a, b];
}
console.log(f(), f(5), f(5, 0), f(undefined, 9), f(null));

🖥️ Output

[ 1, 2 ] [ 5, 6 ] [ 5, 0 ] [ 1, 9 ] [ null, 1 ]

Defaults apply only to undefined. With f(null), a is null and b = null + 1 = 1.

Q5. Rewrite screenshot(name, fullPage, type, quality) as a function that takes an options object with defaults fullPage: false, type: "png", quality: 80, and returns a summary string.

Show answer

📄 practice5.js

function screenshot(name, { fullPage = false, type = "png", quality = 80 } = {}) {
  return `${name}.${type} fullPage=${fullPage} quality=${quality}`;
}

console.log(screenshot("home"));
console.log(screenshot("checkout", { fullPage: true, type: "jpeg" }));

🖥️ Output

home.png fullPage=false quality=80
checkout.jpeg fullPage=true quality=80

Q6. Write joinPath(...segments) that joins any number of URL segments with /, removing extra slashes at the ends of each segment.

Show answer

📄 practice6.js

function joinPath(...segments) {
  return segments
    .map((s) => String(s).replace(/^\/+|\/+$/g, ""))
    .filter((s) => s.length > 0)
    .join("/");
}

console.log(joinPath("https://api.example.com/", "/v1/", "users", 42));

🖥️ Output

https://api.example.com/v1/users/42

🧠 MCQ Quiz: Default, Rest and Spread Parameters

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. When is a default parameter value used?
  2. What does ((x = 5) => x)(null) return?
  3. What does a rest parameter collect its values into?
  4. Where must a rest parameter appear?
  5. What does Math.max(...[3, 9, 4]) return?
  6. Which functions have an arguments object?
  7. Why add = {} after a destructured options parameter?
  8. What is (function (a, b = 2, c) {}).length?
  9. What is the main benefit of the options object pattern?
  10. Is a default parameter expression evaluated once or on every call?

💼 Interview Questions and Answers

Q1. What is the difference between rest and spread?

They use the same ... syntax for opposite jobs. Rest appears in a parameter list or destructuring pattern and gathers several values into one array (or object). Spread appears in a call or an array/object literal and expands one array (or object) into separate items. function f(...args) {} is rest; f(...list) is spread.

Q2. Why are default parameters better than x = x || defaultValue?

|| replaces every falsy value, so legitimate inputs such as 0, "" and false become the default (a timeout of 0 or headless: false would be lost). Default parameters apply only to undefined, they are visible in the function signature, and they can be expressions using earlier parameters.

Q3. How do you implement a required parameter in JavaScript?

Either validate inside the function (if (email === undefined) throw new Error(...)), or use a default expression that throws, function f(email = required("email")), which only runs when the argument is missing. In TypeScript, parameters are required unless marked optional, so the compiler enforces it.

Q4. Explain this code and its output.

📄 connect.js

function connect({ host = "localhost", port = 5432 } = {}, ...flags) {
  return `${host}:${port} ${flags.join(",") || "no flags"}`;
}
console.log(connect());
console.log(connect({ port: 6543 }, "ssl", "readonly"));

⌨️ Terminal

node connect.js

🖥️ Output

localhost:5432 no flags
localhost:6543 ssl,readonly

The first parameter destructures an options object with defaults and falls back to {} when missing. ...flags collects any extra arguments into an array. With no flags, flags.join(",") is an empty string, so || "no flags" supplies the text.


❓ Frequently Asked Questions

🤔 Can a default parameter refer to another parameter?

Yes, to parameters declared before it: function f(a, b = a * 2). Referring to a later parameter throws a ReferenceError.

🤔 Is arguments deprecated?

Not removed, but discouraged. Rest parameters give a real array, work in arrow functions and make the signature clearer.

🤔 How do I make a parameter optional in JavaScript?

Every parameter is optional; a missing one is undefined. Give it a default value or handle undefined explicitly.

🤔 How many parameters can a JavaScript function have?

There is no practical limit, but more than three positional parameters is hard to read. Switch to an options object.


🏁 Summary

  • Default parameters (x = 5) apply only when the argument is undefined, and are evaluated on every call.
  • Rest parameters (...args) collect remaining arguments into an array and must come last.
  • Spread (f(...arr)) expands an array into separate arguments.
  • The options object pattern with destructuring and = {} gives named, optional, order-free arguments.
  • Validate required parameters early and throw clear errors.

Next, continue with Lesson 20: Scope and Hoisting.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Scope and Hoisting: Global, Function, Block and Lexical Scope

Every variable lives somewhere. Scope decides where a name can be used, and hoisting decides what happens when you use a name before the line that declares it. Together they explain many confusing bugs: a variable that is “not defined” inside a callback, a value that changes when it should not, or undefined appearing out of nowhere. In this lesson you will learn every kind of scope, how JavaScript looks names up through the scope chain, and exactly what is hoisted and what is not.

📖 What You’ll Learn: what scope is, global, module, function and block scope, the scope chain and lexical scope, shadowing, how hoisting works for var, let, const, function declarations, function expressions and classes, the temporal dead zone, and how to avoid scope bugs in tests.


🗺️ What Is Scope?

Definition: the scope of a variable is the region of code where that variable can be accessed. Outside its scope the name does not exist, and using it throws a ReferenceError.

ScopeCreated byApplies to
GlobalThe top level of a browser classic scriptvar, let, const, functions
ModuleEach ES module or Node.js fileEverything declared at the top of that file
FunctionEvery functionvar, let, const, parameters, inner functions
BlockAny { }: if, for, while, plain blockslet, const, class (not var)

Scopes are nested: a block inside a function inside a module. Inner code can see outer variables, but outer code cannot see inner variables.


🌍 Global and Module Scope

In a browser classic <script>, top-level variables are global: every other script on the page can read and change them. In Node.js and in ES modules, each file has its own module scope, so top-level variables are private to that file unless you export them.

📄 module-scope.js

const BASE_URL = "https://sqatools.in";   // module scope: visible everywhere in this file

function loginUrl() {
  return `${BASE_URL}/login`;              // inner code can read outer variables
}

console.log(loginUrl());
console.log(typeof globalThis.BASE_URL);   // not a property of the global object
console.log(typeof globalThis.console);    // built-ins are truly global

⌨️ Terminal

node module-scope.js

🖥️ Output

https://sqatools.in/login
undefined
object

⚠️ Watch out: Assigning to an undeclared name in sloppy mode creates an accidental global (see the Syntax lesson). Strict mode and ES modules turn that into a ReferenceError.


🏠 Function Scope

Variables declared inside a function, including its parameters, exist only while that function runs and only inside it:

📄 function-scope.js

function checkout(cartTotal) {
  const tax = cartTotal * 0.18;
  var shipping = 50;
  return cartTotal + tax + shipping;
}

console.log(checkout(1000));
console.log(typeof tax, typeof shipping, typeof cartTotal);
console.log(tax);

⌨️ Terminal

node function-scope.js

🖥️ Output

1230
undefined undefined undefined
/home/you/js-course/function-scope.js:9
console.log(tax);
            ^

ReferenceError: tax is not defined
    at Object.<anonymous> (/home/you/js-course/function-scope.js:9:13)

Node.js v26.13.0

typeof is safe to use on unknown names and returns "undefined"; using the name directly throws. Each call also gets a fresh set of local variables, so two calls never share their locals.


🧱 Block Scope

let, const and class are scoped to the nearest block { }. var ignores blocks and belongs to the whole function (or file).

📄 block-scope.js

function report(results) {
  for (let i = 0; i < results.length; i++) {
    const line = `${i + 1}. ${results[i]}`;
    var lastLine = line;
    console.log(line);
  }
  console.log("after loop, lastLine:", lastLine);   // var leaked out of the block
  console.log("i is", typeof i, "- line is", typeof line);
}

report(["login passed", "search failed"]);

⌨️ Terminal

node block-scope.js

🖥️ Output

1. login passed
2. search failed
after loop, lastLine: 2. search failed
i is undefined - line is undefined

You can also create a plain block just to limit a variable’s lifetime:

📄 plain-block.js

{
  const temp = "only needed here";
  console.log(temp);
}
console.log(typeof temp);

⌨️ Terminal

node plain-block.js

🖥️ Output

only needed here
undefined

🔍 The Scope Chain and Lexical Scope

Definition: when JavaScript looks up a name, it searches the current scope first, then the enclosing scope, and so on outwards until the module or global scope. This chain of nested scopes is the scope chain. If the name is not found anywhere, you get a ReferenceError.

Lexical scope means the chain is decided by where the code is written, not by where a function is called from:

📄 lexical.js

const env = "module";

function outer() {
  const env = "outer";
  function inner() {
    return `inner sees ${env}`;       // looks up: inner -> outer (found)
  }
  return inner;
}

function caller() {
  const env = "caller";
  const fn = outer();
  return fn();                        // called from caller, but scope comes from where inner was written
}

console.log(caller());

⌨️ Terminal

node lexical.js

🖥️ Output

inner sees outer

The result is inner sees outer, not caller. This rule is what makes closures work, which is the subject of the next lesson.


🎭 Shadowing

Definition: shadowing happens when an inner scope declares a variable with the same name as an outer one. Inside the inner scope, the inner variable hides the outer one.

📄 shadowing.js

const status = "global status";

function runTest() {
  const status = "test status";       // shadows the outer status
  if (true) {
    const status = "block status";    // shadows again
    console.log(status);
  }
  console.log(status);
}

runTest();
console.log(status);

⌨️ Terminal

node shadowing.js

🖥️ Output

block status
test status
global status

💡 Tip: Shadowing is legal but makes code harder to follow, especially with short names like data or result. ESLint’s no-shadow rule can warn you.


⬆️ Hoisting: What Is Moved to the Top?

Definition: before running a scope, JavaScript registers all declarations in it. This is hoisting. What you can do before the declaration line depends on the kind of declaration:

DeclarationHoisted?Value before its line
function f() {}Yes, with bodyThe function: callable
var xYesundefined
let x / const xYes, but uninitialisedReferenceError (TDZ)
class C {}Yes, but uninitialisedReferenceError (TDZ)
const f = function () {} / arrowLike its constReferenceError (TDZ)
var f = function () {}Like its varundefined: calling it is a TypeError

📄 hoisting.js

console.log(add(2, 3));          // function declaration: works
console.log(typeof legacy);      // var: undefined, not an error

function add(a, b) {
  return a + b;
}
var legacy = "set later";

try {
  multiply(2, 3);                // var holding a function expression
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}
var multiply = function (a, b) {
  return a * b;
};

try {
  new Report();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}
class Report {}

⌨️ Terminal

node hoisting.js

🖥️ Output

5
undefined
TypeError: multiply is not a function
ReferenceError: Cannot access 'Report' before initialization

The temporal dead zone (TDZ) can appear inside a scope

A let in an inner scope hides the outer variable for the whole inner scope, even before its declaration line:

📄 tdz-shadow.js

const user = "outer user";

function show() {
  console.log(user);     // refers to the inner user, which is still in the TDZ
  const user = "inner user";
}

show();

⌨️ Terminal

node tdz-shadow.js

🖥️ Output

/home/you/js-course/tdz-shadow.js:4
  console.log(user);     // refers to the inner user, which is still in the TDZ
              ^

ReferenceError: Cannot access 'user' before initialization
    at show (/home/you/js-course/tdz-shadow.js:4:15)
    at Object.<anonymous> (/home/you/js-course/tdz-shadow.js:8:1)

Node.js v26.13.0

Many people expect this to print outer user. Because the inner user is hoisted to the top of show, the name already refers to it, and it is not initialised yet.


🧪 Tester Scenario: Avoid Shared State Between Tests

A test file often has variables at module scope. If tests change them, the result depends on test order, which is a classic source of flaky tests. This simulation runs two “tests” in different orders:

📄 shared-state.js

// Shared, mutable module-level state (bad)
let cart = [];

const tests = {
  "adds item": () => { cart.push("pen"); return cart.length === 1; },
  "cart starts empty": () => cart.length === 0,
};

function runInOrder(order) {
  cart = [];
  return order.map((name) => `${name}: ${tests[name]() ? "PASS" : "FAIL"}`).join(", ");
}

console.log("order A:", runInOrder(["cart starts empty", "adds item"]));
console.log("order B:", runInOrder(["adds item", "cart starts empty"]));

// Fixed: each test creates its own state in its own function scope
const isolated = {
  "adds item": () => { const cart = []; cart.push("pen"); return cart.length === 1; },
  "cart starts empty": () => { const cart = []; return cart.length === 0; },
};
console.log("isolated:", Object.entries(isolated).map(([n, t]) => `${n}: ${t() ? "PASS" : "FAIL"}`).join(", "));

⌨️ Terminal

node shared-state.js

🖥️ Output

order A: cart starts empty: PASS, adds item: PASS
order B: adds item: PASS, cart starts empty: FAIL
isolated: adds item: PASS, cart starts empty: PASS

In Playwright, beforeEach hooks and fixtures give each test fresh state for the same reason, and they matter even more when tests run in parallel.


📝 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. Predict what each console.log prints, then run the code.

let a = 1;
function f() {
  let a = 2;
  {
    let a = 3;
    console.log(a);
  }
  console.log(a);
}
f();
console.log(a);
Show answer

📄 practice1.js

let a = 1;
function f() {
  let a = 2;
  {
    let a = 3;
    console.log(a);
  }
  console.log(a);
}
f();
console.log(a);

🖥️ Output

3
2
1

Each block declares its own a, shadowing the outer one only inside that block.

Q2. Explain why this prints undefined instead of throwing an error.

console.log(total);
var total = 100;
Show answer

📄 practice2.js

console.log(total);
var total = 100;

🖥️ Output

undefined

var total is hoisted to the top of the scope and initialised with undefined. Only the assignment = 100 stays on its line. With let or const it would be a ReferenceError (TDZ).

Q3. Write a function counterReport() that declares a counter inside a for loop block with let, and show that the counter is not available after the loop.

Show answer

📄 practice3.js

function counterReport() {
  for (let i = 0; i < 3; i++) {
    // i only exists in this loop
  }
  return typeof i;
}
console.log(counterReport());

🖥️ Output

undefined

Q4. Fix this code so it prints QA then DEV without renaming the outer variable.

const team = "QA";
function show() {
  console.log(team);
  const team = "DEV";
  console.log(team);
}
show();
Show answer

The inner team is in the temporal dead zone at the first log. Give the inner variable a different name:

📄 practice4.js

const team = "QA";
function show() {
  console.log(team);
  const otherTeam = "DEV";
  console.log(otherTeam);
}
show();

🖥️ Output

QA
DEV

Q5. Which function can be called before its definition: function a() {}, const b = () => {}, var c = function () {}? Prove it with typeof before the definitions.

Show answer

📄 practice5.js

console.log(typeof a);   // "function": hoisted with body
console.log(typeof c);   // "undefined": var hoisted, value not yet assigned
try {
  console.log(typeof b); // b is in the TDZ
} catch (e) {
  console.log(e.message);
}

function a() {}
const b = () => {};
var c = function () {};

🖥️ Output

function
undefined
Cannot access 'b' before initialization

Even typeof throws for a name in the TDZ. Only a can be called before its definition.

Q6. Rewrite this so each call to createCounter has its own count instead of sharing a module-level one.

let count = 0;
function createCounter() {
  return () => ++count;
}
Show answer

📄 practice6.js

function createCounter() {
  let count = 0;            // each call creates a new count
  return () => ++count;
}

const a = createCounter();
const b = createCounter();
console.log(a(), a(), b());

🖥️ Output

1 2 1

This is a closure, explained in detail in the next lesson.


🧠 MCQ Quiz: Scope and Hoisting

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which keywords are block-scoped?
  2. How is the scope of a variable decided in JavaScript?
  3. What does typeof undeclaredName return?
  4. What is printed?
    console.log(x);
    var x = 7;
  5. Which can be called before its line?
  6. What is shadowing?
  7. In Node.js, is a top-level const in one file visible in another file?
  8. What happens when a variable is not found anywhere in the scope chain?
  9. What is printed?
    let v = 1;
    { let v = 2; }
    console.log(v);
  10. Why can shared module-level variables cause flaky tests?

💼 Interview Questions and Answers

Q1. What is the difference between function scope and block scope?

Function scope means a variable is visible throughout the function in which it is declared; var works this way and ignores if/for blocks. Block scope means a variable is visible only inside the nearest { }; let, const and class work this way. Block scope keeps variables short-lived and prevents leaks such as a loop counter being visible after the loop.

Q2. What is hoisting? Is let hoisted?

Hoisting is the creation of all declarations in a scope before any code in that scope runs. Function declarations are hoisted with their body; var is hoisted and initialised to undefined; let, const and class are hoisted but left uninitialised, so accessing them before the declaration throws a ReferenceError (temporal dead zone). So yes, let is hoisted, just not initialised.

Q3. What is lexical scope and the scope chain?

Lexical scope means the set of variables a piece of code can access is determined by its position in the source code. When a name is used, the engine looks in the current scope, then each enclosing scope outward, up to the module and global scope: that path is the scope chain. Where a function is called from does not matter.

Q4. Predict the output.

📄 predict.js

var x = "global";
function test() {
  console.log(x);
  var x = "local";
  console.log(x);
}
test();

⌨️ Terminal

node predict.js

🖥️ Output

undefined
local

The inner var x is hoisted to the top of test and shadows the outer x, so the first log prints undefined, not "global". The second prints "local".


❓ Frequently Asked Questions

🤔 What are the types of scope in JavaScript?

Global scope, module scope (per file in Node.js and ES modules), function scope and block scope. Closures let inner functions keep access to outer scopes.

🤔 Are function expressions hoisted?

Only the variable that holds them is hoisted, following var, let or const rules. The function itself is created when that line runs.

🤔 Why does let give “Cannot access before initialization” instead of “not defined”?

Because the name exists (it was hoisted) but is in the temporal dead zone. “Not defined” means the name does not exist in any reachable scope.

🤔 Is it bad to use global variables?

In browser pages and test suites, yes, mostly. Globals can be changed from anywhere, which causes hard-to-find bugs and order-dependent tests. Keep variables in the smallest scope that works.


🏁 Summary

  • Scope is where a name can be used: global, module, function and block scope.
  • let/const/class are block-scoped; var is function-scoped.
  • Name lookup follows the lexical scope chain from inner to outer scopes; inner names can shadow outer ones.
  • Function declarations are hoisted with their body; var is hoisted as undefined; let/const/class are in the TDZ until declared.
  • Keep test state in the smallest scope (inside each test or fixture) to avoid order-dependent failures.

Next, continue with Lesson 21: Closures.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript switch Statement: case, break, default and Fall-Through

When one value can match many fixed options, such as a browser name, an HTTP method or a test environment, a long else if chain becomes noisy. The switch statement compares one value against a list of case labels and runs the matching code. In this lesson you will learn how switch works, why break matters, how to group cases, the switch (true) pattern for ranges, and when a lookup object is the better choice.

📖 What You’ll Learn: switch syntax, case and default, strict comparison in cases, break and fall-through, grouping several cases, returning from a switch inside a function, block scope inside cases, switch (true) for ranges, switch versus if/else versus lookup objects, and a tester scenario that picks environment settings.


🔀 What Is a switch Statement?

Definition: a switch statement evaluates an expression once and compares its value with each case using strict equality (===). It runs the code of the first matching case and continues until it reaches break or the end of the switch. The optional default case runs when nothing matches.

📄 Syntax

switch (expression) {
  case value1:
    // runs when expression === value1
    break;
  case value2:
    // runs when expression === value2
    break;
  default:
    // runs when no case matches
}

📄 switch.js

const browser = "firefox";

switch (browser) {
  case "chromium":
    console.log("Engine: Blink");
    break;
  case "firefox":
    console.log("Engine: Gecko");
    break;
  case "webkit":
    console.log("Engine: WebKit");
    break;
  default:
    console.log(`Unknown browser: ${browser}`);
}

⌨️ Terminal

node switch.js

🖥️ Output

Engine: Gecko

🎯 Cases Use Strict Equality (===)

Each case is compared with ===, so the type must match. A number from a page or a command-line argument arrives as a string and will not match a numeric case:

📄 strict.js

function describe(status) {
  switch (status) {
    case 200:
      return "OK";
    case 404:
      return "Not Found";
    default:
      return `No match for ${JSON.stringify(status)} (${typeof status})`;
  }
}

console.log(describe(200));
console.log(describe("200"));          // string: no case matches
console.log(describe(Number("200")));  // convert first

⌨️ Terminal

node strict.js

🖥️ Output

OK
No match for "200" (string)
OK

⚠️ Watch out: Convert input to the right type before the switch, for example switch (Number(code)), or the default branch will run silently.


⛔ break and Fall-Through

Without break, execution falls through into the next case and runs its code as well, whether or not that case matches:

📄 fall-through.js

const level = "warn";

switch (level) {
  case "error":
    console.log("send alert");
  case "warn":
    console.log("write to log file");
  case "info":
    console.log("print to console");
}

⌨️ Terminal

node fall-through.js

🖥️ Output

write to log file
print to console

The "warn" case matched, and because there is no break, the "info" code ran too. Sometimes this is intentional, as here, where each level also does everything below it. Usually it is a bug.

💡 Tip: If you use fall-through on purpose, add a comment such as // falls through. ESLint’s no-fallthrough rule reports missing break statements unless that comment is present.


🧺 Grouping Several Cases

Empty cases that follow each other share the same code. This is the most common, and perfectly clear, use of fall-through:

📄 grouping.js

function dayType(day) {
  switch (day.toLowerCase()) {
    case "saturday":
    case "sunday":
      return "weekend";
    case "monday":
    case "tuesday":
    case "wednesday":
    case "thursday":
    case "friday":
      return "weekday";
    default:
      return "invalid day";
  }
}

for (const d of ["Sunday", "wednesday", "Funday"]) {
  console.log(d, "->", dayType(d));
}

⌨️ Terminal

node grouping.js

🖥️ Output

Sunday -> weekend
wednesday -> weekday
Funday -> invalid day

Inside a function, return leaves both the switch and the function, so no break is needed after it.


📦 Block Scope Inside Cases

All cases share one block, so declaring the same let or const name in two cases is an error:

📄 scope-bug.js

const method = "POST";
switch (method) {
  case "GET":
    const message = "reading data";
    console.log(message);
    break;
  case "POST":
    const message = "creating data";
    console.log(message);
    break;
}

⌨️ Terminal

node scope-bug.js

🖥️ Output

/home/you/js-course/scope-bug.js:8
    const message = "creating data";
          ^

SyntaxError: Identifier 'message' has already been declared

Node.js v26.13.0

Fix: wrap each case body in its own braces to give it a separate block:

📄 scope-fixed.js

const method = "POST";
switch (method) {
  case "GET": {
    const message = "reading data";
    console.log(message);
    break;
  }
  case "POST": {
    const message = "creating data";
    console.log(message);
    break;
  }
}

⌨️ Terminal

node scope-fixed.js

🖥️ Output

creating data

📊 Ranges with switch (true)

Cases must be exact values, so ranges such as “score from 75 to 89” do not fit directly. A known pattern is switch (true): each case is a condition, and the first one that equals true wins.

📄 switch-true.js

function rateResponse(ms) {
  switch (true) {
    case ms < 200:
      return "excellent";
    case ms < 1000:
      return "acceptable";
    case ms < 3000:
      return "slow";
    default:
      return "timeout risk";
  }
}

for (const ms of [150, 640, 2400, 5000]) {
  console.log(`${ms} ms: ${rateResponse(ms)}`);
}

⌨️ Terminal

node switch-true.js

🖥️ Output

150 ms: excellent
640 ms: acceptable
2400 ms: slow
5000 ms: timeout risk

📌 Note: switch (true) works, but many teams prefer an if / else if chain for ranges because it is more familiar. Pick one style per project.


⚖️ switch vs if/else vs Lookup Object

UseWhen
if / else ifConditions are ranges or combinations (age >= 18 && hasId), or there are only two or three branches
switchOne value is compared with many exact options, and each option runs different code
Lookup object / MapEach option only maps to a value (or a function), and the list may grow

The same mapping written as a switch and as a lookup object:

📄 compare.js

function timeoutFor(env) {
  switch (env) {
    case "local":
      return 5000;
    case "qa":
      return 15000;
    case "prod":
      return 30000;
    default:
      throw new Error(`Unknown environment: ${env}`);
  }
}

const TIMEOUTS = { local: 5000, qa: 15000, prod: 30000 };
const timeoutFor2 = (env) => {
  if (!(env in TIMEOUTS)) throw new Error(`Unknown environment: ${env}`);
  return TIMEOUTS[env];
};

console.log(timeoutFor("qa"), timeoutFor2("qa"));
try {
  timeoutFor("staging");
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node compare.js

🖥️ Output

15000 15000
Unknown environment: staging

💡 Tip: Throwing in default for unexpected values is a good habit in test code. A typo such as "QA" instead of "qa" then fails loudly instead of running tests with the wrong settings.


🧪 Tester Scenario: Choose Settings per Environment and Action

This script reads the environment from the command line (with a default), picks the base URL and retry count, and maps test actions to log messages:

📄 env-switch.js

const env = (process.argv[2] || "qa").toLowerCase();

let baseURL;
let retries;
switch (env) {
  case "local":
    baseURL = "http://localhost:3000";
    retries = 0;
    break;
  case "qa":
  case "staging":
    baseURL = `https://${env}.example.com`;
    retries = 1;
    break;
  case "prod":
    baseURL = "https://www.example.com";
    retries = 2;
    break;
  default:
    throw new Error(`Unsupported environment "${env}"`);
}
console.log({ env, baseURL, retries });

const steps = ["open", "login", "search", "logout", "upload"];
for (const step of steps) {
  switch (step) {
    case "open":
      console.log(`→ open ${baseURL}`);
      break;
    case "login":
    case "logout":
      console.log(`→ ${step} (auth step)`);
      break;
    case "search":
      console.log("→ search for \"laptop\"");
      break;
    default:
      console.log(`→ skipped unknown step "${step}"`);
  }
}

⌨️ Terminal

node env-switch.js

🖥️ Output

{ env: 'qa', baseURL: 'https://qa.example.com', retries: 1 }
→ open https://qa.example.com
→ login (auth step)
→ search for "laptop"
→ logout (auth step)
→ skipped unknown step "upload"

Run it with an argument to try other environments: node env-switch.js staging.


📝 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 a switch that prints the number of days in a month name (ignore leap years). Group months with 31 and 30 days.

Show answer

📄 practice1.js

function daysIn(month) {
  switch (month) {
    case "feb":
      return 28;
    case "apr":
    case "jun":
    case "sep":
    case "nov":
      return 30;
    case "jan": case "mar": case "may": case "jul":
    case "aug": case "oct": case "dec":
      return 31;
    default:
      throw new Error(`Unknown month ${month}`);
  }
}

console.log(daysIn("feb"), daysIn("jun"), daysIn("dec"));

🖥️ Output

28 30 31

Q2. Predict the output, then run it.

const x = 2;
switch (x) {
  case 1:
    console.log("one");
  case 2:
    console.log("two");
  case 3:
    console.log("three");
    break;
  default:
    console.log("other");
}
Show answer

📄 practice2.js

const x = 2;
switch (x) {
  case 1:
    console.log("one");
  case 2:
    console.log("two");
  case 3:
    console.log("three");
    break;
  default:
    console.log("other");
}

🖥️ Output

two
three

Case 2 matches, prints “two”, falls through into case 3, prints “three” and stops at break.

Q3. Build a tiny calculator: calc(a, op, b) supports +, -, *, / and throws for unknown operators and division by zero.

Show answer

📄 practice3.js

function calc(a, op, b) {
  switch (op) {
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/":
      if (b === 0) throw new Error("Division by zero");
      return a / b;
    default:
      throw new Error(`Unknown operator ${op}`);
  }
}

console.log(calc(6, "+", 2), calc(6, "-", 2), calc(6, "*", 2), calc(6, "/", 2));
try { calc(1, "/", 0); } catch (e) { console.log(e.message); }
try { calc(1, "^", 2); } catch (e) { console.log(e.message); }

🖥️ Output

8 4 12 3
Division by zero
Unknown operator ^

Q4. Use switch (true) to convert a percentage to a grade: 90+ A, 75+ B, 60+ C, otherwise F.

Show answer

📄 practice4.js

function grade(p) {
  switch (true) {
    case p >= 90: return "A";
    case p >= 75: return "B";
    case p >= 60: return "C";
    default: return "F";
  }
}

console.log([92, 75, 61, 10].map(grade).join(" "));

🖥️ Output

A B C F

Q5. Why does this switch always print “unknown”? Fix it.

const input = "2";
switch (input) {
  case 1: console.log("one"); break;
  case 2: console.log("two"); break;
  default: console.log("unknown");
}
Show answer

Cases use strict equality: the string "2" never equals the number 2. Convert the input first:

📄 practice5.js

const input = "2";
switch (Number(input)) {
  case 1: console.log("one"); break;
  case 2: console.log("two"); break;
  default: console.log("unknown");
}

🖥️ Output

two

Q6. Rewrite this switch as a lookup object with a default of "⚪".

switch (status) {
  case "passed": icon = "✅"; break;
  case "failed": icon = "❌"; break;
  case "skipped": icon = "⏭️"; break;
  default: icon = "⚪";
}
Show answer

📄 practice6.js

const ICONS = { passed: "✅", failed: "❌", skipped: "⏭️" };
for (const status of ["passed", "failed", "flaky"]) {
  console.log(status, ICONS[status] ?? "⚪");
}

🖥️ Output

passed ✅
failed ❌
flaky ⚪

🧠 MCQ Quiz: switch Statement

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which comparison does switch use to match cases?
  2. What happens if a matching case has no break?
  3. When does the default case run?
  4. How do you make two cases run the same code?
  5. Why does declaring const x in two different cases fail?
  6. What is switch (true) used for?
  7. Inside a function, why is break not needed after return in a case?
  8. Which is usually the best choice for mapping a few fixed keys to values?
  9. What does this print?
    switch (3) {
      default: console.log("d");
      case 1: console.log("1");
    }
  10. Which ESLint rule reports an accidental missing break?

💼 Interview Questions and Answers

Q1. What is fall-through in a switch statement?

After a case matches, JavaScript keeps executing the following case bodies until it hits break, return, throw or the end of the switch. Intentional fall-through is used to group cases that share code; accidental fall-through (a forgotten break) is a common bug that ESLint’s no-fallthrough rule catches.

Q2. When would you choose switch over if/else?

When one expression is compared against many exact values and each value needs different code, such as actions per HTTP method or per test step. For ranges and combined conditions if/else is clearer; for value-only mappings a lookup object or Map is shorter and data-driven.

Q3. Why might a switch never match even though the value “looks” right?

Cases use ===, so types must match exactly: "200" vs 200, "QA" vs "qa", or a value with trailing spaces from a page. Normalise the input first (Number(), .trim().toLowerCase()) and make default throw or log the unexpected value so the mismatch is visible.

Q4. Can a case contain an expression instead of a literal?

Yes. Case labels are evaluated as expressions, so case MAX_RETRIES: or case a + b: are valid. They are evaluated in order only until a match is found. switch (true) takes advantage of this by using conditions as case expressions.

📄 case-expr.js

const LIMIT = 3;
const attempts = 3;
switch (attempts) {
  case LIMIT - 1: console.log("last try left"); break;
  case LIMIT: console.log("limit reached"); break;
}

⌨️ Terminal

node case-expr.js

🖥️ Output

limit reached

❓ Frequently Asked Questions

🤔 Is break required in every case?

Not by the language, but without it execution falls through to the next case. Leave it out only on purpose (and comment it), or when the case ends with return or throw.

🤔 Does the default case have to be last?

No, it can appear anywhere, but putting it last is the convention and avoids confusing fall-through.

🤔 Can switch compare strings?

Yes. Any value works, compared with ===. Normalise case and whitespace first when the input comes from users or web pages.

🤔 Is switch faster than if/else?

For typical code the difference is negligible. Choose the form that is clearest for the logic.


🏁 Summary

  • switch compares one value with many case labels using ===; default handles no match.
  • Without break (or return), execution falls through into the next case.
  • Group cases by listing labels together; wrap case bodies in braces when they declare variables.
  • switch (true) can handle ranges, but if/else if is often clearer.
  • Use lookup objects for simple value mappings, and throw in default for unexpected input.

Next, continue with Lesson 15: Loops.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in