JavaScript Interview top 14 programs
JavaScript interview questions can vary widely in difficulty, but here are some challenging JavaScript coding problems along with step-by-step solutions for each:
1. Reverse a String:
Problem: Write a JavaScript function to reverse a string.
Solution:
function reverseString(str) {
// Split the string into an array of characters
const charArray = str.split('');
// Reverse the array
const reversedArray = charArray.reverse();
// Join the characters back into a string
const reversedStr = reversedArray.join('');
return reversedStr;
}
const reversed = reverseString("Hello, World!");
console.log(reversed); // Output: "!dlroW ,olleH"
2. Find the First Non-Repeated Character:
Problem: Write a function to find the first non-repeated character in a string.
Solution:
function firstNonRepeatedChar(str) {
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (str.indexOf(char) === str.lastIndexOf(char)) {
return char;
}
}
return null; // If all characters are repeated
}
const firstUnique = firstNonRepeatedChar("programming");
console.log(firstUnique); // Output: "p"
3. Implement a Queue:
Problem: Implement a queue data structure in JavaScript.
Solution:
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) {
return null;
}
return this.items.shift();
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.dequeue()); // Output: 1
4. Find the Intersection of Two Arrays:
Problem: Write a function that returns the intersection of two arrays.
Solution:
function intersection(arr1, arr2) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const result = [];
for (const num of set1) {
if (set2.has(num)) {
result.push(num);
}
}
return result;
}
const array1 = [1, 2, 2, 1];
const array2 = [2, 2];
const intersected = intersection(array1, array2);
console.log(intersected); // Output: [2]
5. Implement a Promise.all-like Function:
Problem: Write a function promiseAll
that takes an array of Promises and resolves them, returning an array of their resolved values.
Solution:
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completedCount = 0;
promises.forEach((promise, index) => {
promise.then((result) => {
results[index] = result;
completedCount++;
if (completedCount === promises.length) {
resolve(results);
}
}).catch(reject);
});
});
}
// Usage:
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
promiseAll([promise1, promise2, promise3]).then((values) => {
console.log(values); // Output: [1, 2, 3]
});
6. Implement a Deep Clone Function:
Problem: Write a function deepClone
that recursively clones an object with nested properties and arrays.
Solution:
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(deepClone);
}
const clonedObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}
return clonedObj;
}
// Usage:
const original = { a: 1, b: { c: 2 }, d: [3, 4] };
const cloned = deepClone(original);
console.log(cloned);
7. Find the Longest Substring Without Repeating Characters:
Problem: Given a string, find the length of the longest substring without repeating characters.
Solution:
function lengthOfLongestSubstring(s) {
let maxLength = 0;
let start = 0;
const charIndexMap = {};
for (let end = 0; end < s.length; end++) {
const char = s[end];
if (charIndexMap[char] >= start) {
start = charIndexMap[char] + 1;
}
charIndexMap[char] = end;
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
// Usage:
const input = "abcabcbb";
const length = lengthOfLongestSubstring(input);
console.log(length); // Output: 3
8. Implement a Throttle Function:
Problem: Write a throttle
function that limits the rate at which a function can be called.
Solution:
function throttle(func, delay) {
let lastExecuted = 0;
return function (...args) {
const now = Date.now();
if (now - lastExecuted >= delay) {
func.apply(this, args);
lastExecuted = now;
}
};
}
// Usage:
const throttledFunc = throttle(() => {
console.log("Function executed!");
}, 1000);
setInterval(throttledFunc, 200); // The function will be executed every 1000ms at most
9. Implement a Debounce Function:
Problem: Write a debounce
function that delays the execution of a function until after a specified time period has passed without additional invocations.
Solution:
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage:
const debouncedFunc = debounce(() => {
console.log("Function executed after debounce!");
}, 1000);
// Call the debounced function multiple times quickly
for (let i = 0; i < 5; i++) {
debouncedFunc();
}
// Only one execution will occur after the last call
10. Implement a Currying Function:
Problem: Write a curry
function that converts a function into a curried version, allowing you to partially apply arguments.
Solution:
function curry(fn, ...args) {
return args.length >= fn.length ? fn(...args) : (...nextArgs) => curry(fn, ...args, ...nextArgs);
}
// Usage:
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // Output: 6
11. Implement a Memoization Function:
Problem: Write a memoize
function that caches the results of expensive function calls to improve performance.
Solution:
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;
};
}
// Usage:
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
const memoizedFibonacci = memoize(fibonacci);
console.log(memoizedFibonacci(10)); // Output: 55
12. Find the Missing Number in an Array:
Problem: Given an array containing n distinct numbers taken from 0 to n, find the missing number.
Solution:
function missingNumber(nums) {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((sum, num) => sum + num, 0);
return expectedSum - actualSum;
}
// Usage:
const numbers = [3, 0, 1];
const missing = missingNumber(numbers);
console.log(missing); // Output: 2
13. Reverse Words in a String:
Problem: Write a function to reverse the order of words in a string while keeping the words themselves unchanged.
Solution:
function reverseWords(str) {
return str.split(' ').reverse().join(' ');
}
// Usage:
const input = "Hello World";
const reversed = reverseWords(input);
console.log(reversed); // Output: "World Hello"
14. Implement a Binary Search Tree (BST):
Problem: Implement a Binary Search Tree data structure in JavaScript with methods for insertion, deletion, and searching.
Solution:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new TreeNode(value);
if (!this.root) {
this.root = newNode;
return this;
}
let current = this.root;
while (true) {
if (value === current.value) {
return undefined; // Avoid duplicates
}
if (value < current.value) {
if (!current.left) {
current.left = newNode;
return this;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
return this;
}
current = current.right;
}
}
}
search(value) {
let current = this.root;
while (current) {
if (value === current.value) {
return current;
}
if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return null;
}
// Other methods for traversal and deletion can be added
}
Do you want to learn more interview Questions like this ?
Message me on linkedin