
Are you aiming to strengthen your JavaScript logic skills? Whether you’re preparing for technical interviews, tackling coding assessments, or simply seeking to refine your problem-solving abilities, engaging with logic-building exercises is vital. In this collection, you’ll find 50 thoughtfully curated JavaScript logic questions, each accompanied by thorough explanations. These questions are designed to help you develop both fundamental and advanced understanding of JavaScript concepts. Dive in, challenge yourself, and deepen your mastery of JavaScript logic.
Introduction
JavaScript stands as a foundational language in modern web development. Mastery of logical structures is essential for producing efficient and reliable code. The following set of questions addresses a range of fundamental topics, including arrays, strings, loops, functions, and objects. Each question is accompanied by a succinct answer, designed to deepen your understanding of core concepts and enhance your programming proficiency.
50 JavaScript Logic Building Questions with Answers
Reverse a string in JavaScript.
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example: reverseString("hello") => "olleh"
Check if a string is a palindrome.
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
// Example: isPalindrome("madam") => true
Find the largest number in an array.
function largestNumber(arr) {
return Math.max(...arr);
}
// Example: largestNumber([1, 2, 3]) => 3
Find the factorial of a number.
function factorial(n) {
return n === 0 ? 1 : n * factorial(n - 1);
}
// Example: factorial(5) => 120
Check if a number is prime.
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
// Example: isPrime(7) => true
Find the sum of all numbers in an array.
function sumArray(arr) {
return arr.reduce((a, b) => a + b, 0);
}
// Example: sumArray([1,2,3]) => 6
Remove duplicates from an array.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Example: removeDuplicates([1,2,2,3]) => [1,2,3]
Find the Fibonacci sequence up to n terms.
function fibonacci(n) {
let seq = [0, 1];
for (let i = 2; i < n; i++) {
seq.push(seq[i-1] + seq[i-2]);
}
return seq.slice(0, n);
}
// Example: fibonacci(5) => [0,1,1,2,3]
Check if two strings are anagrams.
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
// Example: areAnagrams("listen", "silent") => true
Find the second largest number in an array.
function secondLargest(arr) {
let unique = [...new Set(arr)];
unique.sort((a, b) => b - a);
return unique[1];
}
// Example: secondLargest([1,2,3,2]) => 2
Count vowels in a string.
function countVowels(str) {
return (str.match(/[aeiou]/gi) || []).length;
}
// Example: countVowels("hello") => 2
Find the missing number in an array of 1 to n.
function findMissing(arr, n) {
let total = (n * (n + 1)) / 2;
let sum = arr.reduce((a, b) => a + b, 0);
return total - sum;
}
// Example: findMissing([1,2,4,5], 5) => 3
Capitalize the first letter of each word in a string.
function capitalizeWords(str) {
return str.replace(/\b\w/g, c => c.toUpperCase());
}
// Example: capitalizeWords("hello world") => "Hello World"
Find the GCD of two numbers.
function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b);
}
// Example: gcd(12, 8) => 4
Find the LCM of two numbers.
function lcm(a, b) {
return (a * b) / gcd(a, b);
}
// Example: lcm(12, 8) => 24
Check if a number is even or odd.
function isEven(num) {
return num % 2 === 0;
}
// Example: isEven(4) => true
Find the longest word in a string.
function longestWord(str) {
return str.split(' ').reduce((a, b) => a.length > b.length ? a : b);
}
// Example: longestWord("I love JavaScript") => "JavaScript"
Count the number of words in a string.
function wordCount(str) {
return str.trim().split(/\s+/).length;
}
// Example: wordCount("Hello world!") => 2
Check if an array is sorted.
function isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i-1]) return false;
}
return true;
}
// Example: isSorted([1,2,3]) => true
Find the intersection of two arrays.
function intersection(arr1, arr2) {
return arr1.filter(x => arr2.includes(x));
}
// Example: intersection([1,2,3], [2,3,4]) => [2,3]
Find the union of two arrays.
function union(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
// Example: union([1,2], [2,3]) => [1,2,3]
Find the average of numbers in an array.
function average(arr) {
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
// Example: average([1,2,3]) => 2
Find all prime numbers up to n.
function primesUpTo(n) {
let primes = [];
for (let i = 2; i <= n; i++) {
if (isPrime(i)) primes.push(i);
}
return primes;
}
// Example: primesUpTo(10) => [2,3,5,7]
Flatten a nested array.
function flatten(arr) {
return arr.flat(Infinity);
}
// Example: flatten([1, [2, [3]]]) => [1,2,3]
Find the frequency of each element in an array.
function frequency(arr) {
return arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
}
// Example: frequency([1,2,2,3]) => {1:1, 2:2, 3:1}
Remove falsy values from an array.
function removeFalsy(arr) {
return arr.filter(Boolean);
}
// Example: removeFalsy([0,1,false,2,'',3]) => [1,2,3]
Convert Celsius to Fahrenheit.
function cToF(c) {
return (c * 9/5) + 32;
}
// Example: cToF(0) => 32
Convert Fahrenheit to Celsius.
function fToC(f) {
return (f - 32) * 5/9;
}
// Example: fToC(32) => 0
Find the sum of digits of a number.
function sumDigits(num) {
return num.toString().split('').reduce((a, b) => a + Number(b), 0);
}
// Example: sumDigits(123) => 6
Check if a year is a leap year.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
// Example: isLeapYear(2024) => true
Find the median of an array.
function median(arr) {
arr.sort((a, b) => a - b);
let mid = Math.floor(arr.length / 2);
return arr.length % 2 !== 0 ? arr[mid] : (arr[mid-1] + arr[mid]) / 2;
}
// Example: median([1,2,3]) => 2
Find the mode of an array.
function mode(arr) {
let freq = frequency(arr);
let max = Math.max(...Object.values(freq));
return Object.keys(freq).filter(k => freq[k] === max);
}
// Example: mode([1,2,2,3]) => ["2"]
Check if a string contains only digits.
function isDigits(str) {
return /^\d+$/.test(str);
}
// Example: isDigits("12345") => true
Find the first non-repeated character in a string.
function firstNonRepeated(str) {
for (let char of str) {
if (str.indexOf(char) === str.lastIndexOf(char)) return char;
}
return null;
}
// Example: firstNonRepeated("aabbcde") => "c"
Check if an object is empty.
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
// Example: isEmpty({}) => true
Clone an object.
function clone(obj) {
return {...obj};
}
// Example: clone({a:1}) => {a:1}
Merge two objects.
function merge(obj1, obj2) {
return {...obj1, ...obj2};
}
// Example: merge({a:1}, {b:2}) => {a:1, b:2}
Check if a string starts with a given substring.
function startsWith(str, sub) {
return str.startsWith(sub);
}
// Example: startsWith("hello", "he") => true
Check if a string ends with a given substring.
function endsWith(str, sub) {
return str.endsWith(sub);
}
// Example: endsWith("hello", "lo") => true
Repeat a string n times.
function repeatString(str, n) {
return str.repeat(n);
}
// Example: repeatString("abc", 3) => "abcabcabc"
Truncate a string to a specified length.
function truncate(str, len) {
return str.length > len ? str.slice(0, len) + "..." : str;
}
// Example: truncate("Hello World", 5) => "Hello..."
Find all occurrences of a substring in a string.
function findAllOccurrences(str, sub) {
let indices = [];
let idx = str.indexOf(sub);
while (idx !== -1) {
indices.push(idx);
idx = str.indexOf(sub, idx + 1);
}
return indices;
}
Convert a string to snake_case.
function toSnakeCase(str) {
return str.replace(/[A-Z]/g, c => '_' + c.toLowerCase()).replace(/\s+/g, '_');
}
// Example: toSnakeCase("helloWorld") => "hello_world"
Check if a string is a valid email.
function isValidEmail(str) {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(str);
}
// Example: isValidEmail("test@example.com") => true
Generate a random number between min and max.
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Example: randomNumber(1, 10) => e.g., 7
Check if two arrays are equal.
function arraysEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
return arr1.every((val, i) => val === arr2[i]);
}
// Example: arraysEqual([1,2,3], [1,2,3]) => true
Rotate an array by k positions.
function rotateArray(arr, k) {
k %= arr.length;
return [...arr.slice(k), ...arr.slice(0, k)];
}
// Example: rotateArray([1,2,3,4], 2) => [3,4,1,2]
Find the maximum product of two numbers in an array.
function maxProduct(arr) {
arr.sort((a, b) => b - a);
return arr[0] * arr[1];
}
// Example: maxProduct([1,5,3,2]) => 15
Replace all occurrences of a character in a string.
function replaceChar(str, oldChar, newChar) {
return str.replace(RegExp(oldChar, 'g'), newChar);
}
// Example: replaceChar("hello", "l", "x") => "hexxo"
Generate all permutations of a string.
function permute(str) {
if (str.length <= 1) return [str];
let result = [];
for (let i = 0; i < str.length; i++) {
let char = str[i];
let rest = str.slice(0, i) + str.slice(i + 1);
permute(rest).forEach(p => result.push(char + p));
}
return result;
}
// Example: permute("abc") => ["abc", "acb", "bac", "bca", "cab", "cba"]
Conclusion
So, you’ve got 50 JavaScript brain teasers here—everything from the classic string shuffling and array wizardry to the wild stuff like permutations and making sneaky copies of objects. Honestly, grinding through these isn’t just about flexing for an interview (although, hey, it helps). It’s about actually getting sharper at picking apart problems and, you know, not panicking when that whiteboard marker squeaks. Just keep at it, mess around with more challenges, and before you know it, you’ll be the go-to JavaScript whiz everyone pesters for help. Happy coding—or, well, as happy as debugging lets you be!