DEV Community

Cover image for 🚀 Top 10 Most-Asked JavaScript Coding Interview Questions (with Explanations)
Rahul Chaurasia
Rahul Chaurasia

Posted on

🚀 Top 10 Most-Asked JavaScript Coding Interview Questions (with Explanations)

JavaScript interviews often test your problem-solving and logic-building skills with small but tricky coding challenges.
In this post, I’m sharing 10 must-know JavaScript interview questions with complete solutions, outputs, time complexities, and explanations.

👉 These are directly taken from my Amazon eBook “Top 50 Most Asked JavaScript Coding Questions in Interviews” where I’ve compiled the most frequently asked questions in interviews for Frontend, React, and MERN developer roles.

Let’s dive in 👇

1️⃣ Factorial of a Number

let number = 7; // Number to find the factorial of

// Function to find the factorial of a given number
function findFactorial(num) {
  // Factorial of 0 is defined as 1
  if (num === 0) {
    return 1;
  }
  // Initialize factorial result as 1
  let factorial = 1;

  // Calculate factorial by multiplying each integer up to num
  for (let i = 1; i <= num; i++) {
    factorial *= i;
  }

  return factorial;
}

const result = findFactorial(number);
console.log(result); // Output: 5040
Enter fullscreen mode Exit fullscreen mode

Explanation: This program calculates the factorial of the number 7. The findFactorial function first checks if the input number is 0. If true, it returns 1 because 0! = 1.
If the number is greater than 0, it initializes factorial to 1 and multiplies it by every integer from 1 to 7.
Thus, the final result is 5040, which is 7!.

Time Complexity: O(n)

2️⃣ Fibonacci Series

// Function to generate the Fibonacci series up to the n-th term
function fibonacci(n) {
  if (n === 0) {
    return [0];
  }

  if (n === 1) {
    return [0, 1];
  }

  // Initialize the series with the first two terms
  let fib = [0, 1];

  // Compute the next terms
  for (let i = 2; i < n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
  }

  return fib;
}

let n = 5; // Number of terms in the Fibonacci series
const result = fibonacci(n);

console.log(result); // Output: [0, 1, 1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The function first handles base cases (n=0 or n=1).
  • It initializes the series with [0, 1].
  • Then, it uses a loop to calculate each next term as the sum of the previous two terms.
  • Since the loop runs n times, the time complexity is O(n).

Time Complexity: O(n)

3️⃣ Palindrome Check(string)

let str = "racecar";

// Function to reverse the string
function reverseStr(str) {
  return str.split("").reverse().join("");
}

// Function to check if the string is a palindrome
function isPalindrome(string) {
  let reversedString = reverseStr(string);
  return reversedString === string ? true : false;
}

let result = isPalindrome(str);
console.log(result); // Output: true

Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. reverseStr(str) → splits the string into characters, reverses them, and joins back.
  2. isPalindrome(string) → compares the reversed string with the original.
  3. If both are the same, it returns true, meaning the string is a palindrome.

Time Complexity: O(n)

4️⃣ Anagram Check

let str1 = "listen";
let str2 = "silent";

// Function to check if two strings are anagrams
function isAnagram(str1, str2) {
  // Sort and join the characters of both strings
  const sortedArr1 = str1.split("").sort().join("");
  const sortedArr2 = str2.split("").sort().join("");

  // Compare the sorted versions of the strings
  return sortedArr1 === sortedArr2;
}

let result = isAnagram(str1, str2);
console.log(result); // Output: true

Enter fullscreen mode Exit fullscreen mode

Explanation: The function checks whether two strings are anagrams by:

  1. Splitting each string into an array of characters.
  2. Sorting the characters and joining them back into strings.
  3. Comparing the sorted strings. If both sorted strings are identical, the original strings are anagrams. The sorting step takes O(n log n), where n is the length of the string.

Time Complexity: O(n log n) (sorting)

5️⃣ Reverse a String

let str = "example";

function reverseStr(str) {
  let reverseStr = "";
  for (let i = 0; i < str.length; i++) {
    reverseStr = str.charAt(i) + reverseStr;
  }
  return reverseStr;
}

let result = reverseStr(str);
console.log(result); // Output: "elpmaxe"

Enter fullscreen mode Exit fullscreen mode

Explanation: This program reverses a given string by iterating through each character and adding it to the front of a new string. The time complexity is O(n), where n is the length of the string.

Time Complexity: O(n)

6️⃣ First Non-Repeated Character

let str = "algorithm"; // String to check

// Function to find the first non-repeated character
function firstNonRepeatedCharacter(str) {
  for (let i = 0; i < str.length; i++) {
    // Check if the character is non-repeated
    if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) {
      return str[i];
    }
  }
  return null; // Return null if all characters are repeated
}

let result = firstNonRepeatedCharacter(str);
console.log(result); // Output: "g"

Enter fullscreen mode Exit fullscreen mode

Explanation: The function loops through each character of the string. For each character, it checks whether the first occurrence (indexOf) is the same as the last occurrence (lastIndexOf). If they are equal, it means that character appears only once in the string, and that’s our answer. If no such character exists, the function returns null.

Time Complexity: O(n²) — because for each character, the function uses both indexOf and lastIndexOf, each of which takes O(n) time.

7️⃣ Count Vowels in a String

const str = "Rajat"; // String to check for vowels

// Function to count the number of vowels in the given string
function countVowels(str) {
  const vowels = ["a", "e", "i", "o", "u"]; // Array of vowel characters
  let count = 0; // Initialize the vowel count

  // Iterate through each character in the string
  for (let char of str.toLowerCase()) {
    // Increment count if the character is a vowel
    if (vowels.includes(char)) {
      count++;
    }
  }

  return count; // Return the total count of vowels
}

const result = countVowels(str);
console.log(result); // Output: 2

Enter fullscreen mode Exit fullscreen mode

Explanation: This program counts the number of vowels in the string str. The countVowels function first defines an array vowels containing the lowercase vowel characters. It then iterates through each character of the string, converting it to lowercase to handle case sensitivity. If the character is found in the vowels array, the count is incremented. The function finally returns the total count of vowels.

Time Complexity: O(n)

8️⃣ Binary Search

let arr = [1, 3, 7, 8, 9, 34, 56];
let k = 9; // The value to search for

// Function to perform Binary Search
function binarySearch(arr, k) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

    // If k is less than the middle element, search in the left half
    if (k < arr[mid]) {
      end = mid - 1;
    }
    // If k is greater than the middle element, search in the right half
    else if (k > arr[mid]) {
      start = mid + 1;
    }
    // If k is equal to the middle element, return the index
    else if (k === arr[mid]) {
      return mid;
    }
  }

  return -1; // Element not found
}

const result = binarySearch(arr, k);
console.log(result); // Output: 4 (since 9 is at index 4)
Enter fullscreen mode Exit fullscreen mode

Explanation: This program implements the Binary Search algorithm, which is used to search for an element in a sorted array.
The algorithm repeatedly divides the search interval in half:

If the value of the search key is less than the middle element, the search continues in the left half.

If it’s greater, the search continues in the right half.

If it matches, the index is returned.

Since the array is divided into halves each time, the time complexity is O(log n).
Time Complexity: O(log n)

9️⃣ Promise Handling (race, all, allSettled)

function handlePromise() {
  let promise1 = new Promise((resolve) => {
    setTimeout(() => {
      resolve("promise1 resolved");
    }, 1000);
  });

  let promise2 = new Promise((resolve) => {
    setTimeout(() => {
      resolve("promise2 resolved");
    }, 500);
  });

  let promise3 = new Promise((resolve) => {
    setTimeout(() => {
      resolve("promise3 resolved");
    }, 1500);
  });

  // Using Promise.race: Returns the result of the fastest promise
  Promise.race([promise1, promise2, promise3])
    .then((result) => {
      console.log("Promise.race result:", result);
    })
    .catch((error) => {
      console.log("Promise.race caught an error:", error);
    });

  // Using Promise.all: Waits for all promises to resolve
  Promise.all([promise1, promise2, promise3])
    .then((results) => {
      console.log("Promise.all results:", results);
    })
    .catch((error) => {
      console.log("Promise.all caught an error:", error);
    });

  // Adding a rejected promise to showcase Promise.allSettled
  let promise4 = new Promise((_, reject) => {
    setTimeout(() => {
      reject("promise4 encountered an error");
    }, 700);
  });

  // Using Promise.allSettled: Returns results of all promises,
  // regardless of whether they resolve or reject
  Promise.allSettled([promise1, promise2, promise3, promise4]).then(
    (results) => {
      console.log("Promise.allSettled results:", results);
    }
  );
}

handlePromise();

Enter fullscreen mode Exit fullscreen mode

Output:
Promise.race result: promise2 resolved

Promise.all results: [ 'promise1 resolved', 'promise2 resolved', 'promise3 resolved' ]

Promise.allSettled results: [
{ status: 'fulfilled', value: 'promise1 resolved' },
{ status: 'fulfilled', value: 'promise2 resolved' },
{ status: 'fulfilled', value: 'promise3 resolved' },
{ status: 'rejected', reason: 'promise4 encountered an error' }
]

Explanation:

  • Promise.race → Returns the result from the fastest resolved promise. Here, promise2 resolves first in 500ms.
  • Promise.all → Waits until all promises are resolved successfully. It returns an array of results.
  • Promise.allSettled → Returns the result of all promises, regardless of whether they fulfill or reject. Useful when you want the outcome of every promise.

Time Complexity: O(n) over the number of promises (coordination work).

🔟 Closures in JavaScript

function multiplier(factor) {
  // 'factor' is captured by the inner function
  return function(number) {
    // Inner function multiplies 'number' by the captured 'factor'
    return factor * number;
  };
}

const triple = multiplier(3); // multiplier returns a function with factor set to 3
console.log(triple(7)); // Output: 21

Enter fullscreen mode Exit fullscreen mode

Explanation: This example demonstrates closures in JavaScript.
The inner function has access to the factor variable from its outer lexical scope, even after multiplier has finished executing. When you call triple(7), the function remembers the captured value of factor (which is 3) and multiplies it by 7, giving the result 21.

Time Complexity: O(1)

📘 Want all 50 interview-ready questions?

These 10 are a warm-up. For the complete set with clear explanations, outputs, edge cases, and time complexities, check out my eBook:

👉 Top 50 Most Asked JavaScript Coding Questions in Interviews
[https://a.co/d/gd6Hdu9]

You’ll get:

  • Battle-tested solutions you can type confidently in interviews
  • String, Array, Object, and Promise/Async essentials
  • Clean code patterns you’ll reuse at work

If this post helped, consider supporting by grabbing the book—happy prepping and good luck! 💪

Top comments (0)