Question 1: Reverse a String
Write a function that takes a string as input and returns its reverse.
function reverseString(str) {
return str.split('').reverse().join('');
}
// Test
console.log(reverseString('hello')); // Output: "olleh"
Question 2: Check for Palindrome
Write a function that checks if a given string is a palindrome (reads the same forwards and backward).
function isPalindrome(str) {
const reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
// Test
console.log(isPalindrome('racecar')); // Output: true
console.log(isPalindrome('hello')); // Output: false
Question 3: Find the First Non-Repeated Character
Write a function that takes a string as input and returns the first non-repeated character in the string.
function firstNonRepeatedChar(str) {
const charCount = {};
for (const char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (const char of str) {
if (charCount[char] === 1) {
return char;
}
}
return null; // If all characters are repeated
}
// Test
console.log(firstNonRepeatedChar('abacdbe')); // Output: "c"
Question 4: FizzBuzz
Write a function that prints the numbers from 1 to n. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz" instead of the number. For numbers that are multiples of both 3 and 5, print "FizzBuzz".
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
let output = '';
if (i % 3 === 0) {
output += 'Fizz';
}
if (i % 5 === 0) {
output += 'Buzz';
}
console.log(output || i);
}
}
// Test
fizzBuzz(15); // Output: 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"
Question 5: Remove Duplicates from an Array
Write a function that takes an array as input and returns a new array with duplicates removed.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Test
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]
These are just a few examples of JavaScript coding interview questions. Remember to practice and understand the concepts thoroughly to perform well in technical interviews.
Top comments (0)