JavaScript Mostly Asked Interview Practice Questions

 


1. Palindrome Check

Write a function to check if a string is a palindrome.


function isPalindrome(str) { let reversed = str.split('').reverse().join(''); return str === reversed; } console.log(isPalindrome('racecar')); // true console.log(isPalindrome('hello')); // false

2. Anagram Check

Write a function that checks if two strings are anagrams of each other.


function isAnagram(str1, str2) { let normalize = str => str.toLowerCase().replace(/[\W_]+/g, '').split('').sort().join(''); return normalize(str1) === normalize(str2); } console.log(isAnagram('listen', 'silent')); // true console.log(isAnagram('hello', 'world')); // false

3. FizzBuzz

Write a function that prints the numbers from 1 to 100, but for multiples of 3, print "Fizz", for multiples of 5 print "Buzz", and for multiples of both 3 and 5 print "FizzBuzz".


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

4. Sum of Array

Write a function to return the sum of all elements in an array.


function sumArray(arr) { return arr.reduce((sum, num) => sum + num, 0); } console.log(sumArray([1, 2, 3, 4])); // 10

5. Find Maximum

Write a function that returns the maximum number in an array.


function findMax(arr) { return Math.max(...arr); } console.log(findMax([3, 5, 7, 2, 8])); // 8

6. Remove Duplicates

Write a function that removes duplicates from an array.


function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]

7. Flatten an Array

Write a function to flatten an array of arrays into a single array.


function flattenArray(arr) { return arr.flat(); } console.log(flattenArray([[1, 2], [3, 4], [5]])); // [1, 2, 3, 4, 5]

8. Find Missing Number

Write a function that finds the missing number in an array of consecutive numbers.


function findMissingNumber(arr) { let n = arr.length + 1; let totalSum = (n * (n + 1)) / 2; let arrSum = arr.reduce((sum, num) => sum + num, 0); return totalSum - arrSum; } console.log(findMissingNumber([1, 2, 4, 5, 6])); // 3

9. Factorial

Write a function to calculate the factorial of a number.


function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); } console.log(factorial(5)); // 120

10. Debounce Function

Write a debounce function in JavaScript.


function debounce(func, delay) { let timeoutId; return function (...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } const logMessage = debounce(() => console.log('Hello'), 1000); logMessage(); // Will log "Hello" after 1 second if not called again within that time.


11. Reverse a String

Write a function to reverse a given string without using the built-in reverse method.


function reverseString(str) { let reversed = ''; for (let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } return reversed; } console.log(reverseString('hello')); // 'olleh'

12. Capitalize First Letter of Each Word

Write a function to capitalize the first letter of each word in a sentence.


function capitalizeWords(str) { return str.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' '); } console.log(capitalizeWords('hello world')); // 'Hello World'

13. Find Second Largest Element

Write a function to find the second largest number in an array.


function secondLargest(arr) { let uniqueArr = [...new Set(arr)]; uniqueArr.sort((a, b) => b - a); return uniqueArr[1]; } console.log(secondLargest([1, 5, 3, 9, 7])); // 7

14. Sum of Digits

Write a function to compute the sum of the digits of a number.


function sumOfDigits(num) { return num.toString().split('').reduce((sum, digit) => sum + parseInt(digit), 0); } console.log(sumOfDigits(1234)); // 10

15. Count Vowels and Consonants

Write a function to count the number of vowels and consonants in a string.


function countVowelsAndConsonants(str) { let vowels = 'aeiouAEIOU'; let vowelCount = 0; let consonantCount = 0; for (let char of str) { if (vowels.includes(char)) { vowelCount++; } else if (/[a-zA-Z]/.test(char)) { consonantCount++; } } return { vowels: vowelCount, consonants: consonantCount }; } console.log(countVowelsAndConsonants('hello world')); // { vowels: 3, consonants: 7 }

16. Sum of Even Numbers

Write a function that returns the sum of all even numbers in an array.


function sumEvenNumbers(arr) { return arr.filter(num => num % 2 === 0).reduce((sum, num) => sum + num, 0); } console.log(sumEvenNumbers([1, 2, 3, 4, 5, 6])); // 12

17. Check for Duplicates

Write a function that checks if an array contains any duplicate elements.


function hasDuplicates(arr) { return new Set(arr).size !== arr.length; } console.log(hasDuplicates([1, 2, 3, 4, 5])); // false console.log(hasDuplicates([1, 2, 3, 4, 4])); // true

18. Merge and Sort Two Arrays

Write a function to merge two arrays and return a sorted array.


function mergeAndSort(arr1, arr2) { return [...arr1, ...arr2].sort((a, b) => a - b); } console.log(mergeAndSort([3, 1, 4], [6, 5, 2])); // [1, 2, 3, 4, 5, 6]

19. Generate Fibonacci Sequence

Write a function to generate the Fibonacci sequence up to n numbers.


function fibonacci(n) { let fib = [0, 1]; for (let i = 2; i < n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } return fib; } console.log(fibonacci(6)); // [0, 1, 1, 2, 3, 5]

20. Find Intersection of Two Arrays

Write a function that finds the intersection (common elements) of two arrays.


function arrayIntersection(arr1, arr2) { return arr1.filter(item => arr2.includes(item)); } console.log(arrayIntersection([1, 2, 3], [2, 3, 4])); // [2, 3]

21. Group Elements by Frequency

Write a function that groups elements of an array by their frequency.


function groupByFrequency(arr) { let frequencyMap = {}; arr.forEach(item => frequencyMap[item] = (frequencyMap[item] || 0) + 1); return frequencyMap; } console.log(groupByFrequency([1, 2, 2, 3, 3, 3])); // {1: 1, 2: 2, 3: 3}

22. Remove Null and Undefined Values

Write a function to remove null and undefined values from an array.


function removeNullUndefined(arr) { return arr.filter(item => item !== null && item !== undefined); } console.log(removeNullUndefined([1, null, 2, undefined, 3])); // [1, 2, 3]

23. Find Longest Word

Write a function to find the longest word in a sentence.


function findLongestWord(sentence) { let words = sentence.split(' '); let longestWord = words.reduce((longest, currentWord) => currentWord.length > longest.length ? currentWord : longest, ''); return longestWord; } console.log(findLongestWord('The quick brown fox jumped over the lazy dog')); // 'jumped'

24. Binary Search Algorithm

Write a function to implement binary search for a sorted array.


function binarySearch(arr, target) { let left = 0, right = arr.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (arr[mid] === target) return mid; else if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 4)); // 3 console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 10)); // -1

25. Throttle Function

Write a throttle function that limits the execution of a function to once every n milliseconds.


function throttle(func, delay) { let lastCall = 0; return function (...args) { const now = new Date().getTime(); if (now - lastCall >= delay) { lastCall = now; return func(...args); } }; } const throttledLog = throttle(() => console.log('Throttled Function Call'), 2000); setInterval(throttledLog, 500); // Will log once every 2 seconds

26. Count Occurrences of Each Character

Write a function that counts the occurrences of each character in a string.

function countOccurrences(str) { let charCount = {}; for (let char of str) { charCount[char] = (charCount[char] || 0) + 1; } return charCount; } console.log(countOccurrences('hello')); // {h: 1, e: 1, l: 2, o: 1}

27. Flatten Nested Arrays

Write a function that flattens a deeply nested array (any level of depth).

function flattenDeep(arr) { return arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flattenDeep(toFlatten) : toFlatten), []); } console.log(flattenDeep([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]

28. Prime Number Check

Write a function that checks if a number is prime.

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

29. Sum of Nested Arrays

Write a function that computes the sum of all numbers in a deeply nested array.

function sumNested(arr) { return arr.reduce((sum, item) => sum + (Array.isArray(item) ? sumNested(item) : item), 0); } console.log(sumNested([1, [2, 3], [4, [5]]])); // 15

30. Convert Array to Object

Write a function that converts an array of key-value pairs into an object.

function arrayToObject(arr) { return arr.reduce((obj, [key, value]) => { obj[key] = value; return obj; }, {}); } console.log(arrayToObject([['name', 'John'], ['age', 30]])); // { name: 'John', age: 30 }

31. Find Unique Elements

Write a function that returns only unique elements from an array (without using Set).

function uniqueElements(arr) { let uniqueArr = []; arr.forEach(item => { if (!uniqueArr.includes(item)) uniqueArr.push(item); }); return uniqueArr; } console.log(uniqueElements([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]

32. Deep Clone Object

Write a function to perform a deep clone of an object.

function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } const obj = { a: 1, b: { c: 2 } }; const clone = deepClone(obj); console.log(clone); // { a: 1, b: { c: 2 } }

33. Check if Arrays are Equal

Write a function to check if two arrays are equal (order and elements).

function arraysEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; return arr1.every((val, index) => val === arr2[index]); } console.log(arraysEqual([1, 2, 3], [1, 2, 3])); // true console.log(arraysEqual([1, 2, 3], [1, 2, 4])); // false

34. Find Duplicates in Array

Write a function that finds all duplicates in an array.

function findDuplicates(arr) { let seen = new Set(); let duplicates = new Set(); arr.forEach(num => { if (seen.has(num)) { duplicates.add(num); } else { seen.add(num); } }); return [...duplicates]; } console.log(findDuplicates([1, 2, 3, 4, 4, 5, 6, 2])); // [2, 4]

35. Check Balanced Parentheses

Write a function that checks if a string has balanced parentheses.

function isBalanced(str) { let stack = []; for (let char of str) { if (char === '(') { stack.push('('); } else if (char === ')') { if (stack.length === 0) return false; stack.pop(); } } return stack.length === 0; } console.log(isBalanced('(())')); // true console.log(isBalanced('(()')); // false

36. Rotate Array

Write a function that rotates an array n times.

function rotateArray(arr, n) { n = n % arr.length; return arr.slice(n).concat(arr.slice(0, n)); } console.log(rotateArray([1, 2, 3, 4, 5], 2)); // [3, 4, 5, 1, 2]

37. Memoized Fibonacci

Write a function that generates the Fibonacci sequence using memoization.

function memoizedFibonacci() { let cache = {}; return function fib(n) { if (n in cache) return cache[n]; if (n <= 1) return n; cache[n] = fib(n - 1) + fib(n - 2); return cache[n]; }; } const fib = memoizedFibonacci(); console.log(fib(10)); // 55

38. Throttle Function Using Timestamps

Write a throttle function that uses timestamps to limit the function calls.

function throttle(func, limit) { let lastFunc; let lastRan; return function () { const context = this; const args = arguments; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(() => { if (Date.now() - lastRan >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; } const throttledLog = throttle(() => console.log('Throttled'), 2000); setInterval(throttledLog, 500); // Logs "Throttled" once every 2 seconds

39. Count Words in a String

Write a function to count the number of words in a string.

function countWords(str) { return str.split(/\s+/).filter(word => word.length > 0).length; } console.log(countWords('Hello world! How are you?')); // 5

40. Event Delegation

Write a simple example that demonstrates event delegation in JavaScript.


document.getElementById('parent').addEventListener('click', function (event) { if (event.target && event.target.nodeName === 'BUTTON') { console.log('Button clicked:', event.target.innerText); } });

HTML:

<div id="parent"> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> </div>

41. Find Missing Number in Sorted Array

Write a function to find the missing number in a sorted array.

function findMissing(arr) { let n = arr.length; let totalSum = ((n + 1) * (n + 2)) / 2; let arrSum = arr.reduce((sum, num) => sum + num, 0); return totalSum - arrSum; } console.log(findMissing([1, 2, 3, 5])); // 4

42. Debounce Function with Immediate Call

Write a debounce function that has an option to run the function immediately.

function debounce(func, delay, immediate = false) { let timeout; return function () { const context = this; const args = arguments; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(() => { timeout = null; if (!immediate) func.apply(context, args); }, delay); if (callNow) func.apply(context, args); }; } const debouncedLog = debounce(() => console.log('Debounced'), 2000, true); debouncedLog(); // Executes immediately, subsequent calls are debounced

43. Implement a Curry Function

Write a function that curries another function.

function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func.apply(this, args); } else { return function (...nextArgs) { return curried.apply(this, args.concat(nextArgs)); }; } }; } function add(a, b, c) { return a + b + c; } const curriedAdd = curry(add); console.log(curriedAdd(1)(2)(3)); // 6

44. Shuffle an Array

Write a function to randomly shuffle the elements of an array.

function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } console.log(shuffleArray([1, 2, 3, 4, 5])); // Randomly shuffled array

45. Implement Object.create() Polyfill

Write a polyfill for Object.create() in JavaScript.

function myObjectCreate(proto) { function F() {} F.prototype = proto; return new F(); } const obj = { name: 'John' }; const newObj = myObjectCreate(obj); console.log(newObj.name); // 'John'

46. Implement Promise.all() Polyfill

Write a polyfill for Promise.all() in JavaScript.

function myPromiseAll(promises) { return new Promise((resolve, reject) => { let results = []; let completed = 0; promises.forEach((promise, index) => { Promise.resolve(promise) .then(result => { results[index] = result; completed++; if (completed === promises.length) { resolve(results); } }) .catch(error => reject(error)); }); }); } myPromiseAll([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]) .then(console.log); // [1, 2, 3]

47. Find Longest Palindrome in a String

Write a function that finds the longest palindromic substring in a string.

function longestPalindrome(str) { let result = ''; for (let i = 0; i < str.length; i++) { for (let j = i; j < str.length; j++) { let substr = str.slice(i, j + 1); if (substr === substr.split('').reverse().join('') && substr.length > result.length) { result = substr; } } } return result; } console.log(longestPalindrome('babad')); // 'bab' or 'aba'

48. Get All Subsets of an Array

Write a function that returns all possible subsets of a given array.

function getSubsets(arr) { return arr.reduce((subsets, value) => { return subsets.concat(subsets.map(set => [value, ...set])); }, [[]]); } console.log(getSubsets([1, 2, 3])); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

49. Implement Debounce with Trailing and Leading Edge

Write a debounce function that allows execution on both the leading and trailing edge.

function debounce(func, delay, leading = false) { let timeout; return function (...args) { const context = this; const callNow = leading && !timeout; clearTimeout(timeout); timeout = setTimeout(() => { timeout = null; if (!leading) func.apply(context, args); }, delay); if (callNow) func.apply(context, args); }; } const debouncedFunc = debounce(() => console.log('Debounced!'), 2000, true); debouncedFunc();

50. Find the Deepest Node in a Tree

Write a function to find the deepest node in a binary tree.

function findDeepestNode(root) { let maxDepth = -1; let deepestNode = null; function traverse(node, depth) { if (node === null) return; if (depth > maxDepth) { maxDepth = depth; deepestNode = node; } traverse(node.left, depth + 1); traverse(node.right, depth + 1); } traverse(root, 0); return deepestNode; } // Example tree: { value: 1, left: {...}, right: {...} }

51. Sum of Ranges in Array

Write a function that takes an array and returns the sum of all ranges in it (e.g., consecutive numbers).

function sumOfRanges(arr) { let sum = 0; for (let i = 1; i < arr.length; i++) { sum += Math.abs(arr[i] - arr[i - 1]); } return sum; } console.log(sumOfRanges([1, 4, 6, 8])); // 7

52. Find Intersection of Two Arrays

Write a function that returns the intersection of two arrays.

function arrayIntersection(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } console.log(arrayIntersection([1, 2, 3], [2, 3, 4])); // [2, 3]

53. Sort Array of Objects by Property

Write a function that sorts an array of objects by a given property.

function sortByProperty(arr, prop) { return arr.sort((a, b) => (a[prop] > b[prop] ? 1 : -1)); } const people = [{ name: 'John', age: 25 }, { name: 'Jane', age: 22 }]; console.log(sortByProperty(people, 'age')); // [{ name: 'Jane', age: 22 }, { name: 'John', age: 25 }]

54. Binary Search in a Sorted Array

Write a function to implement binary search in a sorted array.

function binarySearch(arr, target) { let low = 0; let high = arr.length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); if (arr[mid] === target) return mid; if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; } console.log(binarySearch([1, 2, 3, 4, 5], 3)); // 2

55. Check if Two Strings Are Anagrams

Write a function to check if two strings are anagrams.

function areAnagrams(str1, str2) { const formatStr = str => str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join(''); return formatStr(str1) === formatStr(str2); } console.log(areAnagrams('listen', 'silent')); // true console.log(areAnagrams('hello', 'world')); // false

56. Count Vowels in a String

Write a function to count the number of vowels in a string.

function countVowels(str) { return str.match(/[aeiou]/gi)?.length || 0; } console.log(countVowels('hello world')); // 3

57. Generate Pascal’s Triangle

Write a function to generate Pascal’s triangle up to a given number of rows.

function generatePascalsTriangle(rows) { let triangle = [[1]]; for (let i = 1; i < rows; i++) { let prevRow = triangle[i - 1]; let newRow = [1]; for (let j = 1; j < prevRow.length; j++) { newRow.push(prevRow[j - 1] + prevRow[j]); } newRow.push(1); triangle.push(newRow); } return triangle; } console.log(generatePascalsTriangle(5)); // [ // [1], // [1, 1], // [1, 2, 1], // [1, 3, 3, 1], // [1, 4, 6, 4, 1] // ]

58. Check if a String is a Substring

Write a function to check if one string is a substring of another.

function isSubstring(str, sub) { return str.includes(sub); } console.log(isSubstring('hello world', 'world')); // true

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

Write a function to find the first non-repeating character in a string.

function firstNonRepeatingChar(str) { for (let i = 0; i < str.length; i++) { if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) { return str[i]; } } return null; } console.log(firstNonRepeatingChar('swiss')); // 'w'

60. Find Maximum Profit from Stock Prices

Write a function that finds the maximum profit from an array of stock prices.

function maxProfit(prices) { let minPrice = Infinity; let maxProfit = 0; for (let price of prices) { minPrice = Math.min(minPrice, price); maxProfit = Math.max(maxProfit, price - minPrice); } return maxProfit; } console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 5

Feel free to continue practicing with these or adapt them for your specific use cases!

Post a Comment

Previous Post Next Post