100 Javascript practice problems with solutions

Feeling like you’re stuck in tutorial limbo—watching video after video but still afraid to write your own JavaScript? That’s a tough spot, and the truth is, watching can only take you so far. Real growth comes from hands-on practice, where you type the code, fix the errors, and finally watch things click. This post is built exactly for that breakthrough moment.

We’ve put together 100 JavaScript practice problems with clear, step-by-step solutions so you can move from knowing about code to actually writing it with confidence. You’ll work through simple fundamentals like variables, loops, arrays, and functions, then push into exciting challenges involving DOM manipulation, events, API calls, async/await, and more. Each problem is described in plain, friendly language, letting you try it yourself first before checking the answer and truly understanding the why.

Why is practice so important? Because programming is a skill—just like playing an instrument or a sport. Every problem you solve strengthens your logic, builds muscle memory, and makes common patterns feel natural. Practice turns shaky knowledge into real, interview-ready ability. It’s what separates people who understand the syntax from developers who can build things and solve problems on the spot.

Whether you’re just starting to fall in love with web development or you’re gearing up for a front-end coding interview, these JavaScript coding exercises will help you feel prepared, capable, and genuinely proud of your progress. Pick a problem, start coding, and experience that amazing “I’m really getting this!” moment. Your journey to mastering JavaScript starts today.

Also try it: 100 TypeScript practice problems with solutions

1. Hello World

Write a function hello() that returns the string “Hello, World!”.

js

function hello() {
  return "Hello, World!";
}

2. Sum of Two Numbers

Write a function sum(a, b) that returns the sum of two numbers.

js

function sum(a, b) {
  return a + b;
}

3. Check Even or Odd

Write a function isEven(num) that returns true if the number is even, false otherwise.

js

function isEven(num) {
  return num % 2 === 0;
}

4. Maximum of Three Numbers

Write a function maxOfThree(a, b, c) that returns the largest of three numbers.

js

function maxOfThree(a, b, c) {
  return Math.max(a, b, c);
}

5. Reverse a String

Write a function reverseString(str) that returns the reversed string.

js

function reverseString(str) {
  return str.split('').reverse().join('');
}

6. Factorial of a Number

Write a function factorial(n) that returns the factorial of n (n!).

js

function factorial(n) {
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
}

7. Check Palindrome (String)

Write a function isPalindrome(str) that checks if a string is a palindrome (ignoring spaces, punctuation, and case).

js

function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === cleaned.split('').reverse().join('');
}

8. Find the Longest Word in a Sentence

Write a function longestWord(sentence) that returns the longest word in a sentence.

js

function longestWord(sentence) {
  const words = sentence.split(' ');
  return words.reduce((longest, current) => current.length > longest.length ? current : longest, '');
}

9. Capitalize First Letter of Each Word

Write a function capitalizeWords(str) that capitalizes the first letter of every word.

js

function capitalizeWords(str) {
  return str.replace(/\b\w/g, char => char.toUpperCase());
}

10. Count Vowels

Write a function countVowels(str) that counts the number of vowels (a, e, i, o, u) in a string.

js

function countVowels(str) {
  const vowels = str.match(/[aeiou]/gi);
  return vowels ? vowels.length : 0;
}

11. Sum of Array Elements

Write a function sumArray(arr) that returns the sum of all numbers in an array.

js

function sumArray(arr) {
  return arr.reduce((sum, num) => sum + num, 0);
}

12. Find the Largest Number in an Array

Write a function maxInArray(arr) that returns the maximum number in an array.

js

function maxInArray(arr) {
  return Math.max(...arr);
}

13. Filter Out Negative Numbers

Write a function filterNegative(arr) that returns a new array with all negative numbers removed.

js

function filterNegative(arr) {
  return arr.filter(num => num >= 0);
}

14. Remove Duplicates from Array

Write a function removeDuplicates(arr) that returns a new array without duplicates.

js

function removeDuplicates(arr) {
  return [...new Set(arr)];
}

15. Merge Two Arrays and Sort

Write a function mergeAndSort(arr1, arr2) that merges two arrays and sorts them in ascending order.

js

function mergeAndSort(arr1, arr2) {
  return [...arr1, ...arr2].sort((a, b) => a - b);
}

16. Count Occurrences of an Element in an Array

Write a function countOccurrences(arr, val) that counts how many times val appears.

js

function countOccurrences(arr, val) {
  return arr.filter(item => item === val).length;
}

17. Chunk Array into Groups

Write a function chunkArray(arr, size) that splits an array into groups of length size.

js

function chunkArray(arr, size) {
  const chunks = [];
  for (let i = 0; i < arr.length; i += size) {
    chunks.push(arr.slice(i, i + size));
  }
  return chunks;
}

18. Flatten a Nested Array (One Level)

Write a function flatten(arr) that flattens a 2D array into a single array.

js

function flatten(arr) {
  return arr.flat();
}

19. Find the Intersection of Two Arrays

Write a function arrayIntersection(arr1, arr2) that returns elements present in both arrays.

js

function arrayIntersection(arr1, arr2) {
  return arr1.filter(value => arr2.includes(value));
}

20. Compute the Average of an Array of Numbers

Write a function average(arr) that returns the average value.

js

function average(arr) {
  return arr.reduce((sum, val) => sum + val, 0) / arr.length;
}

21. Generate Fibonacci Sequence up to N Terms

Write a function fibonacci(n) that returns an array of the first n Fibonacci numbers.

js

function fibonacci(n) {
  const fib = [0, 1];
  for (let i = 2; i < n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
  }
  return fib.slice(0, n);
}

22. Check if a Number is Prime

Write a function isPrime(num) that returns true for prime numbers, false otherwise.

js

function isPrime(num) {
  if (num < 2) return false;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return true;
}

23. Convert Celsius to Fahrenheit

Write a function celsiusToFahrenheit(celsius) and its inverse fahrenheitToCelsius.

js

function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}
function fahrenheitToCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5/9;
}

24. FizzBuzz

Write a function fizzBuzz(n) that prints numbers 1..n, but for multiples of 3 print “Fizz”, for 5 print “Buzz”, for both print “FizzBuzz”.

js

function fizzBuzz(n) {
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i % 3 === 0) console.log("Fizz");
    else if (i % 5 === 0) console.log("Buzz");
    else console.log(i);
  }
}

25. Find the Missing Number in a Given Array of 1 to N

Write a function missingNumber(arr, n) that finds the missing number from an array containing numbers 1..n with one missing.

js

function missingNumber(arr, n) {
  const total = (n * (n + 1)) / 2;
  const sum = arr.reduce((acc, cur) => acc + cur, 0);
  return total - sum;
}

26. Calculate the Sum of Digits of a Number

Write a function sumOfDigits(num) that sums all digits of a positive integer.

js

function sumOfDigits(num) {
  return String(num).split('').reduce((sum, digit) => sum + Number(digit), 0);
}

27. Convert a Number to Roman Numerals (up to 3999)

Write a function toRoman(num) that converts an integer to a Roman numeral.

js

function toRoman(num) {
  const values = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
  const symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
  let roman = '';
  for (let i = 0; i < values.length; i++) {
    while (num >= values[i]) {
      roman += symbols[i];
      num -= values[i];
    }
  }
  return roman;
}

28. Convert Roman Numeral to Integer

Write a function fromRoman(str) that converts a Roman numeral to an integer.

js

function fromRoman(s) {
  const map = { I:1, V:5, X:10, L:50, C:100, D:500, M:1000 };
  let result = 0;
  for (let i = 0; i < s.length; i++) {
    const curr = map[s[i]];
    const next = map[s[i+1]];
    if (next && curr < next) result -= curr;
    else result += curr;
  }
  return result;
}

29. Deep Clone an Object

Write a function deepClone(obj) that returns a deep copy of an object.

js

function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}
// Note: Does not handle functions, undefined, etc. For a more robust solution:
function deepCloneAdvanced(obj, hash = new WeakMap()) {
  if (Object(obj) !== obj) return obj;
  if (hash.has(obj)) return hash.get(obj);
  const result = Array.isArray(obj) ? [] : {};
  hash.set(obj, result);
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) result[key] = deepCloneAdvanced(obj[key], hash);
  }
  return result;
}

30. Merge Two Objects

Write a function mergeObjects(obj1, obj2) that merges two objects (shallow, second overwrites).

js

function mergeObjects(obj1, obj2) {
  return { ...obj1, ...obj2 };
}

31. Check if Two Objects are Deeply Equal

Write a function deepEqual(a, b) that compares two objects/values deeply.

js

function deepEqual(a, b) {
  if (a === b) return true;
  if (a == null || typeof a != "object" || b == null || typeof b != "object") return false;
  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  for (let key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  }
  return true;
}

32. Count Properties of an Object

Write a function countProperties(obj) that returns the number of own enumerable properties.

js

function countProperties(obj) {
  return Object.keys(obj).length;
}

33. Convert Object to Query String

Write a function toQueryString(obj) that converts an object to a URL query string (e.g., ?name=John&age=30).

js

function toQueryString(obj) {
  return Object.entries(obj).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&');
}

34. Invert Keys and Values of an Object

Write a function invertObject(obj) that swaps keys and values.

js

function invertObject(obj) {
  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
}

35. Flatten a Deeply Nested Array (any depth)

Write a function deepFlatten(arr) that flattens all nested arrays.

js

function deepFlatten(arr) {
  return arr.flat(Infinity);
}

36. Rotate Array to the Right by K Steps

Write a function rotateArray(arr, k) that rotates an array to the right by k steps.

js

function rotateArray(arr, k) {
  k %= arr.length;
  return [...arr.slice(-k), ...arr.slice(0, -k)];
}

37. Find the First Non-Repeating Character in a String

Write a function firstNonRepeating(str) that returns the first character that does not repeat.

js

function firstNonRepeating(str) {
  const freq = {};
  for (let ch of str) freq[ch] = (freq[ch] || 0) + 1;
  for (let ch of str) if (freq[ch] === 1) return ch;
  return null;
}

38. Check if Two Strings are Anagrams

Write a function areAnagrams(str1, str2) that returns true if the strings are anagrams (case-insensitive, ignoring spaces).

js

function areAnagrams(str1, str2) {
  const normalize = str => str.toLowerCase().replace(/[^a-z]/g, '').split('').sort().join('');
  return normalize(str1) === normalize(str2);
}

39. Truncate a String with Ellipsis

Write a function truncate(str, maxLength) that truncates the string to maxLength and adds “…” if truncated.

js

function truncate(str, maxLength) {
  return str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
}

40. Repeat a String N Times

Write a function repeatString(str, count) that returns the string repeated count times.

js

function repeatString(str, count) {
  return str.repeat(count);
}

41. Generate Random Number Between Min and Max (Inclusive)

Write a function randomInRange(min, max) that returns a random integer.

js

function randomInRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

42. Get Current Date in YYYY-MM-DD Format

Write a function getCurrentDate() that returns today’s date in that format.

js

function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

43. Check if a String is a Valid Email (Basic)

Write a function isValidEmail(email) using a simple regex.

js

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

44. Find the Difference Between Two Arrays

Write a function arrayDifference(arr1, arr2) that returns elements in arr1 not in arr2.

js

function arrayDifference(arr1, arr2) {
  return arr1.filter(x => !arr2.includes(x));
}

45. Find the Symmetric Difference of Two Arrays

Write a function symmetricDifference(arr1, arr2) that returns elements in either array but not both.

js

function symmetricDifference(arr1, arr2) {
  return [...new Set([...arr1.filter(x => !arr2.includes(x)), ...arr2.filter(x => !arr1.includes(x))])];
}

46. Convert Snake Case to Camel Case

Write a function snakeToCamel(str) that converts “hello_world” to “helloWorld”.

js

function snakeToCamel(str) {
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

47. Convert Camel Case to Snake Case

Write a function camelToSnake(str) that converts “helloWorld” to “hello_world”.

js

function camelToSnake(str) {
  return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
}

48. Pad a String to a Certain Length with a Character (Left and Right)

Write a function padString(str, length, char = ' ') that pads both sides evenly.

js

function padString(str, length, char = ' ') {
  const totalPad = length - str.length;
  const leftPad = Math.floor(totalPad / 2);
  const rightPad = totalPad - leftPad;
  return char.repeat(leftPad) + str + char.repeat(rightPad);
}

49. Check if All Elements in an Array Satisfy a Condition

Write a function allPositive(arr) that returns true if all numbers are positive.

js

function allPositive(arr) {
  return arr.every(num => num > 0);
}

50. Find the Index of the First Occurrence in an Array

Write a function indexOf(arr, element) without using built‑in indexOf.

js

function indexOf(arr, element) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === element) return i;
  }
  return -1;
}

51. Implement Memoization for a Function

Write a higher‑order function memoize(fn) that caches results.

js

function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

52. Implement Debounce

Write a function debounce(fn, delay) that delays invocation until after delay milliseconds of inactivity.

js

function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

53. Implement Throttle

Write a function throttle(fn, limit) that ensures function is called at most once every limit ms.

js

function throttle(fn, limit) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

54. Implement a Simple Event Emitter

Write a class EventEmitter with onemit, and off methods.

js

class EventEmitter {
  constructor() {
    this.events = {};
  }
  on(event, listener) {
    if (!this.events[event]) this.events[event] = [];
    this.events[event].push(listener);
  }
  emit(event, ...args) {
    (this.events[event] || []).forEach(listener => listener(...args));
  }
  off(event, listener) {
    if (!this.events[event]) return;
    this.events[event] = this.events[event].filter(l => l !== listener);
  }
}

55. Implement Array.prototype.myMap

Write a polyfill for Array.map.

js

Array.prototype.myMap = function(callback, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(callback.call(thisArg, this[i], i, this));
  }
  return result;
};

56. Implement Array.prototype.myFilter

js

Array.prototype.myFilter = function(callback, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (callback.call(thisArg, this[i], i, this)) result.push(this[i]);
  }
  return result;
};

57. Implement Array.prototype.myReduce

js

Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = initialValue !== undefined ? initialValue : this[0];
  let startIndex = initialValue !== undefined ? 0 : 1;
  for (let i = startIndex; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }
  return accumulator;
};

58. Implement Function.prototype.myBind

js

Function.prototype.myBind = function(context, ...boundArgs) {
  const fn = this;
  return function(...args) {
    return fn.apply(context, [...boundArgs, ...args]);
  };
};

59. Implement Object.create Polyfill

js

function myObjectCreate(proto) {
  function F() {}
  F.prototype = proto;
  return new F();
}

60. Implement instanceof Operator

Write a function myInstanceof(obj, constructor) that mimics instanceof.

js

function myInstanceof(obj, constructor) {
  let proto = Object.getPrototypeOf(obj);
  while (proto !== null) {
    if (proto === constructor.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

61. Write a Function that Calls a Callback on Each Element (forEach)

Implement forEach without the built‑in.

js

function forEach(arr, callback) {
  for (let i = 0; i < arr.length; i++) {
    callback(arr[i], i, arr);
  }
}

62. Group Array of Objects by a Property

Write a function groupBy(arr, property) that returns an object with keys as property values.

js

function groupBy(arr, property) {
  return arr.reduce((groups, item) => {
    const key = item[property];
    (groups[key] = groups[key] || []).push(item);
    return groups;
  }, {});
}

63. Sort Array of Objects by a Field

Write a function sortBy(arr, field) that sorts ascending by a field.

js

function sortBy(arr, field) {
  return [...arr].sort((a, b) => a[field] > b[field] ? 1 : -1);
}

64. Shuffle an Array (Fisher‑Yates)

Write a function shuffle(arr) that returns a new shuffled array.

js

function shuffle(arr) {
  const shuffled = [...arr];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

65. Convert Object to Array of Key‑Value Pairs

Write a function entries(obj) that returns [['key', value], ...].

js

function entries(obj) {
  return Object.entries(obj);
}

66. Check if a String Contains All Letters of Another String

Write a function containsAllLetters(str, letters) that checks if str contains all characters of letters (with multiplicity).

js

function containsAllLetters(str, letters) {
  const map = {};
  for (let ch of str) map[ch] = (map[ch] || 0) + 1;
  for (let ch of letters) {
    if (!map[ch]) return false;
    map[ch]--;
  }
  return true;
}

67. Find the Most Frequent Element in an Array

Write a function mostFrequent(arr) that returns the element with highest frequency.

js

function mostFrequent(arr) {
  const freq = {};
  arr.forEach(val => freq[val] = (freq[val] || 0) + 1);
  return Object.keys(freq).reduce((a, b) => freq[a] > freq[b] ? a : b);
}

Also try it: 100 Dart practice problems with solutions

68. Compress a String with Character Counts

Write a function compressString(str) that returns “a2b3c1” for “aabbbc”.

js

function compressString(str) {
  if (!str) return '';
  let result = '';
  let count = 1;
  for (let i = 1; i < str.length; i++) {
    if (str[i] === str[i-1]) count++;
    else {
      result += str[i-1] + count;
      count = 1;
    }
  }
  result += str[str.length-1] + count;
  return result;
}

69. Decompress a String

Write a function decompressString(str) that reverses the above, e.g., “a2b3c1” → “aabbbc”.

js

function decompressString(str) {
  let result = '';
  for (let i = 0; i < str.length; i += 2) {
    const char = str[i];
    const count = parseInt(str[i+1]);
    result += char.repeat(count);
  }
  return result;
}

70. Validate a Balanced Parentheses String

Write a function isBalanced(str) that returns true if brackets (){}[] are balanced.

js

function isBalanced(str) {
  const stack = [];
  const pairs = { '(': ')', '{': '}', '[': ']' };
  for (let ch of str) {
    if (pairs[ch]) stack.push(ch);
    else if (Object.values(pairs).includes(ch)) {
      if (pairs[stack.pop()] !== ch) return false;
    }
  }
  return stack.length === 0;
}

71. Implement a Simple Promise

Write a class MyPromise with basic then and catch (simplified).

js

class MyPromise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.callbacks = [];
    const resolve = (val) => {
      if (this.state !== 'pending') return;
      this.state = 'fulfilled';
      this.value = val;
      this.callbacks.forEach(cb => cb.onFulfilled(val));
    };
    const reject = (reason) => {
      if (this.state !== 'pending') return;
      this.state = 'rejected';
      this.value = reason;
      this.callbacks.forEach(cb => cb.onRejected(reason));
    };
    try { executor(resolve, reject); } catch(e) { reject(e); }
  }
  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      const handler = () => {
        try {
          if (this.state === 'fulfilled') resolve(onFulfilled ? onFulfilled(this.value) : this.value);
          else if (this.state === 'rejected') reject(onRejected ? onRejected(this.value) : this.value);
        } catch(e) { reject(e); }
      };
      if (this.state !== 'pending') handler();
      else this.callbacks.push({ onFulfilled: handler, onRejected: handler });
    });
  }
  catch(onRejected) { return this.then(null, onRejected); }
}

72. Implement Promise.all

Write a function promiseAll(promises) that mimics Promise.all.

js

function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let completed = 0;
    promises.forEach((promise, index) => {
      Promise.resolve(promise)
        .then(value => {
          results[index] = value;
          completed++;
          if (completed === promises.length) resolve(results);
        })
        .catch(reject);
    });
  });
}

73. Implement Promise.race

js

function promiseRace(promises) {
  return new Promise((resolve, reject) => {
    promises.forEach(promise => Promise.resolve(promise).then(resolve, reject));
  });
}

74. Sleep Function Using Promise

Write a function sleep(ms) that resolves after ms milliseconds.

js

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

75. Chain Multiple Asynchronous Operations

Write a function fetchData that simulates an API call and chain another call.

js

function fakeFetch(url) {
  return new Promise(resolve => {
    setTimeout(() => resolve(`Data from ${url}`), 1000);
  });
}
async function chainedFetch() {
  const data1 = await fakeFetch('/api/1');
  const data2 = await fakeFetch('/api/2');
  return [data1, data2];
}

76. Using async/await with Error Handling

Rewrite a promise chain using async/await and try/catch.

js

async function processData() {
  try {
    const response = await fetch('https://api.example.com');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch failed:', error);
  }
}

77. Convert Callback-Based Function to Promise

Given readFile(path, callback), create readFilePromise(path).

js

const fs = require('fs');
function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

78. Run Multiple Promises Sequentially

Write a function sequentialPromises(tasks) that executes async tasks in order.

js

async function sequentialPromises(tasks) {
  const results = [];
  for (let task of tasks) {
    results.push(await task());
  }
  return results;
}

79. Limit Concurrent Async Operations

Write a function asyncPool(limit, tasks) that runs at most limit tasks concurrently.

js

async function asyncPool(limit, tasks) {
  const results = [];
  const executing = [];
  for (const [i, task] of tasks.entries()) {
    const p = Promise.resolve().then(() => task());
    results[i] = p;
    if (limit <= tasks.length) {
      const e = p.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);
      if (executing.length >= limit) await Promise.race(executing);
    }
  }
  return Promise.all(results);
}

80. Retry a Promise with Exponential Backoff

Write a function retryWithBackoff(fn, retries, delay).

js

function retryWithBackoff(fn, retries, delay = 100) {
  return new Promise((resolve, reject) => {
    const attempt = (n) => {
      fn().then(resolve).catch(() => {
        if (n === 0) return reject(new Error('Max retries exceeded'));
        setTimeout(() => attempt(n - 1), delay * Math.pow(2, retries - n));
      });
    };
    attempt(retries);
  });
}

81. Bind this with Arrow Function vs Regular

Explain output of the following:

js

const obj = {
  name: 'Alice',
  greet: function() { console.log(this.name); },
  greetArrow: () => { console.log(this.name); }
};
obj.greet(); // Alice
const greet2 = obj.greet; greet2(); // undefined (non-strict)
obj.greetArrow(); // undefined (window/global)

82. Create a Counter Using Closures

Write a function createCounter() that returns an object with incrementdecrement, and value methods.

js

function createCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count
  };
}

83. Create a Function that Logs a String with a Delay

Write a function delayedLog(msg, delay).

js

function delayedLog(msg, delay) {
  setTimeout(() => console.log(msg), delay);
}

84. Implement a Simple Pub/Sub (Observer) Pattern

Write an Observer class with subscribeunsubscribenotify.

js

class Observer {
  constructor() { this.subscribers = []; }
  subscribe(fn) { this.subscribers.push(fn); }
  unsubscribe(fn) { this.subscribers = this.subscribers.filter(sub => sub !== fn); }
  notify(data) { this.subscribers.forEach(fn => fn(data)); }
}

85. Convert Object to JSON String Manually (Simplified)

Write a function myJSONStringify(obj) that handles primitives, arrays, and objects without circular references.

js

function myJSONStringify(obj) {
  if (obj === null || typeof obj !== 'object') {
    return typeof obj === 'string' ? `"${obj}"` : String(obj);
  }
  if (Array.isArray(obj)) {
    return '[' + obj.map(item => myJSONStringify(item)).join(',') + ']';
  }
  const entries = Object.entries(obj).map(([key, value]) => `"${key}":${myJSONStringify(value)}`);
  return '{' + entries.join(',') + '}';
}

Also try it: 100 TypeScript practice problems with solutions

86. Create a Function with a Chainable API

Write a calculator that returns an object with methods addsubtractmultiplydivide, and result that chain.

js

function calculator(initial = 0) {
  let value = initial;
  return {
    add: (n) => { value += n; return this; },
    subtract: (n) => { value -= n; return this; },
    multiply: (n) => { value *= n; return this; },
    divide: (n) => { value /= n; return this; },
    result: () => value
  };
}

87. Extract All Values from a Nested Object (Recursively)

Write a function getAllValues(obj) that returns an array of all leaf values.

js

function getAllValues(obj) {
  let values = [];
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      const val = obj[key];
      if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
        values = values.concat(getAllValues(val));
      } else {
        values.push(val);
      }
    }
  }
  return values;
}

88. Find the GCD of Two Numbers

Write a function gcd(a, b) using Euclidean algorithm.

js

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

89. Find the LCM of Two Numbers

Write a function lcm(a, b).

js

function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

90. Generate All Combinations of a String

Write a function stringCombinations(str) that returns all subsets of the characters (e.g., “ab” → [“a”,”b”,”ab”]).

js

function stringCombinations(str) {
  const result = [];
  const combine = (prefix, start) => {
    for (let i = start; i < str.length; i++) {
      const newPrefix = prefix + str[i];
      result.push(newPrefix);
      combine(newPrefix, i + 1);
    }
  };
  combine('', 0);
  return result;
}

91. Flatten Object Keys with Dot Notation

Write a function flattenObject(obj, prefix = '') that returns a single-level object with dot-separated keys.

js

function flattenObject(obj, prefix = '') {
  return Object.keys(obj).reduce((acc, key) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      Object.assign(acc, flattenObject(obj[key], pre + key));
    } else {
      acc[pre + key] = obj[key];
    }
    return acc;
  }, {});
}

92. Unflatten Object (from Dot Notation)

Write a function unflattenObject(obj) that reconstructs a nested object from dot‑notation keys.

js

function unflattenObject(obj) {
  return Object.keys(obj).reduce((result, path) => {
    const keys = path.split('.');
    keys.reduce((acc, key, i) => {
      if (i === keys.length - 1) acc[key] = obj[path];
      else acc[key] = acc[key] || {};
      return acc[key];
    }, result);
    return result;
  }, {});
}

93. Implement a Basic Templating Function

Write a function template(str, data) that replaces {{ key }} with values from data.

js

function template(str, data) {
  return str.replace(/{{\s*([\w.]+)\s*}}/g, (_, key) => {
    return key.split('.').reduce((obj, k) => obj?.[k], data) ?? '';
  });
}

94. Find the Longest Palindromic Substring

Write a function longestPalindrome(s) that returns the longest substring that is a palindrome.

js

function longestPalindrome(s) {
  let start = 0, maxLen = 1;
  for (let i = 0; i < s.length; i++) {
    for (let j = i + 1; j < s.length; j++) {
      const sub = s.substring(i, j + 1);
      if (sub === sub.split('').reverse().join('') && sub.length > maxLen) {
        start = i;
        maxLen = sub.length;
      }
    }
  }
  return s.substring(start, start + maxLen);
}

(Note: more efficient O(n²) dynamic programming solution exists.)

95. Convert a Number to Words (e.g., 123 → “one hundred twenty three”)

Write a basic function numToWords(num) for numbers 0‑999.

js

function numToWords(num) {
  const ones = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
  const tens = ['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'];
  if (num === 0) return 'zero';
  const convert = (n) => {
    if (n < 20) return ones[n];
    const digit = n % 10;
    return tens[Math.floor(n / 10)] + (digit ? ' ' + ones[digit] : '');
  };
  let result = '';
  if (Math.floor(num / 100) > 0) {
    result += ones[Math.floor(num / 100)] + ' hundred';
    num %= 100;
    if (num > 0) result += ' ';
  }
  if (num > 0) result += convert(num);
  return result;
}

96. Implement a Simple “Typewriter” Effect (Console)

Write a function typeEffect(text) that prints characters one by one with a delay.

js

function typeEffect(text) {
  let i = 0;
  const interval = setInterval(() => {
    if (i < text.length) {
      process.stdout.write(text[i]);
      i++;
    } else {
      clearInterval(interval);
      console.log();
    }
  }, 100);
}

97. Parse a Cookie String into an Object

Write a function parseCookies(cookieString) that returns an object with cookie key‑values.

js

function parseCookies(str) {
  return str.split(';').reduce((cookies, pair) => {
    const [key, val] = pair.trim().split('=');
    cookies[key] = decodeURIComponent(val);
    return cookies;
  }, {});
}

98. Check if an Object is Empty

Write a function isEmpty(obj) that returns true if object has no own enumerable properties.

js

function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}

99. Currying a Function

Write a generic curry(func) that allows partial application.

js

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    }
    return function(...args2) {
      return curried.apply(this, args.concat(args2));
    };
  };
}

100. Pipe / Compose Functions

Write a function pipe(...fns) that composes functions left‑to‑right.

js

function pipe(...fns) {
  return (value) => fns.reduce((acc, fn) => fn(acc), value);
}
// Example: const add5 = n => n + 5; const double = n => n * 2; const pipeline = pipe(add5, double); pipeline(10) // 30

Also try it: 100 Java practice problems with solutions

Final Thoughts

And just like that — 100 JavaScript problems are behind you. Take a breath. Feel that quiet pride. You didn’t just watch or scroll — you showed up, struggled a little, and grew a lot. That’s the real stuff. Every line you wrote turned fear into familiarity, confusion into quiet confidence. Keep going. Come back whenever doubt creeps in. You’re a JavaScript developer now — and you’ve earned that title. Happy coding, from the heart.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top