JavaScript Interview Code Snippets
In JavaScript interviews, coding questions often assess your problem-solving skills, familiarity with basic programming concepts, and ability to optimize code. Here, we will explore a detailed set of JavaScript interview code snippets that cover a wide range of topics such as string manipulation, sorting algorithms, recursion, and more.
1. Reverse a String in JavaScript
One of the most common tasks in interviews is to reverse a string. Here’s how you can do it using JavaScript:
functionreverseString(str) {
return str.split('').reverse().join('');
}
const input = "hello";
const output = reverseString(input);
console.log(output); // Output: "olleh"
Explanation:
split('')
: Converts the string into an array of characters.reverse()
: Reverses the array.join('')
: Joins the reversed array back into a string.
2. Check if a String is a Palindrome
A palindrome is a word that reads the same forwards and backwards, such as "madam". This is a typical problem used to assess understanding of string manipulation and conditionals.
functionisPalindrome(str) {
const reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
const input = "madam";
const output = isPalindrome(input);
console.log(output); // Output: true
Explanation:
- We reverse the string and compare it to the original string.
- If they are the same, the function returns
true
; otherwise,false
.
3. Find the Factorial of a Number (Recursive)
Calculating the factorial of a number is a fundamental problem, typically solved recursively.
functionfactorial(n) {
if (n === 0) {
return1;
}
return n * factorial(n - 1);
}
const input = 5;
const output = factorial(input);
console.log(output); // Output: 120
Explanation:
- The base case is when
n
is 0, returning 1 (since0! = 1
). - Otherwise, we multiply the current number
n
by the factorial ofn - 1
.
4. Find the Largest Number in an Array
A classic problem that tests your understanding of arrays and iteration.
functionfindLargest(arr) {
returnMath.max(...arr);
}
const input = [10, 20, 30, 5, 100];
const output = findLargest(input);
console.log(output); // Output: 100
Explanation:
Math.max()
returns the largest number in an array.- The spread operator
...
is used to pass the array elements as individual arguments toMath.max()
.
5. Binary Search in a Sorted Array
Binary search is an efficient algorithm for finding an element in a sorted array. It operates in O(log n) time complexity.
functionbinarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} elseif (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Target not found
}
const input = [1, 3, 5, 7, 9, 11];
const target = 7;
const output = binarySearch(input, target);
console.log(output); // Output: 3
Explanation:
- We start with two pointers,
left
andright
, marking the bounds of the search. - If the middle element is the target, return its index.
- Otherwise, narrow down the search range based on whether the target is greater or smaller than the middle element.
6. Sort an Array Using Bubble Sort
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent items, and swaps them if they are in the wrong order.
functionbubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // Swap
}
}
}
return arr;
}
const input = [5, 2, 9, 1, 5, 6];
const output = bubbleSort(input);
console.log(output); // Output: [1, 2, 5, 5, 6, 9]
Explanation:
- We iterate over the array multiple times, comparing adjacent elements and swapping them if they are in the wrong order.
- The algorithm "bubbles" larger elements to the end of the array in each iteration.
7. Find the Intersection of Two Arrays
This problem checks your ability to manipulate arrays and identify common elements between them.
functionintersection(arr1, arr2) {
return arr1.filter(value => arr2.includes(value));
}
const input1 = [1, 2, 2, 1];
const input2 = [2, 2];
const output = intersection(input1, input2);
console.log(output); // Output: [2, 2]
Explanation:
- We use
filter()
to return an array containing elements fromarr1
that also appear inarr2
. includes()
checks if each element ofarr1
is present inarr2
.
8. Find the First Non-Repeating Character in a String
This problem is often used to test your knowledge of arrays, hashmaps, and string manipulation.
functionfirstUniqChar(str) {
const charCount = {};
// Count occurrences of each character
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Find first character with count 1
for (let char of str) {
if (charCount[char] === 1) {
return char;
}
}
returnnull; // No unique character
}
const input = "loveleetcode";
const output = firstUniqChar(input);
console.log(output); // Output: "v"
Explanation:
- We first count the occurrences of each character using a hashmap (
charCount
). - Then, we iterate through the string again to find the first character with a count of 1.
9. Implementing a Simple Event Emitter
Creating a simple event emitter in JavaScript demonstrates understanding of object-oriented programming and event-driven systems.
classEventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
}
emit(event, ...args) {
if (this.events[event]) {
this.events[event].forEach(listener =>listener(...args));
}
}
}
const emitter = newEventEmitter();
emitter.on('greet', name =>console.log(`Hello, ${name}!`));
emitter.emit('greet', 'Alice'); // Output: "Hello, Alice!"
Explanation:
- We maintain a hashmap
events
to store event names and their listeners. on()
adds an event listener, andemit()
triggers all listeners for a specific event.
Conclusion
These JavaScript interview code snippets are common problems you may encounter in interviews. They test various aspects of your coding skills, including problem-solving, algorithmic thinking, and understanding of core JavaScript concepts. In addition to solving these problems, it's essential to analyze the time and space complexity of your solutions to improve your optimization skills. By practicing these problems and similar ones, you'll be better prepared for your next interview.
Comments
Post a Comment