Skip to content
Tutorials Center
My learning

Topics

Lesson 151 of 156 ยท Practice and Review

JavaScript Practice Exercises

38 graded JavaScript exercises with live editors and hidden solutions, covering strings, functions, arrays, objects, classes, async code, the DOM, algorithms and classic interview questions.

Reading about JavaScript builds understanding; writing it builds skill. This page collects 38 practice exercises, grouped by topic and graded from beginner to advanced. Every exercise has a live editor with starter code and a few test calls, so you can see straight away whether your answer works.

Try each exercise on your own before you open the solution. If you get stuck for more than ten minutes, reread the lesson linked at the top of the group, then try again. When you do look at the solution, type it out yourself instead of copying it: your fingers learn too. There is usually more than one correct answer, so if your version prints the expected output, it counts.

How to use the editors. Replace the // your code here line, press Run, and compare the console output with the // expected comments. Your changes are not saved, so copy anything you want to keep.

Basics

These practice variables, conditions and loops.

1. Swap without a temp variable (beginner)

Swap the values of a and b in a single line, without creating a third variable.

JS Exercise 1

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
[a, b] = [b, a];

Array destructuring builds a temporary array [b, a] on the right and unpacks it into a and b on the left.

2. Letter grade (beginner)

Write grade(score) that returns "A" for 90 and above, "B" for 80โ€“89, "C" for 70โ€“79, "D" for 60โ€“69 and "F" below 60. Return "invalid" for anything outside 0โ€“100 or not a number.

JS Exercise 2

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function grade(score) {
  if (typeof score !== "number" || score < 0 || score > 100) return "invalid";
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

Checking the invalid cases first (a "guard clause") keeps the rest simple. Because each return exits early, the later conditions only need a lower bound. typeof NaN is "number", so a stricter version would also check Number.isNaN(score).

3. Sum of digits (beginner)

Write digitSum(n) that adds up the digits of a whole number. Negative numbers should work too.

JS Exercise 3

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function digitSum(n) {
  let total = 0;
  for (let rest = Math.abs(n); rest > 0; rest = Math.floor(rest / 10)) {
    total += rest % 10;
  }
  return total;
}

% 10 gives the last digit and Math.floor(rest / 10) removes it. A shorter string-based version is [...String(Math.abs(n))].reduce((sum, d) => sum + Number(d), 0).

4. Count the vowels (beginner)

Write countVowels(text) that returns how many of the letters a, e, i, o, u appear, in either case.

JS Exercise 4

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function countVowels(text) {
  let count = 0;
  for (const char of text.toLowerCase()) {
    if ("aeiou".includes(char)) count++;
  }
  return count;
}

for...of walks a string character by character. A regex alternative is (text.match(/[aeiou]/gi) ?? []).length; the ?? [] handles match() returning null when nothing matches.

Strings

Practice for String Methods and Template Literals.

5. Title case (beginner)

Write titleCase(text) that capitalizes the first letter of every word and lowercases the rest. Words are separated by single spaces.

JS Exercise 5

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function titleCase(text) {
  return text
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(" ");
}

Split into words, transform each one with map(), and join them back. charAt(0) returns "" for an empty word instead of undefined, so double spaces don't crash it.

6. Palindrome check (intermediate)

Write isPalindrome(text) that returns true if the text reads the same backwards, ignoring case, spaces and punctuation.

JS Exercise 6

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function isPalindrome(text) {
  const clean = text.toLowerCase().replace(/[^a-z0-9]/g, "");
  return clean === [...clean].reverse().join("");
}

The regular expression removes everything that is not a letter or digit. To support accented letters, use /[^\p{L}\p{N}]/gu instead.

7. Truncate with an ellipsis (intermediate)

Write truncate(text, max) that returns the text unchanged if it fits in max characters. Otherwise, cut it so that the result, including a trailing โ€ฆ, is at most max characters, and don't leave a space before the โ€ฆ.

JS Exercise 7

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function truncate(text, max) {
  if (text.length <= max) return text;
  return text.slice(0, max - 1).trimEnd() + "โ€ฆ";
}

Keep max - 1 characters to leave room for the single โ€ฆ character, and trimEnd() removes a dangling space. In the last example, "Hello " becomes "Hello".

Functions

Practice for Functions, Closures and Higher-Order Functions.

8. Counter factory (intermediate)

Write makeCounter(start = 0) that returns an object with increment(), decrement() and value() methods. The count must not be reachable from outside.

JS Exercise 8

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function makeCounter(start = 0) {
  let count = start;
  return {
    increment() { count++; },
    decrement() { count--; },
    value() { return count; },
  };
}

count is a local variable. The three methods are closures that keep access to it after makeCounter returns, but nothing else can reach it.

9. Run only once (intermediate)

Write once(fn) that returns a new function. The first call runs fn with the given arguments and returns its result; every later call returns that same first result without running fn again.

JS Exercise 9

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

A separate called flag is safer than checking result, because fn might return undefined. Using a regular function with fn.apply(this, args) keeps this working when the wrapped function is used as a method.

10. Pipe (intermediate)

Write pipe(...fns) that returns a function passing its input through every function from left to right.

JS Exercise 10

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function pipe(...fns) {
  return (input) => fns.reduce((value, fn) => fn(value), input);
}

reduce() feeds each function's result into the next one. With no functions, reduce() simply returns the starting value, so pipe() is the identity function.

11. Memoize (advanced)

Write memoize(fn) that caches results by argument, so calling the returned function again with the same single argument returns the cached value without running fn.

JS Exercise 11

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}

A Map accepts any value as a key, including objects, and has() correctly handles cached results that are undefined or 0. For several arguments you need a combined key, such as JSON.stringify(args) for simple values.

Arrays

Practice for Array Methods, Iterating Arrays and Array Recipes.

12. Remove duplicates (beginner)

Write unique(list) that returns a new array without duplicates, keeping the first occurrence of each value in its original order.

JS Exercise 12

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function unique(list) {
  return [...new Set(list)];
}

A Set keeps only one copy of each value and remembers insertion order. Spreading it back gives an array.

13. Chunk an array (intermediate)

Write chunk(list, size) that splits an array into groups of size items. The last group may be shorter.

JS Exercise 13

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function chunk(list, size) {
  const groups = [];
  for (let i = 0; i < list.length; i += size) {
    groups.push(list.slice(i, i + size));
  }
  return groups;
}

The loop jumps size items at a time, and slice() safely stops at the end of the array, so the last group is just shorter.

14. Group by a property (intermediate)

Write groupBy(list, key) that returns an object whose keys are the values of item[key] and whose values are arrays of matching items. Don't use Object.groupBy().

JS Exercise 14

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function groupBy(list, key) {
  return list.reduce((groups, item) => {
    const group = item[key];
    (groups[group] ??= []).push(item);
    return groups;
  }, {});
}

??= creates the array the first time a group appears. In modern browsers, Object.groupBy(books, (b) => b.genre) does the same in one call.

15. Top three (intermediate)

Write topThree(products) that returns the names of the three most expensive products, most expensive first, without changing the original array.

JS Exercise 15

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function topThree(products) {
  return products
    .toSorted((a, b) => b.price - a.price)
    .slice(0, 3)
    .map((p) => p.name);
}

toSorted() returns a sorted copy (see Sorting Arrays); b.price - a.price sorts high to low. In older environments, use [...products].sort(...).

16. Deep flatten (advanced)

Write flattenDeep(list) that flattens nested arrays of any depth, without using flat().

JS Exercise 16

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function flattenDeep(list) {
  const result = [];
  for (const item of list) {
    if (Array.isArray(item)) result.push(...flattenDeep(item));
    else result.push(item);
  }
  return result;
}

Recursion handles any depth: each nested array is flattened by the same function. The built-in equivalent is list.flat(Infinity).

Objects

Practice for Objects, Object Methods and Copying Objects.

17. Pick properties (beginner)

Write pick(obj, keys) that returns a new object with only the listed keys that exist on obj.

JS Exercise 17

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function pick(obj, keys) {
  return Object.fromEntries(
    keys.filter((key) => Object.hasOwn(obj, key)).map((key) => [key, obj[key]])
  );
}

Filtering with Object.hasOwn() skips missing keys, so email doesn't appear as undefined. Object.fromEntries() turns the [key, value] pairs back into an object.

18. Invert an object (intermediate)

Write invert(obj) that swaps keys and values: { a: "x" } becomes { x: "a" }.

JS Exercise 18

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function invert(obj) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [value, key])
  );
}

Object.entries() gives [key, value] pairs, destructuring in the arrow parameters swaps them, and Object.fromEntries() rebuilds the object. If two keys share a value, the last one wins.

19. Deep equality (advanced)

Write deepEqual(a, b) that returns true when two values are equal, comparing plain objects and arrays by content at every level.

JS Exercise 19

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
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);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;

  return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
}

Object.is() treats NaN as equal to itself. After ruling out primitives and null, compare key counts, then recurse into every key. This handles plain data; dates, maps and circular references need extra cases.

Classes

Practice for Classes, Private and Static and Data Structures.

20. Bank account (intermediate)

Write a BankAccount class with a private balance, deposit(amount) and withdraw(amount) methods that return the account (for chaining), and a balance getter. Throw a RangeError for non-positive amounts or when a withdrawal exceeds the balance.

JS Exercise 20

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
class BankAccount {
  #balance;

  constructor(owner, opening = 0) {
    this.owner = owner;
    this.#balance = opening;
  }

  get balance() {
    return this.#balance;
  }

  deposit(amount) {
    if (!(amount > 0)) throw new RangeError("Amount must be positive");
    this.#balance += amount;
    return this;
  }

  withdraw(amount) {
    if (!(amount > 0)) throw new RangeError("Amount must be positive");
    if (amount > this.#balance) throw new RangeError("Insufficient funds");
    this.#balance -= amount;
    return this;
  }
}

The #balance field can only change through the methods, which validate every amount. !(amount > 0) also rejects NaN and non-numbers. Real money code should store integer cents to avoid floating-point errors.

21. A min-stack (advanced)

Write a MinStack class with push(n), pop() and min(), where min() returns the smallest value currently in the stack without scanning all items.

JS Exercise 21

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
class MinStack {
  #items = [];
  #mins = [];

  push(n) {
    this.#items.push(n);
    this.#mins.push(Math.min(n, this.#mins.at(-1) ?? Infinity));
  }

  pop() {
    this.#mins.pop();
    return this.#items.pop();
  }

  min() {
    return this.#mins.at(-1);
  }
}

A second stack stores the minimum at each height. Popping removes both tops together, so the previous minimum reappears automatically, and min() is O(1).

Asynchronous code

Practice for Promises, Async and Await and Promise Combinators. These editors use module="true" so you can use top-level await.

22. Countdown with await (beginner)

Write wait(ms) that returns a promise resolving after ms milliseconds, then use it in countdown(n) to log n, n - 1, โ€ฆ 1 and finally "Go!", 300 ms apart.

JS Exercise 22

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function countdown(n) {
  for (let i = n; i > 0; i--) {
    console.log(i);
    await wait(300);
  }
  console.log("Go!");
}

await inside a normal for loop pauses each round, so the numbers appear one after another. (forEach with an async callback would not wait.)

23. Timeout a promise (intermediate)

Write withTimeout(promise, ms) that resolves like promise if it settles in time, and otherwise rejects with an Error("Timed out after <ms> ms").

JS Exercise 23

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function withTimeout(promise, ms) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

Promise.race() settles with whichever promise finishes first. finally() clears the timer so it doesn't fire later for nothing. Note that the slow work itself keeps running; to really cancel a request, use an AbortController.

24. Retry (advanced)

Write retry(task, attempts) that calls the async function task and, if it rejects, tries again up to attempts times in total. Resolve with the first success, or reject with the last error.

JS Exercise 24

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
async function retry(task, attempts) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await task();
    } catch (error) {
      lastError = error;
      console.log(`attempt ${attempt} failed: ${error.message}`);
    }
  }
  throw lastError;
}

return await inside try is important: without await, a rejection would escape the try block instead of being caught. Real code usually waits longer between attempts (exponential backoff).

The DOM

Practice for Events, Changing Content and Event Delegation.

25. Character counter (beginner)

Show "N / 140" under the text area and update it as the user types. When fewer than 20 characters are left, color the counter red.

Exercise 25
Show solution
JavaScript
message.addEventListener("input", () => {
  const used = message.value.length;
  counter.textContent = `${used} / 140`;
  counter.style.color = 140 - used < 20 ? "crimson" : "";
});

The input event fires on every change, including paste and delete, unlike keydown. Setting style.color to an empty string removes the inline style again.

26. Filterable list (intermediate)

As the user types in the search box, hide list items that don't contain the text (case-insensitive) and show "No matches" when nothing is visible.

Exercise 26
Show solution
JavaScript
search.addEventListener("input", () => {
  const query = search.value.trim().toLowerCase();
  let visible = 0;
  for (const item of items) {
    const match = item.textContent.toLowerCase().includes(query);
    item.hidden = !match;
    if (match) visible++;
  }
  empty.hidden = visible > 0;
});

The hidden property maps to the HTML hidden attribute, so there is no CSS to write. querySelectorAll() returns a static NodeList, which works with for...of.

Algorithms

Practice for Searching and Sorting Algorithms and Data Structures.

27. Insertion point (advanced)

Write insertionIndex(sorted, value) using binary search. It returns the index where value should be inserted to keep the array sorted (before any equal values).

JS Exercise 27

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function insertionIndex(sorted, value) {
  let low = 0;
  let high = sorted.length; // note: length, not length - 1
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] < value) low = mid + 1;
    else high = mid;
  }
  return low;
}

This "lower bound" variant keeps the answer inside [low, high] and shrinks the range until it has one possible position left. Because high can equal the length, the value can also go at the very end.

28. Group anagrams (advanced)

Write groupAnagrams(words) that groups words made of the same letters. Return an array of groups, in the order each group first appears.

JS Exercise 28

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function groupAnagrams(words) {
  const groups = new Map();
  for (const word of words) {
    const key = [...word.toLowerCase()].sort().join("");
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(word);
  }
  return [...groups.values()];
}

Anagrams share the same letters, so sorting the letters gives every word in a group the same key. A Map keeps groups in first-seen order, and the whole thing runs in roughly O(n ยท k log k) for n words of length k.

Classic interview questions

These ten problems appear again and again in coding interviews. They are small, but each one teaches a technique: a stack, a Map for counting, a lookup table, recursion or a single pass with a running value. Try to say your plan out loud before you type, the way you would in an interview.

29. Balanced brackets (intermediate)

Write isBalanced(text) that returns true when every (, [ and { is closed by the right kind of bracket in the right order. Ignore all other characters.

JS Exercise 29

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function isBalanced(text) {
  const pairs = { ")": "(", "]": "[", "}": "{" };
  const stack = [];
  for (const char of text) {
    if ("([{".includes(char)) {
      stack.push(char);
    } else if (char in pairs) {
      if (stack.pop() !== pairs[char]) return false;
    }
  }
  return stack.length === 0;
}

Each opening bracket goes on a stack; each closing bracket must match the one on top. An empty stack at the end means nothing was left open. stack.pop() returns undefined on an empty stack, which never equals a bracket, so an extra closing bracket fails too.

30. Reverse the words (beginner)

Write reverseWords(sentence) that reverses the order of the words, not the letters. Extra spaces at the start, end or between words should disappear.

JS Exercise 30

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function reverseWords(sentence) {
  return sentence.trim().split(/\s+/).reverse().join(" ");
}

Splitting on the regular expression /\s+/ treats any run of whitespace as one separator. trim() first prevents empty strings at the edges.

31. All permutations (advanced)

Write permutations(text) that returns every ordering of the letters of a string with no repeated results, in the order a left-to-right search finds them.

JS Exercise 31

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function permutations(text) {
  if (text.length <= 1) return [text];
  const results = new Set();
  for (let i = 0; i < text.length; i++) {
    const rest = text.slice(0, i) + text.slice(i + 1);
    for (const tail of permutations(rest)) {
      results.add(text[i] + tail);
    }
  }
  return [...results];
}

Pick each letter as the first one, then recursively arrange the rest. A Set removes duplicates when the input repeats letters. The number of results grows as n!, so this is fine for a handful of letters and hopeless for twenty.

32. Pangram (beginner)

A pangram uses every letter of the English alphabet at least once. Write isPangram(text), ignoring case and any non-letters.

JS Exercise 32

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function isPangram(text) {
  const letters = new Set(text.toLowerCase().match(/[a-z]/g));
  return letters.size === 26;
}

match(/[a-z]/g) returns every letter, and a Set keeps one of each. If the text has no letters, match returns null, and new Set(null) is simply an empty set, so no special case is needed.

33. Isomorphic strings (intermediate)

Two strings are isomorphic if you can replace each character in the first with exactly one character to get the second, and no two different characters map to the same one. Write isIsomorphic(a, b).

JS Exercise 33

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function isIsomorphic(a, b) {
  if (a.length !== b.length) return false;
  const forward = new Map();
  const backward = new Map();
  for (let i = 0; i < a.length; i++) {
    const x = a[i];
    const y = b[i];
    if (forward.has(x) && forward.get(x) !== y) return false;
    if (backward.has(y) && backward.get(y) !== x) return false;
    forward.set(x, y);
    backward.set(y, x);
  }
  return true;
}

You need both directions: "ab" to "aa" passes the forward check (aโ†’a, bโ†’a) but fails the backward one, since a would have to come from both a and b.

34. Roman numerals (intermediate)

Write toRoman(number) for integers from 1 to 3999, and fromRoman(text) for the reverse.

JS Exercise 34

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const NUMERALS = [
  [1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
  [100, "C"], [90, "XC"], [50, "L"], [40, "XL"],
  [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"],
];

function toRoman(number) {
  let result = "";
  for (const [value, symbol] of NUMERALS) {
    while (number >= value) {
      result += symbol;
      number -= value;
    }
  }
  return result;
}

function fromRoman(text) {
  const values = Object.fromEntries(NUMERALS.filter(([, s]) => s.length === 1).map(([v, s]) => [s, v]));
  let total = 0;
  for (let i = 0; i < text.length; i++) {
    const current = values[text[i]];
    const next = values[text[i + 1]] ?? 0;
    total += current < next ? -current : current;
  }
  return total;
}

Including the subtractive pairs (CM, IV, ...) in the table lets toRoman stay a simple greedy loop. Going back, a symbol smaller than the one after it is subtracted (I before X), otherwise added.

35. First non-repeated character (intermediate)

Write firstUnique(text) that returns the first character that appears exactly once, or null if there is none.

JS Exercise 35

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function firstUnique(text) {
  const counts = new Map();
  for (const char of text) {
    counts.set(char, (counts.get(char) ?? 0) + 1);
  }
  for (const char of text) {
    if (counts.get(char) === 1) return char;
  }
  return null;
}

Two passes: count every character, then walk the text again in order and return the first with a count of 1. A Map keeps lookups fast, so the whole function is O(n). (A common mistake is to use Object.keys order on the counts; that order is not the order of the text for numeric characters.)

36. Biggest profit (intermediate)

Given a list of prices by day, write maxDifference(prices) that returns the largest value of later - earlier, where the later price comes after the earlier one. Return 0 if prices only fall.

JS Exercise 36

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function maxDifference(prices) {
  let lowest = Infinity;
  let best = 0;
  for (const price of prices) {
    lowest = Math.min(lowest, price);
    best = Math.max(best, price - lowest);
  }
  return best;
}

A single pass is enough: remember the lowest price seen so far, and at each step ask "if I sold today, what would my profit be?". Comparing every pair would work too, but takes O(nยฒ) time.

37. Union and intersection (beginner)

Write union(a, b) and intersection(a, b) for two arrays of numbers. Results should have no duplicates and keep first-seen order.

JS Exercise 37

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function union(a, b) {
  return [...new Set([...a, ...b])];
}

function intersection(a, b) {
  const inB = new Set(b);
  return [...new Set(a)].filter((value) => inB.has(value));
}

A Set removes duplicates and remembers insertion order. For the intersection, turning b into a set makes each has() check constant time, so the function is linear instead of quadratic.

38. Number to binary string (beginner)

Write toBinary(n) that converts a non-negative integer to a binary string without using toString(2), and fromBinary(text) for the reverse without parseInt.

JS Exercise 38

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function toBinary(n) {
  if (n === 0) return "0";
  let bits = "";
  while (n > 0) {
    bits = (n % 2) + bits;
    n = Math.floor(n / 2);
  }
  return bits;
}

function fromBinary(text) {
  let value = 0;
  for (const bit of text) {
    value = value * 2 + Number(bit);
  }
  return value;
}

Repeatedly dividing by 2 produces the bits from right to left, so each new bit is put in front. Going back, every new bit doubles what you have so far and adds itself. In real code, n.toString(2) and parseInt(text, 2) do the same.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In the retry solution, why is it return await task(); instead of return task(); inside the try block?

    return task() hands back the promise immediately, so its rejection happens after the try/catch is finished. await makes the rejection throw inside the try block.
  2. 2. Why does the memoize solution use cache.has(arg) rather than if (cache.get(arg))?

    A falsy cached value would look like a cache miss. has() answers whether the key exists, whatever its value.
  3. 3. Which built-in call does the same job as the flattenDeep exercise?

    flat() without an argument only flattens one level, and so does flatMap. Passing Infinity flattens every level.

Summary

  • Practice by topic: basics, strings, functions, arrays, objects, classes, async code, the DOM, algorithms and classic interview questions.
  • Attempt each exercise before opening the solution, and type solutions out yourself.
  • Common winning patterns: guard clauses, reduce() for building results, Map/Set for lookups, closures for private state.
  • For async exercises, remember that await in a for loop runs steps one by one, and return await inside try catches rejections.
  • When you finish, revisit the exercises that took longest. Solving them again a week later locks the skill in.

Next: JavaScript Interview Questions โ€” 36 common questions with concise answers.