· Travis Rodgers · Programming  · 10 min read

Top 10 JavaScript Interview Questions: Master Your Next Technical Interview

Are you preparing for a JavaScript technical interview and feeling a bit nervous?

Don’t worry, you’re not alone.

JavaScript is one of the most popular programming languages, and nailing those tricky interview questions can be the key to landing your ideal job.

But where do you start?

How can you ensure you’re ready to impress your interviewer and showcase your JavaScript skills?

In this article, we’ve compiled the top 10 JavaScript interview questions that you’re likely to encounter in your technical interview, along with hints, explanations, and code examples.

By mastering these concepts, you’ll walk into your next interview with more confidence, ready to tackle most challenges thrown your way.

So grab a cup of coffee, settle in, and let’s dive into the world of JavaScript interview prep together.

1. Implement a function to flatten an array of nested arrays

Hint: Write a JavaScript function that takes an array of nested arrays as input. The function should return a new array with all the elements flattened into a single level.

function flattenArray(arr) {
  return arr.reduce((flat, toFlatten) => {
    return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
  }, []);
}

// Example usage
const nestedArray = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5, 6]

Explanation: This function uses recursion and the reduce method to flatten nested arrays. It checks if each element is an array using Array.isArray(). If it is, it recursively calls flattenArray on that element. Otherwise, it simply concatenates the element to the result.

2. Implement a debounce function

Hint: Implement a debounce function in JavaScript that takes a function and a delay as arguments. The debounce function should return a new function that delays the execution of the original function until a specified time has passed since the last time it was called.

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

// Example usage
const debouncedSearch = debounce((query) => {
  console.log(`Searching for: ${query}`);
}, 300);

// Simulate rapid typing
debouncedSearch("a");
debouncedSearch("ap");
debouncedSearch("app");
debouncedSearch("appl");
debouncedSearch("apple");

Explanation: The debounce function returns a new function that wraps the original function. It uses setTimeout to delay the execution of the original function. If the returned function is called again before the delay has passed, it clears the previous timeout and sets a new one. This ensures that the original function is only called once after the user stops calling the debounced function.

3. Implement a function to check if a string is a palindrome

Hint: Write a JavaScript function that takes a string as input and determines whether it is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring case, spaces, and punctuation.

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

// Example usage
console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true
console.log(isPalindrome("race a car")); // Output: false

Explanation: This function first cleans the input string by converting it to lowercase and removing non-alphanumeric characters. Then it compares the cleaned string with its reverse. If they’re the same, the original string is a palindrome.

4. Implement a function to find the missing number in an array of 1 to N

Hint: Create a JavaScript function that finds the missing number in an array containing integers from 1 to N, where one number is missing. The function should take the array as input and return the missing number.

function findMissingNumber(arr) {
  const n = arr.length + 1;
  const expectedSum = (n * (n + 1)) / 2;
  const actualSum = arr.reduce((sum, num) => sum + num, 0);
  return expectedSum - actualSum;
}

// Example usage
console.log(findMissingNumber([1, 2, 4, 6, 3, 7, 8])); // Output: 5

Explanation: This function uses the formula for the sum of numbers from 1 to N: (N * (N + 1)) / 2. It calculates the expected sum for all numbers from 1 to N, then subtracts the actual sum of the array. The difference is the missing number.

5. Implement a function to reverse a linked list

Hint: Write a JavaScript function that reverses a singly linked list. The function should take the head of the linked list as input and return the new head of the reversed list.

class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function reverseLinkedList(head) {
  let prev = null;
  let current = head;
  
  while (current !== null) {
    const nextTemp = current.next;
    current.next = prev;
    prev = current;
    current = nextTemp;
  }
  
  return prev;
}

// Example usage
const list = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
let reversed = reverseLinkedList(list);
while (reversed !== null) {
  console.log(reversed.val);
  reversed = reversed.next;
}

Explanation: This function reverses a linked list in place. It uses three pointers: prev, current, and nextTemp. It iterates through the list, reversing the next pointer of each node to point to the previous node. The prev pointer becomes the new head of the reversed list.

6. Implement a function to find the longest substring without repeating characters

Hint: Create a JavaScript function that finds the longest substring without repeating characters in a given string. The function should take a string as input and return the longest substring that contains no duplicate characters.

function longestSubstringWithoutRepeats(s) {
  let longest = '';
  let current = '';
  let seen = new Set();
  
  for (let char of s) {
    while (seen.has(char)) {
      seen.delete(current[0]);
      current = current.slice(1);
    }
    current += char;
    seen.add(char);
    if (current.length > longest.length) {
      longest = current;
    }
  }
  
  return longest;
}

// Example usage
console.log(longestSubstringWithoutRepeats("abcabcbb")); // Output: "abc"
console.log(longestSubstringWithoutRepeats("bbbbb")); // Output: "b"
console.log(longestSubstringWithoutRepeats("pwwkew")); // Output: "wke"

Explanation: This function uses a sliding window approach. It maintains a current substring and a set of seen characters. When a repeating character is encountered, it removes characters from the start of the current substring until the repeating character is removed. It keeps track of the longest valid substring found.

7. Implement a function to perform a deep clone of an object

Hint: Write a JavaScript function that performs a deep clone of an object, creating a new object with the same structure and values as the original object. The function should handle nested objects and arrays, ensuring that the cloned object is completely independent of the original object.

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }
  
  const clonedObj = {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  
  return clonedObj;
}

// Example usage
const original = {
  a: 1,
  b: { c: 2, d: [3, 4] },
  e: [{ f: 5 }, { g: 6 }]
};
const cloned = deepClone(original);
console.log(JSON.stringify(cloned));
console.log(cloned.b === original.b); // Output: false

Explanation: This function recursively clones an object and its nested properties. It handles primitive values, arrays, and objects. For arrays, it maps over each element and recursively clones it. For objects, it creates a new object and recursively clones each property.

8. Implement a function to check if two strings are anagrams

Hint: Create a JavaScript function that determines whether two given strings are anagrams of each other. Two strings are considered anagrams if they have the same characters with the same frequency, regardless of order.

function areAnagrams(str1, str2) {
  if (str1.length !== str2.length) {
    return false;
  }
  
  const charCount = {};
  
  for (let char of str1) {
    charCount[char] = (charCount[char] || 0) + 1;
  }
  
  for (let char of str2) {
    if (!charCount[char]) {
      return false;
    }
    charCount[char]--;
  }
  
  return true;
}

// Example usage
console.log(areAnagrams("listen", "silent")); // Output: true
console.log(areAnagrams("hello", "world")); // Output: false

Explanation: This function first checks if the strings have the same length. Then it uses an object to count the occurrences of each character in the first string. It then iterates through the second string, decrementing the count for each character. If at any point a character is not found or its count becomes negative, the strings are not anagrams.

9. Implement a function to find the kth largest element in an unsorted array

Hint: Write a JavaScript function to find the kth largest element in an unsorted array. The function should use the QuickSelect algorithm to efficiently find the kth largest element without fully sorting the array.

function findKthLargest(nums, k) {
  return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}

function quickSelect(nums, left, right, kSmallest) {
  if (left === right) return nums[left];
  
  const pivotIndex = partition(nums, left, right);
  
  if (kSmallest === pivotIndex) {
    return nums[kSmallest];
  } else if (kSmallest < pivotIndex) {
    return quickSelect(nums, left, pivotIndex - 1, kSmallest);
  } else {
    return quickSelect(nums, pivotIndex + 1, right, kSmallest);
  }
}

function partition(nums, left, right) {
  const pivot = nums[right];
  let i = left;
  
  for (let j = left; j < right; j++) {
    if (nums[j] <= pivot) {
      [nums[i], nums[j]] = [nums[j], nums[i]];
      i++;
    }
  }
  
  [nums[i], nums[right]] = [nums[right], nums[i]];
  return i;
}

// Example usage
console.log(findKthLargest([3,2,1,5,6,4], 2)); // Output: 5
console.log(findKthLargest([3,2,3,1,2,4,5,5,6], 4)); // Output: 4

Explanation: This function uses the QuickSelect algorithm, which is an optimized version of QuickSort. It partitions the array around a pivot and recursively searches in the appropriate partition. The average time complexity is O(n), making it more efficient than sorting the entire array for this specific problem.

10. Implement a function to detect a cycle in a linked list

Hint: Create a JavaScript function that detects whether a given linked list contains a cycle. The function should use Floyd’s Tortoise and Hare algorithm (also known as the “two-pointer” technique) to efficiently determine if there is a cycle in the linked list.

class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function hasCycle(head) {
  if (!head || !head.next) {
    return false;
  }
  
  let slow = head;
  let fast = head.next;
  
  while (slow !== fast) {
    if (!fast || !fast.next) {
      return false;
    }
    slow = slow.next;
    fast = fast.next.next;
  }
  
  return true;
}

// Example usage
const node1 = new ListNode(1);
const node2 = new ListNode(2);
const node3 = new ListNode(3);
const node4 = new ListNode(4);

node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node2; // Create a cycle

console.log(hasCycle(node1)); // Output: true

const noCycleList = new ListNode(1, new ListNode(2, new ListNode(3)));
console.log(hasCycle(noCycleList)); // Output: false

Explanation: This function uses Floyd’s Cycle-Finding Algorithm, also known as the “tortoise and hare” algorithm. It uses two pointers, one moving at twice the speed of the other. If there’s a cycle, the fast pointer will eventually catch up to the slow pointer. If there’s no cycle, the fast pointer will reach the end of the list.

Conclusion

If you worked through, and now understand, those top 10 JavaScript interview questions, then congratulations.

By mastering these particular concepts and feeling familiar with the provided code examples, you’ll be well-equipped and confident to face your JavaScript technical interview.

Remember, the key to success in a technical interview is not just about memorizing solutions, but also about understanding the underlying concepts and being able to explain your thought process. Don’t be afraid to think out loud, ask clarifying questions, and discuss alternative approaches with your interviewer (hint: they actually like this).

With dedication, practice, and a solid understanding of these fundamental JavaScript concepts, you’ll be able to showcase your skills and impress potential employers. So keep coding, keep learning, and most importantly, remember how far you’ve come and where you want to be.

Let that drive you toward your next goal.

    Share:

    Related Posts

    View All Posts »