Write a JavaScript program to reverse a string.

Answer:

function reverseString(str){
return str.split('').reverse().join('');
}
console.log(reverseString("hello"));

Write a program to check if a number is prime.

Answer:

function isPrime(num){
for(let i=2;i<num;i++){ if(num%i===0) return false; } return num>1;
}
console.log(isPrime(7));

Find the largest number in an array.

Answer:

let arr=[10,20,50,30];
let max=Math.max(...arr);
console.log(max);

Remove duplicate values from an array.

Answer:

let arr=[1,2,2,3,4,4];
let unique=[...new Set(arr)];
console.log(unique);

Check if a string is palindrome.

Answer:

function palindrome(str){
let rev=str.split('').reverse().join('');
return str===rev;
}
console.log(palindrome("madam"));

Find the factorial of a number.

Answer:

function factorial(n){
if(n===0) return 1;
return n*factorial(n-1);
}
console.log(factorial(5));

Capitalize the first letter of each word.

Answer:

function capitalize(str){
return str.split(" ").map(w=>w[0].toUpperCase()+w.slice(1)).join(" ");
}
console.log(capitalize("javascript interview questions"));

Find the sum of array elements.

Answer:

let arr=[1,2,3,4];
let sum=arr.reduce((a,b)=>a+b,0);
console.log(sum);

Flatten a nested array.

Answer:

let arr=[1,[2,3],[4,[5]]];
let flat=arr.flat(Infinity);
console.log(flat);

Swap two numbers without third variable.

Answer:

let a=5,b=10;
[a,b]=[b,a];
console.log(a,b);

Find duplicates in an array.

let arr=[1,2,3,2,4,1];
let dup=arr.filter((item,index)=>arr.indexOf(item)!==index);
console.log(dup);

Convert array to object.

let arr=["a","b","c"];
let obj={...arr};
console.log(obj);

Merge two arrays.

let a=[1,2];
let b=[3,4];
let c=[...a,...b];
console.log(c);

Find even numbers from array.

let arr=[1,2,3,4,5,6];
let even=arr.filter(n=>n%2===0);
console.log(even);

Find longest word in string.

function longest(str){
return str.split(" ").reduce((a,b)=>a.length>b.length?a:b);
}
console.log(longest("javascript coding interview questions"));

Generate random number.

let rand=Math.floor(Math.random()*100);
console.log(rand);

Convert string to array.

let str="hello";
let arr=str.split("");
console.log(arr);

Count vowels in string.

function countVowel(str){
return str.match(/[aeiou]/gi).length;
}
console.log(countVowel("javascript"));

Sort array in ascending order.

let arr=[5,3,8,1];
arr.sort((a,b)=>a-b);
console.log(arr);

Sort array in descending order.

arr.sort((a,b)=>b-a);

Find intersection of two arrays.

let a=[1,2,3];
let b=[2,3,4];
let inter=a.filter(x=>b.includes(x));
console.log(inter);

Find union of two arrays.

let union=[...new Set([...a,...b])];

Convert object to array.

let obj={a:1,b:2};
let arr=Object.entries(obj);
console.log(arr);

Get keys of object.

Object.keys(obj);

Get values of object.

Object.values(obj);

Check if array includes value.

arr.includes(5);

Remove falsy values from array.

let arr=[0,1,false,2,"",3];
let clean=arr.filter(Boolean);

Clone an object.

let clone={...obj};

Deep clone object.

let deep=JSON.parse(JSON.stringify(obj));

Delay function execution.

setTimeout(()=>console.log("Hello"),2000);

Repeat function execution.

setInterval(()=>console.log("Running"),1000);

Fetch API example.

fetch("https://api.example.com")
.then(res=>res.json())
.then(data=>console.log(data));

Async Await example.

async function getData(){
let res=await fetch("https://api.example.com");
let data=await res.json();
console.log(data);
}

Create promise.

let p=new Promise((resolve,reject)=>{
resolve("Success");
});

Promise chaining.

promise.then(data=>console.log(data))
.catch(err=>console.log(err));

Debounce function example.

function debounce(fn,delay){
let timer;
return function(){
clearTimeout(timer);
timer=setTimeout(()=>fn(),delay);
}
}

Throttle function example.

function throttle(fn,limit){
let flag=true;
return function(){
if(flag){
fn();
flag=false;
setTimeout(()=>flag=true,limit);
}
}
}

Event listener example.

document.getElementById("btn")
.addEventListener("click",()=>alert("Clicked"));

Create class in JavaScript.

class Person{
constructor(name){
this.name=name;
}
}

Inheritance example.

class Student extends Person{
constructor(name,course){
super(name);
this.course=course;
}
}

Find frequency of array elements.

let arr=[1,2,2,3];
let freq={};
arr.forEach(x=>freq[x]=(freq[x]||0)+1);

Check object is empty.

Object.keys(obj).length===0

Convert number to string.

let str=num.toString();

Convert string to number.

let num=Number(str);

Generate unique ID.

let id=Date.now();

Remove last element from array.

arr.pop();

Add element to array.

arr.push(10);

Insert element at beginning.

arr.unshift(5);

Remove first element.

arr.shift();

Convert array to string.

arr.join(",");

Check if value is array.

Array.isArray(arr);

Get current date.

let d=new Date();

Get current timestamp.

Date.now();

Round number.

Math.round(4.5);

Generate random color.

let color="#"+Math.floor(Math.random()*16777215).toString(16);

Find minimum number.

Math.min(...arr);

Find maximum number.

Math.max(...arr);

Check if property exists in object.

"age" in obj

Delete object property.

delete obj.age;

Freeze object.

Object.freeze(obj);

Seal object.

Object.seal(obj);

Loop through object.

for(let key in obj){
console.log(key,obj[key]);
}

Loop through array.

arr.forEach(x=>console.log(x));

Find index of element.

arr.indexOf(5);

Slice array.

arr.slice(1,3);

Splice array.

arr.splice(2,1);

Convert array to set.

new Set(arr);

Convert set to array.

[...set];

Find length of string.

str.length;

Repeat string.

str.repeat(3);

Trim string.

str.trim();

Check string includes word.

str.includes("javascript");

Replace string value.

str.replace("old","new");

Convert string to uppercase.

str.toUpperCase();

Convert string to lowercase.

str.toLowerCase();

Split string.

str.split(" ");

Join array.

arr.join("-");

📢 Join Our WhatsApp Channel

💼 Get Daily IT Job Updates, Interview Preparation Tips & Instant Alerts directly on WhatsApp.

👉 Join WhatsApp Now

📢 Join Our Telegram Channel

💼 Get Daily IT Job Updates, Interview Tips & Exclusive Alerts directly on Telegram!

👉 Join Telegram

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2022 - 2025 itfreesource.com

Enable Notifications OK No thanks