JavaScript Coding Interview Programs with Solutions (Tested)

Most JavaScript interviews, including SDET and automation roles, include one or two small coding tasks. They are rarely about clever algorithms; they check that you can turn a requirement into clean, correct code, think about edge cases, and explain the cost of your solution. This lesson has 24 of the most frequently asked programs, grouped by topic, each with a tested solution (run on Node.js 26 with its real output), the edge cases interviewers look for, and the complexity in Big O. At the end you will find links to more than 370 practice programs on SQA Tools.

Advertisement

📖 What You’ll Learn: a method for solving coding questions in interviews, string programs (reverse, palindrome, anagram, character counts, first unique character, capitalising words), array programs (duplicates, second largest, flatten, chunk, rotate, two-sum, missing number), object programs (group by, deep equality, invert, merge counts), number programs (FizzBuzz, prime, Fibonacci, factorial), utility programs testers are asked (retry, parse query strings, validate emails, compare JSON), and where to practise more.


🧭 How to Solve a Coding Question in an Interview

  1. Clarify: restate the problem; ask about input types, case sensitivity, empty input, duplicates, size.
  2. Examples: write 2–3 inputs with expected outputs, including an edge case.
  3. Plan out loud: describe the approach before coding; mention a simple solution first.
  4. Code clearly: good names, small functions, built-in methods where they help.
  5. Test: run your examples (in your head or the editor), especially the edge cases.
  6. Analyse: state time and space complexity and how you would improve it.

💡 Tip: For testing roles, finishing with “here are the test cases I would write for this function” (empty, one item, duplicates, unicode, very large input) is a strong signal.


🔤 String Programs

1. Reverse a string

Reverse “Playwright” without changing the original. Bonus: handle emoji correctly.

📄 solution.js

const reverse = (s) => [...s].reverse().join("");
console.log(reverse("Playwright"));
console.log(reverse("QA 😀 rocks"));
console.log("QA 😀".split("").reverse().join("") === reverse("QA 😀"));   // split("") breaks emoji

⌨️ Terminal

node solution.js

🖥️ Output

thgirwyalP
skcor 😀 AQ
false

[...s] splits by code points, so emoji stay intact; split("") splits UTF-16 units and corrupts them. O(n) time and space.

2. Palindrome check

Ignore case, spaces and punctuation.

📄 solution.js

function isPalindrome(text) {
  const clean = text.toLowerCase().replace(/[^a-z0-9]/g, "");
  for (let i = 0, j = clean.length - 1; i < j; i++, j--) {
    if (clean[i] !== clean[j]) return false;
  }
  return true;
}
for (const t of ["Madam", "A man, a plan, a canal: Panama", "QA tester", ""]) console.log(JSON.stringify(t), isPalindrome(t));

⌨️ Terminal

node solution.js

🖥️ Output

"Madam" true
"A man, a plan, a canal: Panama" true
"QA tester" false
"" true

Two pointers compare from both ends without building a reversed copy: O(n) time, O(n) for the cleaned string. Note the empty string is a palindrome.

3. Anagram check

“listen” and “silent” use the same letters.

📄 solution.js

function isAnagram(a, b) {
  const norm = (s) => s.toLowerCase().replace(/\s/g, "");
  a = norm(a); b = norm(b);
  if (a.length !== b.length) return false;
  const counts = new Map();
  for (const ch of a) counts.set(ch, (counts.get(ch) ?? 0) + 1);
  for (const ch of b) {
    if (!counts.get(ch)) return false;
    counts.set(ch, counts.get(ch) - 1);
  }
  return true;
}
console.log(isAnagram("listen", "silent"), isAnagram("Dormitory", "dirty room"), isAnagram("test", "tset "), isAnagram("aab", "abb"));

⌨️ Terminal

node solution.js

🖥️ Output

true true true false

Counting characters is O(n); sorting both strings is simpler to write but O(n log n).

4. Count characters and find the most frequent

Count each character in “automation” and return the most frequent one.

📄 solution.js

function charCounts(s) {
  const counts = {};
  for (const ch of s) counts[ch] = (counts[ch] ?? 0) + 1;
  return counts;
}
const counts = charCounts("automation");
const [top, n] = Object.entries(counts).reduce((best, cur) => (cur[1] > best[1] ? cur : best));
console.log(counts);
console.log(`most frequent (first on ties): "${top}" x${n}`);

⌨️ Terminal

node solution.js

🖥️ Output

{ a: 2, u: 1, t: 2, o: 2, m: 1, i: 1, n: 1 }
most frequent (first on ties): "a" x2

Here “a”, “t” and “o” all appear twice; the > comparison keeps the first one found. Ask the interviewer how ties should be handled: it is a classic clarifying question.

5. First non-repeating character

Return the first character that appears only once, or null.

📄 solution.js

function firstUnique(s) {
  const counts = new Map();
  for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
  for (const ch of s) if (counts.get(ch) === 1) return ch;
  return null;
}
console.log(firstUnique("swiss"), firstUnique("testing"), firstUnique("aabb"));

⌨️ Terminal

node solution.js

🖥️ Output

w e null

Two passes, O(n). A Map keeps the logic clear.

6. Capitalise every word and count vowels

“welcome to sqa tools” → “Welcome To Sqa Tools”.

📄 solution.js

const titleCase = (s) => s.split(" ").map((w) => (w ? w[0].toUpperCase() + w.slice(1).toLowerCase() : w)).join(" ");
const vowels = (s) => (s.match(/[aeiou]/gi) ?? []).length;
console.log(titleCase("welcome to sqa TOOLS"));
console.log(vowels("Playwright Automation"), vowels("rhythm"));

⌨️ Terminal

node solution.js

🖥️ Output

Welcome To Sqa Tools
8 0

match returns null when nothing matches, hence ?? []: a classic edge case.


📚 Array Programs

7. Remove duplicates (and keep order)

Return unique values from [3, 1, 3, 2, 1].

📄 solution.js

const unique = (arr) => [...new Set(arr)];
console.log(unique([3, 1, 3, 2, 1]));

// unique objects by a key
const users = [{ id: 1, n: "a" }, { id: 2, n: "b" }, { id: 1, n: "a again" }];
const byId = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(byId);

⌨️ Terminal

node solution.js

🖥️ Output

[ 3, 1, 2 ]
[ { id: 1, n: 'a again' }, { id: 2, n: 'b' } ]

A Set keeps first-insertion order: O(n). For objects, a Map keyed by id keeps the last occurrence.

Advertisement

8. Second largest number

Without sorting; handle duplicates and short arrays.

📄 solution.js

function secondLargest(nums) {
  let first = -Infinity, second = -Infinity;
  for (const n of nums) {
    if (n > first) { second = first; first = n; }
    else if (n > second && n < first) second = n;
  }
  return second === -Infinity ? null : second;
}
console.log(secondLargest([10, 40, 20, 40, 30]), secondLargest([5]), secondLargest([7, 7]));

⌨️ Terminal

node solution.js

🖥️ Output

30 null null

One pass, O(n), O(1) space. Sorting would be O(n log n) and must handle duplicates separately.

9. Flatten a nested array

Flatten [1, [2, [3, [4]], 5]] without and with built-ins.

📄 solution.js

const flatten = (arr) => arr.reduce((out, x) => out.concat(Array.isArray(x) ? flatten(x) : x), []);
const nested = [1, [2, [3, [4]], 5]];
console.log(flatten(nested));
console.log(nested.flat(Infinity));

⌨️ Terminal

node solution.js

🖥️ Output

[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

10. Chunk an array

Split [1..7] into groups of 3 (useful for batching API calls).

📄 solution.js

const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
console.log(chunk([], 3));

⌨️ Terminal

node solution.js

🖥️ Output

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
[]

11. Rotate an array by k

Rotate [1, 2, 3, 4, 5] right by 2; k may be larger than the length.

📄 solution.js

function rotate(arr, k) {
  if (arr.length === 0) return [];
  const n = ((k % arr.length) + arr.length) % arr.length;   // handles k > length and negative k
  return [...arr.slice(-n || arr.length), ...arr.slice(0, -n || arr.length)].slice(0, arr.length);
}
console.log(rotate([1, 2, 3, 4, 5], 2), rotate([1, 2, 3, 4, 5], 7), rotate([1, 2, 3, 4, 5], -1), rotate([1, 2, 3], 0));

⌨️ Terminal

node solution.js

🖥️ Output

[ 4, 5, 1, 2, 3 ] [ 4, 5, 1, 2, 3 ] [ 2, 3, 4, 5, 1 ] [ 1, 2, 3 ]

12. Two sum

Return the indices of two numbers that add up to a target.

📄 solution.js

function twoSum(nums, target) {
  const seen = new Map();                         // value -> index
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return null;
}
console.log(twoSum([2, 7, 11, 15], 9), twoSum([3, 3], 6), twoSum([1, 2], 10));

⌨️ Terminal

node solution.js

🖥️ Output

[ 0, 1 ] [ 0, 1 ] null

The nested-loop solution is O(n²); the Map makes it O(n). Interviewers expect you to start simple and then optimise.

13. Find the missing number

An array has numbers 1..n with one missing.

📄 solution.js

const missing = (arr, n = arr.length + 1) => (n * (n + 1)) / 2 - arr.reduce((s, x) => s + x, 0);
console.log(missing([1, 2, 4, 5, 6]), missing([2, 3, 4]));

⌨️ Terminal

node solution.js

🖥️ Output

3 1

14. Merge two sorted arrays

Merge [1, 4, 9] and [2, 3, 10] into one sorted array in O(n + m).

📄 solution.js

function mergeSorted(a, b) {
  const out = [];
  let i = 0, j = 0;
  while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  return [...out, ...a.slice(i), ...b.slice(j)];
}
console.log(mergeSorted([1, 4, 9], [2, 3, 10]), mergeSorted([], [1]));

⌨️ Terminal

node solution.js

🖥️ Output

[ 1, 2, 3, 4, 9, 10 ] [ 1 ]

🗂️ Object Programs

15. Group by a key

Group test results by status (without Object.groupBy, then with it).

📄 solution.js

const results = [{ t: "login", s: "passed" }, { t: "cart", s: "failed" }, { t: "pay", s: "passed" }];
const grouped = results.reduce((acc, r) => {
  (acc[r.s] ??= []).push(r.t);
  return acc;
}, {});
console.log(grouped);
console.log(Object.keys(Object.groupBy(results, (r) => r.s)));

⌨️ Terminal

node solution.js

🖥️ Output

{ passed: [ 'login', 'pay' ], failed: [ 'cart' ] }
[ 'passed', 'failed' ]

16. Deep equality

Compare two values structurally (objects, arrays, primitives).

📄 solution.js

function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
  if (Array.isArray(a) !== Array.isArray(b)) return false;
  const keysA = Object.keys(a), keysB = Object.keys(b);
  return keysA.length === keysB.length && keysA.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}
console.log(deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }));
console.log(deepEqual({ a: 1 }, { a: "1" }), deepEqual([1, 2], { 0: 1, 1: 2 }), deepEqual(NaN, NaN));

⌨️ Terminal

node solution.js

🖥️ Output

true
false false true

A common follow-up: this ignores Dates, Maps and circular references. Test frameworks (assert.deepStrictEqual, expect().toEqual) handle those.

Advertisement

17. Invert an object and count words

Swap keys and values; count word frequencies in a sentence.

📄 solution.js

const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
console.log(invert({ chromium: "blink", firefox: "gecko", webkit: "webkit" }));

const wordCount = (text) => text.toLowerCase().match(/[a-z]+/g).reduce((m, w) => m.set(w, (m.get(w) ?? 0) + 1), new Map());
console.log(wordCount("Test early, test often, and test the tests"));

⌨️ Terminal

node solution.js

🖥️ Output

{ blink: 'chromium', gecko: 'firefox', webkit: 'webkit' }
Map(6) {
  'test' => 3,
  'early' => 1,
  'often' => 1,
  'and' => 1,
  'the' => 1,
  'tests' => 1
}

18. Get a nested value safely

Read “user.address.city” from an object; return a default when any part is missing.

📄 solution.js

const get = (obj, path, fallback) => path.split(".").reduce((v, k) => v?.[k], obj) ?? fallback;
const data = { user: { address: { city: "Pune" }, tags: ["qa"] } };
console.log(get(data, "user.address.city"), get(data, "user.tags.0"), get(data, "user.phone.number", "n/a"));

⌨️ Terminal

node solution.js

🖥️ Output

Pune qa n/a

🔢 Number Programs

19. FizzBuzz

Print 1–15; multiples of 3 → Fizz, of 5 → Buzz, of both → FizzBuzz.

📄 solution.js

const fizzBuzz = (n) => Array.from({ length: n }, (_, i) => {
  const x = i + 1;
  return x % 15 === 0 ? "FizzBuzz" : x % 3 === 0 ? "Fizz" : x % 5 === 0 ? "Buzz" : x;
});
console.log(fizzBuzz(15).join(" "));

⌨️ Terminal

node solution.js

🖥️ Output

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

20. Prime check and primes up to n

Check one number efficiently; list primes up to 50 with a sieve.

📄 solution.js

function isPrime(n) {
  if (n < 2 || !Number.isInteger(n)) return false;
  for (let d = 2; d * d <= n; d++) if (n % d === 0) return false;
  return true;
}
function primesUpTo(n) {
  const sieve = new Array(n + 1).fill(true);
  sieve[0] = sieve[1] = false;
  for (let i = 2; i * i <= n; i++) if (sieve[i]) for (let j = i * i; j <= n; j += i) sieve[j] = false;
  return sieve.flatMap((p, i) => (p ? [i] : []));
}
console.log([1, 2, 17, 21, 97].map(isPrime));
console.log(primesUpTo(50));

⌨️ Terminal

node solution.js

🖥️ Output

[ false, true, true, false, true ]
[
   2,  3,  5,  7, 11, 13,
  17, 19, 23, 29, 31, 37,
  41, 43, 47
]

Checking divisors only up to √n makes isPrime O(√n). The Sieve of Eratosthenes is O(n log log n).

21. Fibonacci and factorial

Iterative versions; factorial of large numbers with BigInt.

📄 solution.js

const fibonacci = (n) => { const out = [0, 1]; while (out.length < n) out.push(out.at(-1) + out.at(-2)); return out.slice(0, n); };
const factorial = (n) => { let r = 1n; for (let i = 2n; i <= BigInt(n); i++) r *= i; return r; };
console.log(fibonacci(10));
console.log(factorial(5), factorial(25));

⌨️ Terminal

node solution.js

🖥️ Output

[
  0, 1,  1,  2,  3,
  5, 8, 13, 21, 34
]
120n 15511210043330985984000000n

Recursive Fibonacci without memoization is exponential; iteration is O(n). Factorial passes Number.MAX_SAFE_INTEGER quickly, so use BigInt.


🧪 Utility Programs Testers Are Asked

22. Parse a query string

Turn “?browser=chromium&tag=smoke&tag=ui&retries=2” into an object with arrays for repeated keys.

📄 solution.js

function parseQuery(qs) {
  const out = {};
  for (const [k, v] of new URLSearchParams(qs)) {
    out[k] = k in out ? [].concat(out[k], v) : v;
  }
  return out;
}
console.log(parseQuery("?browser=chromium&tag=smoke&tag=ui&retries=2&q=usb%20cable"));

⌨️ Terminal

node solution.js

🖥️ Output

{
  browser: 'chromium',
  tag: [ 'smoke', 'ui' ],
  retries: '2',
  q: 'usb cable'
}

23. Validate an email (simply) and test it

Write a pragmatic validator and the test cases you would run.

📄 solution.js

const isEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(s);
const cases = { "qa@sqatools.in": true, "first.last+tag@mail.co": true, "no-at-sign.com": false, "a@b": false, "spaces in@mail.com": false, "": false };
for (const [input, expected] of Object.entries(cases)) {
  console.log(isEmail(input) === expected ? "✓" : "✗", JSON.stringify(input), isEmail(input));
}

⌨️ Terminal

node solution.js

🖥️ Output

✓ "qa@sqatools.in" true
✓ "first.last+tag@mail.co" true
✓ "no-at-sign.com" false
✓ "a@b" false
✓ "spaces in@mail.com" false
✓ "" false

Perfect email validation by regex is impossible; say so, keep the rule pragmatic, and rely on a confirmation email for the real check.

24. Retry an async function with backoff

Retry up to 3 times, doubling the delay, and report attempts.

📄 solution.js

async function retry(fn, { attempts = 3, delay = 10 } = {}) {
  for (let i = 1; ; i++) {
    try {
      return await fn(i);
    } catch (e) {
      if (i === attempts) throw new Error(`failed after ${attempts} attempts: ${e.message}`);
      await new Promise((r) => setTimeout(r, delay * 2 ** (i - 1)));
    }
  }
}
const flaky = async (attempt) => { if (attempt < 3) throw new Error(`503 on attempt ${attempt}`); return `ok on attempt ${attempt}`; };
console.log(await retry(flaky));
await retry(async () => { throw new Error("500"); }).catch((e) => console.log(e.message));

⌨️ Terminal

node solution.js

🖥️ Output

ok on attempt 3
failed after 3 attempts: 500

Mention that retries belong around unreliable infrastructure, not around assertions, and only for idempotent operations.


📝 More Practice on SQA Tools

Keep practising with these topic-wise program collections (with solutions) on SQA Tools:

For more question-and-answer practice, see the original JavaScript Interview Questions and Answers page.


Advertisement

📝 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 countOccurrences(arr, value) without a loop keyword.

Show answer

📄 p1.js

const countOccurrences = (arr, value) => arr.filter((x) => x === value).length;
console.log(countOccurrences(["pass", "fail", "pass"], "pass"));

🖥️ Output

2

Q2. Return the longest word in a sentence (first one if tied).

Show answer

📄 p2.js

const longestWord = (s) => s.split(/\s+/).reduce((best, w) => (w.length > best.length ? w : best), "");
console.log(longestWord("Playwright makes browser automation reliable"));

🖥️ Output

Playwright

Q3. Check whether brackets in a string are balanced: “({[]})” is, “([)]” is not.

Show answer

📄 p3.js

function balanced(s) {
  const pairs = { ")": "(", "]": "[", "}": "{" };
  const stack = [];
  for (const ch of s) {
    if ("([{".includes(ch)) stack.push(ch);
    else if (ch in pairs && stack.pop() !== pairs[ch]) return false;
  }
  return stack.length === 0;
}
console.log(balanced("({[]})"), balanced("([)]"), balanced("(("), balanced(""));

🖥️ Output

true false false true

Q4. Find the intersection of two arrays (unique values present in both).

Show answer

📄 p4.js

const intersect = (a, b) => [...new Set(a).intersection(new Set(b))];
console.log(intersect([1, 2, 2, 3, 4], [2, 4, 4, 6]));

🖥️ Output

[ 2, 4 ]

Q5. Compress a string: “aaabccdddd” → “a3b1c2d4”.

Show answer

📄 p5.js

const compress = (s) => s.replace(/(.)\1*/g, (run, ch) => ch + run.length);
console.log(compress("aaabccdddd"), compress(""));

🖥️ Output

a3b1c2d4

Q6. Sort users by age (ascending), then by name, without mutating the input.

Show answer

📄 p6.js

const users = [{ n: "Ravi", age: 30 }, { n: "Asha", age: 25 }, { n: "Arjun", age: 30 }];
const sorted = users.toSorted((a, b) => a.age - b.age || a.n.localeCompare(b.n));
console.log(sorted.map((u) => `${u.n}(${u.age})`), users[0].n);

🖥️ Output

[ 'Asha(25)', 'Arjun(30)', 'Ravi(30)' ] Ravi

🧠 MCQ Quiz: Coding Interview Programs

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. Why is [...str].reverse().join("") better than split("") for reversing?
  2. What is the time complexity of two-sum with a Map?
  3. What does [...new Set([3, 1, 3])] return?
  4. Why check divisors only up to √n in a prime test?
  5. What does "abc".match(/x/g) return?
  6. Which is the best first step in a coding interview?
  7. What does arr.flat(Infinity) do?
  8. Why use BigInt for factorial(25)?
  9. Which built-in parses query strings safely?
  10. What is the complexity of merging two sorted arrays with two pointers?

💼 Interview Questions and Answers

Q1. How do you approach a coding problem you have never seen?

Clarify inputs and outputs, work through small examples by hand, find a brute-force solution and say its complexity, then look for a better data structure (Set, Map, two pointers, sorting) to remove repeated work. Code it cleanly, test with the examples plus edge cases (empty, one element, duplicates, negative numbers, unicode), and explain trade-offs.

Q2. How would you test a function such as twoSum or isPalindrome?

Positive cases, negative cases (no answer), boundaries (empty input, one element, the answer at the start or end), duplicates, negative numbers or mixed case and punctuation, very large inputs for performance, and invalid input types if the function must handle them. Put them in a table-driven unit test so new cases are one line each.

Q3. When would you use a Map instead of a plain object?

When keys are not strings (objects, numbers you do not want converted), when insertion order and size matter (map.size), when keys are added and removed often, or when keys could clash with prototype properties such as “constructor”. Plain objects remain natural for fixed, JSON-like records.

Q4. What do interviewers look for beyond a correct answer?

Communication (thinking aloud, asking clarifying questions), readable code with good names, handling of edge cases, testing their own solution, understanding of complexity, and the ability to take a hint and improve the solution calmly.


Advertisement

❓ Frequently Asked Questions

🤔 Can I use built-in methods like sort, Set and flat in interviews?

Usually yes, and you should mention their complexity. If the interviewer wants the algorithm itself (for example “without sort”), they will say so; be ready with both versions for common tasks.

🤔 How many programs should I practise?

Solve each of the 24 here without looking, then 5–10 per topic from the SQA Tools practice pages. Speed comes from recognising patterns: counting with a Map, Sets for uniqueness, two pointers, reduce for grouping.

🤔 Should I write tests during a coding interview?

Run a few example calls at least. For SDET roles, listing the test cases you would automate is a strong plus.

🤔 What about data structure and algorithm rounds?

Product companies may ask harder problems (trees, graphs, dynamic programming). Most QA and automation interviews focus on the string, array and object programs shown here.


🏁 Summary

  • Clarify, give examples, plan aloud, code clearly, test edge cases and state the complexity.
  • Strings: spread for unicode-safe reversal, counting with Maps, regex with null guards.
  • Arrays: Set for uniqueness, Map for O(n) lookups (two-sum), single-pass scans, chunk, rotate, merge.
  • Objects: reduce or Object.groupBy for grouping, careful deep equality, safe nested access.
  • Numbers and utilities: √n prime checks, BigInt for big results, URLSearchParams, retries with backoff; practise more on SQA Tools.

Next, continue with Lesson 79: JavaScript Cheat Sheet.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in