JavaScript is one of the popular language among developers and computer science students. Whether you are applying for the full stack development role or frontend role then JavaScript interview questions are very important to cover to crack such an important opportunity.
Even in different competitions or hackathons JavaScript questions are essential and is important to cover for interviews. In this blog we will talk about top 20 question for JavaScript and these are important to cover basics in detail.
20 JavaScript Interview Questions (Easy to Advanced)
In this section we will be talking about JavaScript interview question as divided into three section which are easy, medium and advanced. Let’s begin with the easy coding question that helps to prepare for the JavaScript interview questions.
Easy Level JavaScript Interview Questions
Write a function to reverse a given string
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example
console.log(reverseString("hello")); // Output: "olleh"
Write a program to check whether a number is even or odd
function isEven(num) {
return num % 2 === 0;
}
// Example
console.log(isEven(4)); // Output: true
console.log(isEven(5)); // Output: false
Find the largest number in an array
function findMax(arr) {
return Math.max(...arr);
}
// Example
console.log(findMax([10, 24, 3, 9])); // Output: 24
Check whether the number is palindrome or not
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
// Example
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false
Write a program to count vowels in a string
function countVowels(str) {
return (str.match(/[aeiou]/gi) || []).length;
}
// Example
console.log(countVowels("education")); // Output: 5
Medium Level JavaScript Interview Questions
Write a program to find the factorial of a number
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
// Example
console.log(factorial(5)); // Output: 120
Write a program to remove duplicates from an array
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Example
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // Output: [1, 2, 3, 4]
Write a program to find the Fibonacci Sequence up to N Terms
function fibonacci(n) {
const fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib.slice(0, n);
}
// Example
console.log(fibonacci(6)); // Output: [0, 1, 1, 2, 3, 5]
Write a program to check whether the two strings are anagrams
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
// Example
console.log(areAnagrams("listen", "silent")); // Output: true
Program to capitalize the first letter of each word
function capitalizeWords(str) {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
// Example
console.log(capitalizeWords("hello world")); // Output: "Hello World"
Write a function to flatten a deeply nested array.
function flattenArray(arr) {
return arr.flat(Infinity);
}
// Example
console.log(flattenArray([1, [2, [3, 4]], 5])); // Output: [1, 2, 3, 4, 5]
Write a program to implement a debounce function that limits how often a function can fire.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
Implement a throttle function to control the rate at which a function is executed.
function throttle(fn, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Write a function to deep clone an object.
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// Example
const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
console.log(copy); // Output: { a: 1, b: { c: 2 } }
Write a function to deep clone an object.
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// Example
const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
console.log(copy); // Output: { a: 1, b: { c: 2 } }
Write your own version of the Array.prototype.map() method.
Array.prototype.customMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
}
// Example
console.log([1, 2, 3].customMap(num => num * 2)); // Output: [2, 4, 6]
Advanced Level JavaScript Interview Questions
Write a function to find the longest word in a sentence.
function longestWord(sentence) {
const words = sentence.split(' ');
return words.reduce((longest, current) =>
current.length > longest.length ? current : longest, '');
}
// Example
console.log(longestWord("JavaScript is awesome")); // Output: "JavaScript"
Write a function that groups a list of words into sets of anagrams.
function groupAnagrams(words) {
const map = {};
for (let word of words) {
const key = word.split('').sort().join('');
map[key] = map[key] || [];
map[key].push(word);
}
return Object.values(map);
}
// Example
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
// Output: [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]
Write a function to validate email addresses using regex.
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// Example
console.log(isValidEmail("test@example.com")); // Output: true
console.log(isValidEmail("invalid-email")); // Output: false
Write a function to return all unique values from two arrays.
function getUnique(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
// Example
console.log(getUnique([1, 2], [2, 3])); // Output: [1, 2, 3]
Write a function to execute an array of functions that return promises sequentially.
function chainPromises(functions) {
return functions.reduce((prev, curr) => {
return prev.then(curr);
}, Promise.resolve());
}
// Example
const task1 = () => Promise.resolve(console.log("Task 1"));
const task2 = () => Promise.resolve(console.log("Task 2"));
chainPromises([task1, task2]);
// Output:
// Task 1
// Task 2
Conclusion
These 20 JavaScript coding questions are really helpful to you if you want to improve your coding skills or doing preparations for interviews. Some questions are really easy, while others are a bit tricky, but practicing them will make you more confident.
JavaScript is used almost everywhere including websites, apps, and even on servers. The more you practice this language, the better you will get at solving real-world problems and building useful things.