Javascript small practical interview questions and answers.
1. Reverse string JavaScript.
let name = "Ankit";
let revName = name.split("").reverse().join("");
console.log("revName---->", revName); // output : revName----> tiknA
let revNames = "";for(let i = name.length-1; i >= 0; i--) { revNames += name[i];}console.log("revNames---->", revNames); // output : revNames----> tiknA
let revNames = "";
for(let i = name.length-1; i >= 0; i--) {
revNames += name[i];
}
console.log("revNames---->", revNames); // output : revNames----> tiknA
2. Remove duplicate string from array JavaScript.
let cityName = ["pune", "ahmedabad", "nagpur", "pune"];
let uniqName = [...new Set(cityName)];
console.log("uniqName--->", uniqName);
// output : uniqName---> [ 'pune', 'ahmedabad', 'nagpur' ]
let uniqeCityName = [];let filterCityName = cityName.map(x => { uniqeCityName.indexOf(x) === -1 && uniqeCityName.push(x);});console.log("uniqeCityName--->", uniqeCityName); // output : uniqeCityName---> [ 'pune', 'ahmedabad', 'nagpur' ]
let uniqeCityName = [];
let filterCityName = cityName.map(x => {
uniqeCityName.indexOf(x) === -1 && uniqeCityName.push(x);
});
console.log("uniqeCityName--->", uniqeCityName);
// output : uniqeCityName---> [ 'pune', 'ahmedabad', 'nagpur' ]
3. Swapping of two numbers JavaScript.
let a = 10, b = 20, tmp;
tmp=a; a=b; b=tmp;
console.log("a,b--->", a,b);
// output : a,b---> 20 10
let swapNumber = [a,b] = [b,a]; // Destructuring es6 methodconsole.log("swapNumber---->", swapNumber); // output : swapNumber----> [ 10, 20 ]
let swapNumber = [a,b] = [b,a]; // Destructuring es6 method
console.log("swapNumber---->", swapNumber);
// output : swapNumber----> [ 10, 20 ]
4. Find highest and Second highest JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let maxNumer = Math.max(...numArray);
console.log('maxNumer--->', maxNumer);
// output : maxNumer---> 99
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];let highestNum, secondHigh;numArray.map(x => { if(!highestNum) highestNum = x; if(highestNum && x > highestNum){ secondHigh = highestNum ; highestNum = x; } else { if(x > secondHigh) secondHigh = x; }});console.log('highestNum, secondHigh--->', highestNum, secondHigh);// output : highestNum, secondHigh---> 99 33
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let highestNum, secondHigh;
numArray.map(x => {
if(!highestNum) highestNum = x;
if(highestNum && x > highestNum){
secondHigh = highestNum ;
highestNum = x; }
else {
if(x > secondHigh) secondHigh = x;
}
});
console.log('highestNum, secondHigh--->', highestNum, secondHigh);
// output : highestNum, secondHigh---> 99 33
5. Sorting array in Ascending and Descending order JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
// Sort in ascending order
let ascending = [...numArray].sort((a, b) => a - b);
console.log("ascending :", ascending);
// output : ascending : [ 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 33, 33, 99 ]
// Sort in descending order
let descending = [...numArray].sort((a, b) => b - a);
console.log("descending :", descending);
// output : descending : [ 99, 33, 33, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1 ]
let sortString = ["mumbai", "pune", "ahmedabad", "botad"];let ascStringSortFun = sortString.sort();console.log("ascStringSortFun---->", ascStringSortFun); // output : ascStringSortFun----> [ 'ahmedabad', 'botad', 'mumbai', 'pune' ]
let descStringSortFun = sortString.sort().reverse();console.log("descStringSortFun---->", descStringSortFun); // output : descStringSortFun----> [ 'pune', 'mumbai', 'botad', 'ahmedabad' ]
let sortString = ["mumbai", "pune", "ahmedabad", "botad"];
let ascStringSortFun = sortString.sort();
console.log("ascStringSortFun---->", ascStringSortFun);
// output : ascStringSortFun----> [ 'ahmedabad', 'botad', 'mumbai', 'pune' ]
let descStringSortFun = sortString.sort().reverse();
console.log("descStringSortFun---->", descStringSortFun);
// output : descStringSortFun----> [ 'pune', 'mumbai', 'botad', 'ahmedabad' ]
6. Find Even and Odd Numbers in an Array in JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let evenNum = numArray.filter(x => {
return x % 2 == 0 && x;
});
console.log('evenNum--->', evenNum);
// output : evenNum---> [ 6, 2, 4, 2 ]
let oddNum = numArray.filter(x => {
return x % 2 != 0 && x;
});
console.log('oddNum--->', oddNum);
// output : oddNum---> [7, 1, 3, 99, 5, 1, 33, 33, 3]
7. Unique Values - Remove duplicates in an Array JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let unqArr = [...new Set(numArray)];
console.log("unqArr--->", unqArr);
// output : unqArr---> [6, 7, 1, 2, 3, 99, 4, 5, 33]
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let uniqeArray = [];let filterNumArray = numArray.map(x => { uniqeArray.indexOf(x) === -1 && uniqeArray.push(x);});console.log("uniqeArray--->", uniqeArray); // output : uniqeArray---> [ 6, 7, 1, 2, 3, 99, 4, 5, 33]
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let uniqeArray = [];
let filterNumArray = numArray.map(x => {
uniqeArray.indexOf(x) === -1 && uniqeArray.push(x);
});
console.log("uniqeArray--->", uniqeArray);
// output : uniqeArray---> [ 6, 7, 1, 2, 3, 99, 4, 5, 33]
8. Find unique values from two array JavaScript.
let num1 = [1,22,33,44,55,99];
let num2 = [55,66,22];
let uniqData = [...new Set([...num1, ...num2])];
console.log('uniqData--->', uniqData);
// output : uniqData---> [1, 22, 33, 44, 55, 99, 66]
9. Find, Map, Filter and Reduce JavaScript.
// find : return only one value, otherwise return undeifned.
// map : return : true, false and array data
// filter : condition match the return array data otherwise return [] array
// reduce : use for mathematic operation
let x = [1, 2, 33, 44, 55, 66];
let findData = x.find((val) => { return val > 44 });
console.log("findData--->", findData); // return single value
// output : findData---> 55
let mapData = x.map((val, index) => { return val + 100; });
console.log("mapData--->", mapData); // return array
// output : mapData---> [ 101, 102, 133, 144, 155, 166 ]
let filterData = x.filter((val, index, array) => { return val > 22; });
console.log("filterData---->", filterData); // return array
// output : filterData----> [ 33, 44, 55, 66 ]
let reduceSumData = x.reduce((total, val, index, array) => { return total + val; });
console.log("reduceSumData--->", reduceSumData); // return number value
// output : reduceSumData---> 201
10. Assume the output of example in JavaScript.
// ********example 1**********
console.log("1");
setTimeout(() => {
console.log("2");
},0);
setTimeout(() => {
console.log("3");
});
console.log("4");
// output : 1 4 2 3
// ********example 2**********
function logger(a,b,a) {
console.log('a,b,a--->', a,b,a);
}
logger(1,2,3,4);
// output : a,b,a---> 3 2 3
// ********example 3**********
let aa = 5;
console.log('aa++--->',aa++);
// output : aa++---> 5
aa = 5;
console.log('++aa--->',++aa);
// output : ++aa---> 6
let bb = 5;
console.log('bb-- --->',bb--);
// output : bb-- ---> 5
bb = 5;
console.log('--bb --->',--bb);
// output : --bb ---> 4
// ********example 4**********
console.log(1);
for(let i=2;i<=10;i++){ console.log(i);}
setTimeout(() => { console.log(11)}, 3000)
let promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('success') }, 500);})
setTimeout(() => { console.log(12)}, 500)
promise.then(res => { console.log(res)})
console.log(13);
// output : 1 2 3 4 5 6 7 8 9 10 13 success 12 11
// ********example 4**********
console.log(1);
for(let i=2;i<=10;i++){
console.log(i);
}
setTimeout(() => {
console.log(11)
}, 3000)
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 500);
})
setTimeout(() => {
console.log(12)
}, 500)
promise.then(res => {
console.log(res)
})
console.log(13);
// output : 1 2 3 4 5 6 7 8 9 10 13 success 12 11
11. Callbacks - Promises - Async/Await in JavaScript.
// *******callback********
function test3(callback) {
console.log('test3---->');
callback();
}
function test4() {
console.log('test4---->');
}
test3(test4);
// output :
// test3---->
// test4---->
// *******Promises***********
function test8() {
console.log('test8--->');
return new Promise((resolve, reject) => {
resolve();
// reject('reject error---->');
})
}
function test9() {
console.log('test9--->');
}
test8().then(test9).catch(e => console.log('e--->', e));
// output :
// test8--->
// test9--->
// *******Async/Await********
async function test1() {
console.log('test1---->');
await test2();
}
function test2() {
console.log('test2---->');
}
test1();
// output :
// test1---->
// test2---->
12. Event loop in JavaScript.
// ****event loop******
function test5() {
console.log('test5---->');
}
function test6() {
setTimeout(() => {
console.log('test6---->'); // execute after 5 second
}, 5000);
}
function test7() {
console.log('test7---->');
}
test5();
test6();
test7();
// output :
// test5---->
// test7---->
// test6---->
13. Event loop in JavaScript. Implement deepMerge, Arrays → concatenate, Objects → recursive merge
const a = {
user: { name: "Akshay", roles: ["admin"] },
settings: { theme: "dark" },
};
const b = {
user: { roles: ["editor"], age: 25 },
settings: { lang: "en" },
};
console.log(deepMerge(a, b));
// output :
{
user: { name: "Akshay", roles: ["admin", "editor"], age: 25 },
settings: { theme: "dark", lang: "en" }
}
// Solution :
function deepMerge(obj1, obj2) {
// If both are arrays → concatenate
if (Array.isArray(obj1) && Array.isArray(obj2)) {
return [...obj1, ...obj2];
}
// If both are objects → recursive merge
if (isObject(obj1) && isObject(obj2)) {
const result = {};
const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
for (const key of keys) {
if (key in obj1 && key in obj2) {
result[key] = deepMerge(obj1[key], obj2[key]);
} else if (key in obj1) {
result[key] = obj1[key];
} else {
result[key] = obj2[key];
}
}
return result;
}
// Primitive values → obj2 overrides obj1
return obj2;
}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
14. Correct and solve this function
function getUser(id) {
return setTimeout(() => {
return { id: id, name: "John" };
}, 500);
}
function getOrders(userId) {
return setTimeout(() => {
return [
{ id: 1, amount: 200 },
{ id: 2, amount: 300 },
];
}, 500);
}
async function getUserData() {
const user = await getUser(1);
const orders = await getOrders(1);
console.log({
user,
orders,
});
}
getUserData();
// Solution
function getUser(id) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: id, name: "John" });
}, 500);
});
}
function getOrders(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, amount: 200 },
{ id: 2, amount: 300 },
]);
}, 500);
});
}
async function getUserData() {
const user = await getUser(1);
const orders = await getOrders(1);
console.log("user---->", user);
console.log("orders---->", orders);
// Combined Output:
// console.log({ user, orders });
}
getUserData();
// Output ::
// user----> { id: 1, name: "John" }
// orders----> [ { id: 1, amount: 200 }, { id: 2, amount: 300 } ]
15. Flat this array without any inbuilt method
const arr = [1, 2, [3, [4, 5], 6], 7];
function flattenArray(input) {
let result = [];
function helper(element) {
// If the element is NOT an array → push directly
if (typeof element !== "object") {
result.push(element);
return;
}
// Manually loop array elements (no built-ins)
for (let i = 0; i < element.length; i++) {
helper(element[i]);
}
}
helper(input);
return result;
}
console.log(flattenArray(arr));
// Output: [1, 2, 3, 4, 5, 6, 7]

No comments:
Post a Comment