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

  1. Sum of Two Numbers
    const add = (a, b) => a + b;
    
  2. Check if a Number is Prime
    const isPrime = num => num > 1 && ![...Array(num).keys()].slice(2).some(i => num % i === 0);
    
  3. Factorial of a Number
    const factorial = n => (n === 0 ? 1 : n * factorial(n - 1));
    
  4. Fibonacci Series
    const fibonacci = n => {
      let [a, b] = [0, 1];
      while (n--) {
        [a, b] = [b, a + b];
      }
      return a;
    };
    
  5. Reverse a String
    const reverseString = str => str.split('').reverse().join('');
    
  6. Palindrome Check
    const isPalindrome = str => str === str.split('').reverse().join('');
    
  7. Find Maximum in Array
    const findMax = arr => Math.max(...arr);
    
  8. Find Minimum in Array
    const findMin = arr => Math.min(...arr);
    
  9. Count Vowels in a String
    const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
    
  10. Sum of Array Elements
    const sumArray = arr => arr.reduce((acc, val) => acc + val, 0);
    

🔹 11–20: Array Manipulation

  1. Array Rotation
    const rotateArray = (arr, k) => [...arr.slice(k), ...arr.slice(0, k)];
    
  2. Remove Duplicates from Array
    const removeDuplicates = arr => [...new Set(arr)];
    
  3. Find Intersection of Two Arrays
    const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));
    
  4. Flatten Nested Array
    const flattenArray = arr => arr.flat(Infinity);
    
  5. 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);
    };
    
  6. Shuffle Array
    const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
    
  7. Move Zeros to End
    const moveZeros = arr => {
      const zeros = arr.filter(val => val === 0);
      const nonZeros = arr.filter(val => val !== 0);
      return [...nonZeros, ...zeros];
    };
    
  8. 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;
    };
    
  9. 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;
    };
    
  10. 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

  1. Count Occurrences of a Character
    const countChar = (str, char) => (str.match(new RegExp(char, 'g')) || []).length;
    
  2. Capitalize First Letter of Each Word
    const capitalizeWords = str => str.replace(/\b\w/g, char => char.toUpperCase());
    
  3. Reverse Each Word in a Sentence
    const reverseWords = str => str.split(' ').reverse().join(' ');
    
  4. 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;
    };
    
  5. 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;
    };
    
  6. Remove All Whitespace
    const removeWhitespace = str => str.replace(/\s+/g, '');
    
  7. Convert String to Title Case
    const toTitleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());
    
  8. Find Longest Word in a Sentence
    const longestWord = str => str.split(' ').reduce((longest, current) => current.length > longest.length ? current : longest, '');
    
  9. Check if String Contains Only Digits
    const isDigitsOnly = str => /^\d+$/.test(str);
    
  10. Convert String to Number
    const toNumber = str => Number(str);
    

🔹 31–40: Object Manipulation

  1. Clone an Object
const cloneObject = obj => ({ ...obj });
  1. Check Deep Equality of Two Objects
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
  1. Merge Two Objects
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
  1. Invert Object Keys and Values
const invertObject = obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
  1. Count Object Keys
const countKeys = obj => Object.keys(obj).length;
  1. Convert Object to Array
const objToArray = obj => Object.entries(obj);
  1. Convert Array to Object
const arrayToObj = arr => Object.fromEntries(arr);
  1. Check if Object is Empty
const isEmpty = obj => Object.keys(obj).length === 0;
  1. Access Nested Property
const getNested = (obj, path) => path.split('.').reduce((acc, part) => acc?.[part], obj);
  1. Rename Object Key
const renameKey = (obj, oldKey, newKey) => {
  const { [oldKey]: old, ...rest } = obj;
  return { ...rest, [newKey]: old };
};

🔹 41–50: Math and Date

  1. Get Random Number Between Two Values
const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  1. Generate a Random Hex Color
const randomHex = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16);
  1. Convert Degrees to Radians
const degToRad = deg => deg * (Math.PI / 180);
  1. Check Leap Year
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  1. Get Days Between Two Dates
const daysBetween = (d1, d2) => Math.abs((d2 - d1) / (1000 * 60 * 60 * 24));
  1. Format Date to YYYY-MM-DD
const formatDate = date => date.toISOString().split('T')[0];
  1. Get Current Time
const currentTime = () => new Date().toLocaleTimeString();
  1. Add Days to Date
const addDays = (date, days) => new Date(date.setDate(date.getDate() + days));
  1. Check if Date is Weekend
const isWeekend = date => [0, 6].includes(date.getDay());
  1. Compare Two Dates
const isSameDate = (d1, d2) => d1.toDateString() === d2.toDateString();

🔹 51–70: Recursion and Iteration

  1. Recursive Sum of Array
const sumRec = arr => arr.length === 0 ? 0 : arr[0] + sumRec(arr.slice(1));
  1. Recursive Fibonacci
const fib = n => (n <= 1 ? n : fib(n - 1) + fib(n - 2));
  1. Recursive Factorial
const factorial = n => (n <= 1 ? 1 : n * factorial(n - 1));
  1. Print Numbers Using Recursion
const print = n => { if (n > 0) { console.log(n); print(n - 1); } };
  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]);
  }
};
  1. 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;
};
  1. 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;
};
  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;
};
  1. 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))];
};
  1. Power Function
const power = (x, n) => n === 0 ? 1 : x * power(x, n - 1);

🔹 71–90: DOM and Events (Browser)

  1. Get Element by ID
const el = document.getElementById('id');
  1. Add Event Listener
document.querySelector('button').addEventListener('click', () => alert('Clicked'));
  1. Change Inner Text
document.getElementById('demo').innerText = 'Hello';
  1. Create Element
const div = document.createElement('div');
div.textContent = 'New';
document.body.appendChild(div);
  1. Toggle Class
document.getElementById('box').classList.toggle('active');
  1. Change Background Color
document.body.style.backgroundColor = 'lightblue';
  1. Form Validation
document.querySelector('form').addEventListener('submit', e => {
  e.preventDefault();
  const input = document.querySelector('#name');
  if (input.value === '') alert('Name required');
});
  1. Live Character Counter
document.querySelector('#input').addEventListener('input', e => {
  document.querySelector('#count').innerText = e.target.value.length;
});
  1. Scroll to Top
window.scrollTo({ top: 0, behavior: 'smooth' });
  1. Detect Key Press
document.addEventListener('keydown', e => console.log(`Key: ${e.key}`));

🔹 91–100: Miscellaneous

  1. Debounce Function
const debounce = (fn, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
};
  1. Throttle Function
const throttle = (fn, delay) => {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn(...args);
    }
  };
};
  1. Memoization
const memoize = fn => {
  const cache = {};
  return arg => (cache[arg] = cache[arg] || fn(arg));
};
  1. 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);
});
  1. Detect Type
const getType = val => Object.prototype.toString.call(val).slice(8, -1);
  1. Deep Clone Object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
  1. Check if Array is Sorted
const isSorted = arr => arr.every((val, i, a) => i === 0 || a[i - 1] <= val);
  1. Generate Range of Numbers
const range = (
start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);
  1. Convert Decimal to Binary
const toBinary = n => n.toString(2);
  1. Convert Binary to Decimal
const toDecimal = bin => parseInt(bin, 2);
Back to list

Leave a Reply

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