7 interview questions about Javascript programming
2 min readJan 24, 2023
How would you reverse a string in JavaScript?
function reverseString(str) {
return str.split('').reverse().join('');
}
How would you check if a given number is a prime number in JavaScript?
function isPrime(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
How would you find the missing number in an array of consecutive integers?
function findMissingNumber(arr) {
let sum = 0;
let expectedSum = (arr.length + 1) * (arr[0] + arr[arr.length - 1]) / 2;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return expectedSum - sum;
}
How would you implement a binary search algorithm in JavaScript?
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
How would you implement a breadth-first search algorithm in JavaScript?
function breadthFirstSearch(root, target) {
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
if (node.value === target) {
return node;
}
for (let i = 0; i < node.children.length; i++) {
queue.push(node.children[i]);
}
}
return null;
}
How would you find the longest common prefix in an array of strings?
function longestCommonPrefix(strs) {
if (strs.length === 0) {
return '';
}
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (prefix === '') {
return '';
}
}
}
return prefix;
}
How would you merge two sorted arrays into one sorted array in JavaScript?
let arr1 = [1, 3, 5, 7];
let arr2 = [2, 4, 6, 8];
let mergedArr = arr1.concat(arr2);
mergedArr.sort((a, b) => a - b);