Frequently Asked JavaScript Interview Questions with Answers

1. Reverse a String

Manual Version:

javascript

function reverseStringManual() {

    const str = prompt("Enter a string to reverse:");

    let reversed = "";

    for (let i = str.length - 1; i >= 0; i--) {

        reversed += str[i];

    }

    console.log(`Reversed string: ${reversed}`);

}

 

Explanation: This code prompts the user to enter a string.

·         It initializes an empty string reversed and loops through the original string starting from the last character.

·         It adds each character to the reversed string, which gives us the string in reverse order.

·         Finally, it prints the reversed string.

·        Intermediate Version:

javascript

 

function reverseStringIntermediate() {

    const str = prompt("Enter a string to reverse:");

    console.log(`Reversed string: ${str.split("").reverse().join("")}`);

}

 

Explanation: This code splits the string into an array of characters using split("").

·         Then, it reverses the array with reverse() and joins the array back into a string using join("").

·         Finally, it prints the reversed string.

·        Advanced Version:

javascript

 

function reverseStringAdvanced() {

    const str = prompt("Enter a string to reverse:");

    console.log(`Reversed string: ${[...str].reduce((rev, char) => char + rev, "")}`);

}

 

Explanation: This version uses reduce() to accumulate the characters in reverse order.

·         The spread syntax [...] turns the string into an array of characters.

·         The reduce() method adds each character to the front of the accumulating string, effectively reversing the string.


2. Check if a Number is a Palindrome

Manual Version:

javascript

 

function isPalindromeManual() {

    const num = parseInt(prompt("Enter a number to check for palindrome:"));

    let reversed = 0, temp = num;

    while (temp > 0) {

        reversed = reversed * 10 + (temp % 10);

        temp = Math.floor(temp / 10);

    }

    console.log(`Is the number a palindrome? ${reversed === num}`);

}

 

Explanation: This code checks if a number is the same when reversed.

·         It uses a while loop to reverse the number by extracting each digit (using temp % 10) and adding it to the reversed number.

·         If the reversed number matches the original number, it's a palindrome.

·        Intermediate Version:

javascript

 

function isPalindromeIntermediate() {

    const num = prompt("Enter a number to check for palindrome:");

    console.log(`Is the number a palindrome? ${num === num.split("").reverse().join("")}`);

}

 

Explanation: This code converts the number into a string and checks if the string is equal to its reversed version.

·         It uses split(""), reverse(), and join("") to reverse the string and compares it with the original number.

Advanced Version:

javascript

 

function isPalindromeAdvanced() {

    const num = prompt("Enter a number to check for palindrome:");

    console.log(`Is the number a palindrome? ${[...num].every((char, i) => char === num[num.length - 1 - i])}`);

}

 

Explanation: This version uses the every() method to compare characters from both ends of the string.

·         It checks if every character at the start is equal to the corresponding character at the end of the string.


3. Calculate the Factorial of a Number

Manual Version:

javascript

 

function factorialManual() {

    const n = parseInt(prompt("Enter a number to find its factorial:"));

    let fact = 1;

    for (let i = 2; i <= n; i++) {

        fact *= i;

    }

    console.log(`Factorial: ${fact}`);

}

 

Explanation: This code calculates the factorial of a number using a for loop.

·         It multiplies the numbers from 1 to n to get the factorial and prints the result.

·        Intermediate Version:

javascript

 

function factorialIntermediate() {

    const n = parseInt(prompt("Enter a number to find its factorial:"));

    function factorial(n) {

        return n === 0 || n === 1 ? 1 : n * factorial(n - 1);

    }

    console.log(`Factorial: ${factorial(n)}`);

}

factorialIntermediate();

 

Explanation: This version uses a recursive function to calculate the factorial.

·         The function calls itself with a smaller number until it reaches the base case (0 or 1), then calculates the factorial by multiplying the results.

Advanced Version:

javascript

 

function factorialAdvanced() {

    const n = parseInt(prompt("Enter a number to find its factorial:"));

    console.log(`Factorial: ${Array.from({ length: n }, (_, i) => i + 1).reduce((a, b) => a * b, 1)}`);

}

factorialAdvanced();

 

Explanation: This version uses Array.from() to create an array of numbers from 1 to n and then calculates the factorial using reduce().

·         It multiplies all the elements in the array to get the factorial.


4. Find the Largest Number in an Array

Manual Version:

javascript

 

function largestNumberManual() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    let max = arr[0];

    for (let num of arr) {

        if (num > max) max = num;

    }

    console.log(`Largest number: ${max}`);

}

largestNumberManual();

 

Explanation: This code finds the largest number in an array.

·         It loops through each element in the array and keeps track of the largest number found.

Intermediate Version:

javascript

 

function largestNumberIntermediate() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Largest number: ${Math.max(...arr)}`);

}

largestNumberIntermediate();

 

Explanation: This version uses Math.max() with the spread operator (...) to find the largest number in the array.

Advanced Version:

javascript

 

function largestNumberAdvanced() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Largest number: ${arr.reduce((max, num) => (num > max ? num : max), -Infinity)}`);

}

largestNumberAdvanced();

 

Explanation: This version uses reduce() to find the largest number by comparing each element in the array.


5. Remove Duplicate Elements from an Array

Manual Version:

javascript

 

function removeDuplicatesManual() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    const unique = [];

    for (let num of arr) {

        if (!unique.includes(num)) unique.push(num);

    }

    console.log(`Array without duplicates: ${unique}`);

}

removeDuplicatesManual();

 

Explanation: This code loops through the array and adds each unique element to a new array called unique.

·         It checks if the number is already in the unique array using includes().

·        Intermediate Version:

javascript

 

function removeDuplicatesIntermediate() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Array without duplicates: ${[...new Set(arr)]}`);

}

removeDuplicatesIntermediate();

 

Explanation: This version uses a Set, which automatically removes duplicates, and then converts the Set back to an array using the spread operator.

Advanced Version:

javascript

 

function removeDuplicatesAdvanced() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Array without duplicates: ${arr.filter((num, i) => arr.indexOf(num) === i)}`);

}

removeDuplicatesAdvanced();


Explanation: This version uses filter() to create a new array, ensuring that only the first occurrence of each element is kept.

 
6. Check if a String is an Anagram of Another String

Manual Version:

javascript

 

function isAnagramManual() {

    const str1 = prompt("Enter the first string:");

    const str2 = prompt("Enter the second string:");

    const sorted1 = str1.split("").sort().join("");

    const sorted2 = str2.split("").sort().join("");

    console.log(`Are the strings anagrams? ${sorted1 === sorted2}`);

}

isAnagramManual();

 

Explanation:

·         This function takes two strings as input.

·         It splits each string into an array of characters, sorts them alphabetically, and joins them back into a string.

·         If the sorted strings are identical, the strings are anagrams of each other.

·        Intermediate Version:

javascript

 

function isAnagramIntermediate() {

    const str1 = prompt("Enter the first string:");

    const str2 = prompt("Enter the second string:");

    if (str1.length !== str2.length) return console.log("Not anagrams");

    const count = {};

    for (let char of str1) count[char] = (count[char] || 0) + 1;

    for (let char of str2) {

        if (!count[char]) return console.log("Not anagrams");

        count[char]--;

    }

    console.log("Are the strings anagrams? Yes");

}

isAnagramIntermediate();

 

Explanation:

·         This function first checks if the lengths of both strings are equal.

·         It then counts the frequency of each character in the first string using an object (count).

·         For each character in the second string, it decreases the count from the object.

·         If the count of any character is less than 0, the strings are not anagrams.

Advanced Version:

javascript

 

function isAnagramAdvanced() {

    const str1 = prompt("Enter the first string:");

    const str2 = prompt("Enter the second string:");

    const sum1 = str1.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);

    const sum2 = str2.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);

    console.log(`Are the strings anagrams? ${sum1 === sum2}`);

}

isAnagramAdvanced();

 

Explanation:

·         This function calculates the sum of the ASCII values of each character in both strings.

·         If the sums are equal, the strings are anagrams because the same characters appear in both strings, even if they are arranged differently.


7. Count the Number of Vowels in a Given String

Manual Version:

javascript

 

function countVowelsManual() {

    const str = prompt("Enter a string:");

    let count = 0;

    for (let char of str.toLowerCase()) {

        if ("aeiou".includes(char)) count++;

    }

    console.log(`Number of vowels: ${count}`);

}

countVowelsManual();

 

Explanation:

·         This function converts the string to lowercase and loops through each character.

·         It checks if the character is a vowel by checking if it’s present in the string "aeiou".

·         For each vowel, the counter (count) is incremented.

Intermediate Version:

javascript

 

function countVowelsIntermediate() {

    const str = prompt("Enter a string:");

    console.log(`Number of vowels: ${str.match(/[aeiou]/gi)?.length || 0}`);

}

countVowelsIntermediate();

 

Explanation:

·         This version uses a regular expression (/[aeiou]/gi) to match all vowels (both uppercase and lowercase).

·         match() returns an array of vowels, and we use .length to get the number of vowels.

·         If no vowels are found, it defaults to 0.

Advanced Version:

javascript

 

function countVowelsAdvanced() {

    const str = prompt("Enter a string:");

    console.log(`Number of vowels: ${[...str].reduce((count, char) => count + ("aeiou".includes(char.toLowerCase()) ? 1 : 0), 0)}`);

}

countVowelsAdvanced();

 

Explanation:

·         This version uses reduce() to count the vowels by checking each character (converted to lowercase) and adding 1 if it’s a vowel.

·         It accumulates the vowel count in count.


8. Sort an Array of Numbers in Ascending Order

Manual Version:

javascript

 

function sortArrayManual() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    for (let i = 0; i < arr.length - 1; i++) {

        for (let j = i + 1; j < arr.length; j++) {

            if (arr[i] > arr[j]) {

                [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap the elements

            }

        }

    }

    console.log(`Sorted array: ${arr}`);

}

sortArrayManual();

 

Explanation:

·         This is a simple sorting algorithm (Bubble Sort). It compares each element with every other element and swaps them if the first element is larger than the second.

·         The process repeats until the array is sorted.

·        Intermediate Version:

javascript

 

function sortArrayIntermediate() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Sorted array: ${arr.sort((a, b) => a - b)}`);

}

sortArrayIntermediate();

 

Explanation:

·         This version uses JavaScript’s built-in sort() method.

·         The sort() method sorts the array in ascending order, and the callback (a, b) => a - b ensures that the numbers are sorted numerically, not as strings.

Advanced Version:

javascript

 

function sortArrayAdvanced() {

    const arr = prompt("Enter numbers separated by spaces:").split(" ").map(Number);

    console.log(`Sorted array: ${arr.reduce((sorted, num) => {

        let inserted = false;

        for (let i = 0; i < sorted.length; i++) {

            if (num < sorted[i]) {

                sorted.splice(i, 0, num);

                inserted = true;

                break;

            }

        }

        if (!inserted) sorted.push(num);

        return sorted;

    }, [])}`);

}

sortArrayAdvanced();

 

Explanation:

·         This version implements an insertion sort algorithm.

·         It iterates over the array and inserts each number into its correct position in the already-sorted part of the array.


Prathima Tech

I am a dedicated Software Engineer with 7 years of experience in teaching and training, specializing in software development, automation, and web technologies. Passionate about simplifying complex concepts, I mentor students and professionals to build strong technical foundations. My goal is to inspire innovation and empower others to succeed in the dynamic world of technology.

Post a Comment

Previous Post Next Post