1. Basic JavaScript Questions
- Reverse a String:
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // Output: "olleh"
Check if a String is a Palindrome:
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
console.log(isPalindrome("madam")); // Output: true
Find the Largest Number in an Array:
function findMax(arr) {
return Math.max(...arr);
}
console.log(findMax([1, 5, 3, 9, 2])); // Output: 9
FizzBuzz Problem: Print numbers from 1 to 100, but for multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both, print "FizzBuzz".
for (let i = 1; i <= 100; i++) {
let output = '';
if (i % 3 === 0) output += 'Fizz';
if (i % 5 === 0) output += 'Buzz';
console.log(output || i);
}
Remove Duplicates from an Array:
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // Output: [1, 2, 3, 4]
2. Intermediate JavaScript Questions
- Find Factorial of a Number (Recursive):
function factorial(n) {
return n === 0 ? 1 : n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
Flatten a Nested Array:
function flattenArray(arr) {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
console.log(flattenArray([1, [2, [3, 4], 5], 6])); // Output: [1, 2, 3, 4, 5, 6]
Check for Anagram:
function isAnagram(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(isAnagram('listen', 'silent')); // Output: true
Implement Array.prototype.map():
Array.prototype.customMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
Find Missing Number in an Array:
function findMissing(arr, n) {
const expectedSum = (n * (n + 1)) / 2;
const actualSum = arr.reduce((a, b) => a + b, 0);
return expectedSum - actualSum;
}
console.log(findMissing([1, 2, 4, 5, 6], 6)); // Output: 3
3. Advanced JavaScript Questions
- Deep Clone an Object:
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
Debounce Function:
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
Throttle Function:
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
JavaScript coding questions to help prepare for interviews
Working Code Edited question September 21, 2024
Sorry, you do not have permission to read comments.