Javascript Coding Questions and Answers
-
Write a JavaScript function to reverse a string.
Use the following JavaScript code:
function reverseString(str) { return str.split('').reverse().join(''); } console.log(reverseString("hello")); // Output: "olleh"
-
Write a JavaScript function to check if a number is prime.
Use the following JavaScript code:
function isPrime(num) { if (num <= 1) return false; for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) return false; } return true; } console.log(isPrime(7)); // Output: true
-
Write a JavaScript function to find the factorial of a number.
Use the following JavaScript code:
function factorial(n) { if (n === 0 || n === 1) return 1; return n * factorial(n - 1); } console.log(factorial(5)); // Output: 120
-
Write a JavaScript function to flatten a nested array.
Use the following JavaScript code:
function flattenArray(arr) { return arr.flat(Infinity); } console.log(flattenArray([1, [2, [3, [4]]]])); // Output: [1, 2, 3, 4]
-
Write a JavaScript function to sort an array of objects by a specific property.
Use the following JavaScript code:
function sortByProperty(arr, prop) { return arr.sort((a, b) => (a[prop] > b[prop]) ? 1 : -1); } const people = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]; console.log(sortByProperty(people, 'age'));
-
Write a JavaScript function to find the longest word in a sentence.
Use the following JavaScript code:
function longestWord(sentence) { const words = sentence.split(' '); return words.reduce((longest, word) => word.length > longest.length ? word : longest, ''); } console.log(longestWord("The quick brown fox jumped over the lazy dog")); // Output: "jumped"
- Write a JavaScript function to remove duplicates from an array.
Use the following JavaScript code:
function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]
- Write a JavaScript function to find the sum of all numbers in an array.
Use the following JavaScript code:
function sumArray(arr) { return arr.reduce((sum, num) => sum + num, 0); } console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
- Write a JavaScript function to check if a string is a palindrome.
Use the following JavaScript code:
function isPalindrome(str) { const cleaned = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); return cleaned === cleaned.split('').reverse().join(''); } console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true
- Write a JavaScript function to merge two sorted arrays.
Use the following JavaScript code:
function mergeSortedArrays(arr1, arr2) { let i = 0, j = 0, result = []; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) result.push(arr1[i++]); else result.push(arr2[j++]); } return result.concat(arr1.slice(i)).concat(arr2.slice(j)); } console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6]
- Write a JavaScript function to find the intersection of two arrays.
Use the following JavaScript code:
function intersectArrays(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } console.log(intersectArrays([1, 2, 3, 4], [3, 4, 5, 6])); // Output: [3, 4]
- Write a JavaScript function to generate a random integer between two values.
Use the following JavaScript code:
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandomInt(1, 10)); // Output: a random integer between 1 and 10
- Write a JavaScript function to count the occurrences of each character in a string.
Use the following JavaScript code:
function countChars(str) { return str.split('').reduce((count, char) => { count[char] = (count[char] || 0) + 1; return count; }, {}); } console.log(countChars("hello")); // Output: { h: 1, e: 1, l: 2, o: 1 }
- Write a JavaScript function to find the missing number in an array of 1 to n.
Use the following JavaScript code:
function findMissingNumber(arr, n) { const total = (n * (n + 1)) / 2; const sum = arr.reduce((a, b) => a + b, 0); return total - sum; } console.log(findMissingNumber([1, 2, 4, 5, 6], 6)); // Output: 3
- Write a JavaScript function to debounce a function.
Use the following JavaScript code:
function debounce(func, delay) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), delay); }; } const debouncedFunc = debounce(() => console.log('Debounced!'), 300); debouncedFunc(); // Debounced! (after 300ms)
- Write a JavaScript function to check if two strings are anagrams.
Use the following JavaScript code:
function areAnagrams(str1, str2) { const normalize = str => str.replace(/[^a-zA-Z]/g, '').toLowerCase().split('').sort().join(''); return normalize(str1) === normalize(str2); } console.log(areAnagrams("Listen", "Silent")); // Output: true
- Write a JavaScript function to find the longest substring without repeating characters.
Use the following JavaScript code:
function longestUniqueSubstring(str) { let start = 0, maxLength = 0, usedChars = {}; for (let end = 0; end < str.length; end++) { if (usedChars[str[end]] !== undefined) { start = Math.max(start, usedChars[str[end]] + 1); } usedChars[str[end]] = end; maxLength = Math.max(maxLength, end - start + 1); } return maxLength; } console.log(longestUniqueSubstring("abcabcbb")); // Output: 3
- Write a JavaScript function to merge two sorted arrays into one sorted array.
Use the following JavaScript code:
function mergeSortedArrays(arr1, arr2) { let merged = [], i = 0, j = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) merged.push(arr1[i++]); else merged.push(arr2[j++]); } return merged.concat(arr1.slice(i)).concat(arr2.slice(j)); } console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6]
- Write a JavaScript function to count the occurrences of each character in a string.
Use the following JavaScript code:
function countCharacterOccurrences(str) { const count = {}; for (const char of str) { count[char] = (count[char] || 0) + 1; } return count; } console.log(countCharacterOccurrences("hello")); // Output: { h: 1, e: 1, l: 2, o: 1 }
- Write a JavaScript function to find the intersection of two arrays.
Use the following JavaScript code:
function arrayIntersection(arr1, arr2) { const set2 = new Set(arr2); return arr1.filter(item => set2.has(item)); } console.log(arrayIntersection([1, 2, 3, 4], [3, 4, 5, 6])); // Output: [3, 4]
Creative Footer for Interview Questions - Write a JavaScript function to remove duplicates from an array.