15 JavaScript Interview Difficult Questions And Code Implementation
This article give depth look at 15 Javascript Senior Software Enginer Interview questions along with descriptions, definitions, and code implementations:
- **Debouncing Function:**
— **Description:** Debouncing is a technique used to limit the rate at which a function is called, ensuring that it is only executed after a certain period of inactivity.
— **Definition:** A debouncing function postpones the execution of a function until after a specified delay has passed since the last time the function was invoked.
— **Implementation:**
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
2. **Throttling Function:**
— **Description:** Throttling is a technique used to limit the rate at which a function can be called, ensuring that it is not invoked more than once within a specified time interval.
— **Definition:** A throttling function restricts the frequency of function invocations to prevent excessive execution and resource consumption.
— **Implementation:**
function throttle(func, delay) {
let throttled = false;
return function(...args) {
if (!throttled) {
throttled = true;
func.apply(this, args);
setTimeout(() => {
throttled = false;
}, delay);
}
};
}
3. **Currying Function:**
— **Description:** Currying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.
— **Definition:** Currying converts a function of multiple arguments into a chain of unary functions, allowing partial application of arguments for increased flexibility and reusability.
— **Implementation:**
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));
};
}
};
}
4. **Flattening Nested Arrays:**
— **Description:** Flattening an array involves converting a nested array structure into a single, one-dimensional array.
— **Definition:** Flattening transforms a nested array structure into a flat array, concatenating all nested elements into a single array.
— **Implementation:**
function flatten(arr) {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
5. **Implementing `Promise.all()`:**
— **Description:** `Promise.all()` is a method that takes an array of promises and returns a single promise that resolves when all promises in the array have resolved, or rejects if any of the promises reject.
— **Definition:** `Promise.all()` aggregates multiple promises into a single promise, resolving when all promises are resolved, or rejecting if any promise is rejected.
— **Implementation:**
function promiseAll(promises) {
return new Promise((resolve, reject) => {
let results = [];
let count = 0;
promises.forEach((promise, index) => {
promise.then(result => {
results[index] = result;
count++;
if (count === promises.length) {
resolve(results);
}
}).catch(reject);
});
});
}
6. **Detecting a Palindrome:**
— **Description:** A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
— **Definition:** Palindrome detection is the process of determining whether a given string or number remains unchanged when reversed.
— **Implementation:**
function isPalindrome(str) {
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleanStr === cleanStr.split('').reverse().join('');
}
7. **Implementing `Array.prototype.map()`:**
— **Description:** `Array.prototype.map()` is a method that creates a new array populated with the results of calling a provided function on every element in the calling array.
— **Definition:** Mapping is the process of transforming each element of an array by applying a function to it, resulting in a new array with the transformed values.
— **Implementation:**
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
8. **Deep Copying Objects:**
— **Description:** Deep copying an object involves creating a new object with the same structure and values as the original, but with no shared references.
— **Definition:** Deep copying is the process of recursively copying all nested objects and arrays within an object, ensuring that the copied object is independent of the original.
— **Implementation:**
function deepCopy(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let copy = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
copy[key] = deepCopy(obj[key]);
}
}
return copy;
}
9. **Detecting Prime Numbers:**
— **Description:** A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
— **Definition:** Prime number detection is the process of determining whether a given number is divisible only by 1 and itself.
— **Implementation:**
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
}
10. **Implementing `Array.prototype.reduce()`:**
— **Description:** `Array.prototype.reduce()` is a method that applies a function against an accumulator and each element in the array to reduce it to a single value.
— **Definition:** Reduction is the process of iteratively applying a function to each element of an array, accumulating a single result.
— **Implementation:**
Array.prototype.myReduce = function(callback, initialValue) {
let accumulator = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator !== undefined) {
accumulator = callback.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
};
11. **Sorting an Array without `Array.prototype.sort()`:**
— **Description:** Sorting an array involves rearranging its elements in ascending or descending order based on a specified criterion.
— **Definition:** Sorting is the process of arranging elements of an array in a specific order, such as numerical or lexicographical.
— **Implementation:**
function sortArray(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
}
return arr;
}
12. **Implementing `Array.prototype.filter()`:**
— **Description:** `Array.prototype.filter()` is a method that creates a new array with all elements that pass the test implemented by the provided function.
— **Definition:** Filtering is the process of selecting elements from an array based on a specified criterion, such as a predicate function.
— **Implementation:**
Array.prototype.myFilter = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
13. **Reversing a String:**
— **Description:** Reversing a string involves flipping its characters in the opposite order.
— **Definition:** String reversal is the process of transforming a string into its mirror image, with characters reversed.
— **Implementation:**
function reverseString(str) {
return str.split('').reverse().join('');
}
14. **Implementing `Array.prototype.every()`:**
— **Description:** `Array.prototype.every()` is a method that tests whether all elements in the array pass the test implemented by the provided function.
— **Definition:** Every testing is the process of determining whether all elements of an array satisfy a specified condition, returning true if all elements pass the test, and false otherwise.
— **Implementation:**
Array.prototype.myEvery = function(callback) {
for (let i = 0; i < this.length; i++) {
if (!callback(this[i], i, this)) {
return false;
}
}
return true;
};
These questions cover a range of JavaScript concepts and are commonly used in interviews to assess candidates’ understanding and problem-solving skills.