Certainly! Here’s a curated list of 100 practical JavaScript coding examples commonly asked in technical interviews. These examples cover a wide range of topics, including algorithms, data structures, and core JavaScript concepts, to help you prepare effectively.
🔹 1–10: Basic JavaScript Concepts
- Sum of Two Numbers
const add = (a, b) => a + b; - Check if a Number is Prime
const isPrime = num => num > 1 && ![...Array(num).keys()].slice(2).some(i => num % i === 0); - Factorial of a Number
const factorial = n => (n === 0 ? 1 : n * factorial(n - 1)); - Fibonacci Series
const fibonacci = n => { let [a, b] = [0, 1]; while (n--) { [a, b] = [b, a + b]; } return a; }; - Reverse a String
const reverseString = str => str.split('').reverse().join(''); - Palindrome Check
const isPalindrome = str => str === str.split('').reverse().join(''); - Find Maximum in Array
const findMax = arr => Math.max(...arr); - Find Minimum in Array
const findMin = arr => Math.min(...arr); - Count Vowels in a String
const countVowels = str => (str.match(/[aeiou]/gi) || []).length; - Sum of Array Elements
const sumArray = arr => arr.reduce((acc, val) => acc + val, 0);
🔹 11–20: Array Manipulation
- Array Rotation
const rotateArray = (arr, k) => [...arr.slice(k), ...arr.slice(0, k)]; - Remove Duplicates from Array
const removeDuplicates = arr => [...new Set(arr)]; - Find Intersection of Two Arrays
const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value)); - Flatten Nested Array
const flattenArray = arr => arr.flat(Infinity); - Find Missing Number
const findMissing = arr => { const n = arr.length + 1; const total = (n * (n + 1)) / 2; return total - arr.reduce((acc, val) => acc + val, 0); }; - Shuffle Array
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5); - Move Zeros to End
const moveZeros = arr => { const zeros = arr.filter(val => val === 0); const nonZeros = arr.filter(val => val !== 0); return [...nonZeros, ...zeros]; }; - Chunk Array into Subarrays
const chunkArray = (arr, size) => { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; }; - Find First Non-Repeating Character
const firstNonRepeating = str => { for (let i = 0; i < str.length; i++) { if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) { return str[i]; } } return null; }; - Group Elements by Condition
const groupBy = (arr, condition) => { return arr.reduce((acc, item) => { const key = condition(item); if (!acc[key]) acc[key] = []; acc[key].push(item); return acc; }, {}); };
🔹 21–30: String Manipulation
- Count Occurrences of a Character
const countChar = (str, char) => (str.match(new RegExp(char, 'g')) || []).length; - Capitalize First Letter of Each Word
const capitalizeWords = str => str.replace(/\b\w/g, char => char.toUpperCase()); - Reverse Each Word in a Sentence
const reverseWords = str => str.split(' ').reverse().join(' '); - Longest Palindromic Substring
const longestPalindrome = str => { const expand = (left, right) => { while (left >= 0 && right < str.length && str[left] === str[right]) { left--; right++; } return str.slice(left + 1, right); }; let result = ''; for (let i = 0; i < str.length; i++) { const odd = expand(i, i); const even = expand(i, i + 1); const longer = odd.length > even.length ? odd : even; if (longer.length > result.length) result = longer; } return result; }; - Check Balanced Parentheses
const isBalanced = str => { const stack = []; const map = { '(': ')', '{': '}', '[': ']' }; for (let char of str) { if (map[char]) { stack.push(char); } else if (Object.values(map).includes(char)) { if (map[stack.pop()] !== char) return false; } } return !stack.length; }; - Remove All Whitespace
const removeWhitespace = str => str.replace(/\s+/g, ''); - Convert String to Title Case
const toTitleCase = str => str.replace(/\b\w/g, char => char.toUpperCase()); - Find Longest Word in a Sentence
const longestWord = str => str.split(' ').reduce((longest, current) => current.length > longest.length ? current : longest, ''); - Check if String Contains Only Digits
const isDigitsOnly = str => /^\d+$/.test(str); - Convert String to Number
const toNumber = str => Number(str);
🔹 31–40: Object Manipulation
- Clone an Object
const cloneObject = obj => ({ ...obj });
- Check Deep Equality of Two Objects
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
- Merge Two Objects
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
- Invert Object Keys and Values
const invertObject = obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
- Count Object Keys
const countKeys = obj => Object.keys(obj).length;
- Convert Object to Array
const objToArray = obj => Object.entries(obj);
- Convert Array to Object
const arrayToObj = arr => Object.fromEntries(arr);
- Check if Object is Empty
const isEmpty = obj => Object.keys(obj).length === 0;
- Access Nested Property
const getNested = (obj, path) => path.split('.').reduce((acc, part) => acc?.[part], obj);
- Rename Object Key
const renameKey = (obj, oldKey, newKey) => {
const { [oldKey]: old, ...rest } = obj;
return { ...rest, [newKey]: old };
};
🔹 41–50: Math and Date
- Get Random Number Between Two Values
const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
- Generate a Random Hex Color
const randomHex = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16);
- Convert Degrees to Radians
const degToRad = deg => deg * (Math.PI / 180);
- Check Leap Year
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
- Get Days Between Two Dates
const daysBetween = (d1, d2) => Math.abs((d2 - d1) / (1000 * 60 * 60 * 24));
- Format Date to
YYYY-MM-DD
const formatDate = date => date.toISOString().split('T')[0];
- Get Current Time
const currentTime = () => new Date().toLocaleTimeString();
- Add Days to Date
const addDays = (date, days) => new Date(date.setDate(date.getDate() + days));
- Check if Date is Weekend
const isWeekend = date => [0, 6].includes(date.getDay());
- Compare Two Dates
const isSameDate = (d1, d2) => d1.toDateString() === d2.toDateString();
🔹 51–70: Recursion and Iteration
- Recursive Sum of Array
const sumRec = arr => arr.length === 0 ? 0 : arr[0] + sumRec(arr.slice(1));
- Recursive Fibonacci
const fib = n => (n <= 1 ? n : fib(n - 1) + fib(n - 2));
- Recursive Factorial
const factorial = n => (n <= 1 ? 1 : n * factorial(n - 1));
- Print Numbers Using Recursion
const print = n => { if (n > 0) { console.log(n); print(n - 1); } };
- Nested Object Traversal
const traverse = obj => {
for (let key in obj) {
if (typeof obj[key] === 'object') traverse(obj[key]);
else console.log(key, obj[key]);
}
};
- Flatten Object
const flatten = (obj, prefix = '', res = {}) => {
for (const k in obj) {
const val = obj[k], pre = prefix.length ? `${prefix}.${k}` : k;
if (typeof val === 'object') flatten(val, pre, res);
else res[pre] = val;
}
return res;
};
- Binary Search
const binarySearch = (arr, x) => {
let l = 0, r = arr.length - 1;
while (l <= r) {
const mid = Math.floor((l + r) / 2);
if (arr[mid] === x) return mid;
x < arr[mid] ? r = mid - 1 : l = mid + 1;
}
return -1;
};
- Bubble Sort
const bubbleSort = arr => {
for (let i = 0; i < arr.length; i++)
for (let j = 0; j < arr.length - i - 1; j++)
if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
return arr;
};
- Quick Sort
const quickSort = arr => {
if (arr.length < 2) return arr;
const [pivot, ...rest] = arr;
return [...quickSort(rest.filter(x => x <= pivot)), pivot, ...quickSort(rest.filter(x => x > pivot))];
};
- Power Function
const power = (x, n) => n === 0 ? 1 : x * power(x, n - 1);
🔹 71–90: DOM and Events (Browser)
- Get Element by ID
const el = document.getElementById('id');
- Add Event Listener
document.querySelector('button').addEventListener('click', () => alert('Clicked'));
- Change Inner Text
document.getElementById('demo').innerText = 'Hello';
- Create Element
const div = document.createElement('div');
div.textContent = 'New';
document.body.appendChild(div);
- Toggle Class
document.getElementById('box').classList.toggle('active');
- Change Background Color
document.body.style.backgroundColor = 'lightblue';
- Form Validation
document.querySelector('form').addEventListener('submit', e => {
e.preventDefault();
const input = document.querySelector('#name');
if (input.value === '') alert('Name required');
});
- Live Character Counter
document.querySelector('#input').addEventListener('input', e => {
document.querySelector('#count').innerText = e.target.value.length;
});
- Scroll to Top
window.scrollTo({ top: 0, behavior: 'smooth' });
- Detect Key Press
document.addEventListener('keydown', e => console.log(`Key: ${e.key}`));
🔹 91–100: Miscellaneous
- Debounce Function
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
- Throttle Function
const throttle = (fn, delay) => {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn(...args);
}
};
};
- Memoization
const memoize = fn => {
const cache = {};
return arg => (cache[arg] = cache[arg] || fn(arg));
};
- Generate UUID
const uuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
});
- Detect Type
const getType = val => Object.prototype.toString.call(val).slice(8, -1);
- Deep Clone Object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
- Check if Array is Sorted
const isSorted = arr => arr.every((val, i, a) => i === 0 || a[i - 1] <= val);
- Generate Range of Numbers
const range = (
start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);
- Convert Decimal to Binary
const toBinary = n => n.toString(2);
- Convert Binary to Decimal
const toDecimal = bin => parseInt(bin, 2);