DEV Community

Javascript Developer
Javascript Developer

Posted on

50 Most Useful JavaScript Snippets

1. Generating a Random Number

let randomNum = Math.floor(Math.random() * maxNum);
Enter fullscreen mode Exit fullscreen mode

2. Checking If an Object is Empty

function isEmptyObject(obj) { 
  return Object.keys(obj).length === 0; 
}
Enter fullscreen mode Exit fullscreen mode

3. Creating a Countdown Timer

function countdownTimer(minutes) { 
  let seconds = minutes * 60;
  let interval = setInterval(() => {
    if (seconds <= 0) {
      clearInterval(interval);
      console.log("Time's up!");
    } else {
      console.log(`${Math.floor(seconds / 60)}:${seconds % 60}`);
      seconds--;
    }
  }, 1000);
}
Enter fullscreen mode Exit fullscreen mode

4. Sorting an Array of Objects

function sortByProperty(arr, property) { 
  return arr.sort((a, b) => (a[property] > b[property]) ? 1 : -1); 
}
Enter fullscreen mode Exit fullscreen mode

5. Removing Duplicates from an Array

let uniqueArr = [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

6. Truncating a String

function truncateString(str, num) { 
  return str.length > num ? str.slice(0, num) + "..." : str; 
}
Enter fullscreen mode Exit fullscreen mode

7. Converting a String to Title Case

function toTitleCase(str) { 
  return str.replace(/\b\w/g, txt => txt.toUpperCase()); 
}
Enter fullscreen mode Exit fullscreen mode

8. Checking If a Value Exists in an Array

let isValueInArray = arr.includes(value);
Enter fullscreen mode Exit fullscreen mode

9. Reversing a String

let reversedStr = str.split("").reverse().join("");
Enter fullscreen mode Exit fullscreen mode

10. Creating a New Array from an Existing Array

let newArr = oldArr.map(item => item + 1);
Enter fullscreen mode Exit fullscreen mode

11. Debouncing Function Calls

function debounce(func, delay) { 
  let timeout; 
  return function(...args) { 
    clearTimeout(timeout); 
    timeout = setTimeout(() => func.apply(this, args), delay); 
  }; 
}
Enter fullscreen mode Exit fullscreen mode

12. Throttling Function Calls

function throttle(func, limit) { 
  let lastFunc; 
  let lastRan; 
  return function(...args) { 
    if (!lastRan) { 
      func.apply(this, args); 
      lastRan = Date.now(); 
    } else { 
      clearTimeout(lastFunc); 
      lastFunc = setTimeout(function() { 
        if ((Date.now() - lastRan) >= limit) { 
          func.apply(this, args); 
          lastRan = Date.now(); 
        } 
      }, limit - (Date.now() - lastRan)); 
    } 
  }; 
}
Enter fullscreen mode Exit fullscreen mode

13. Cloning an Object

const cloneObject = (obj) => ({ ...obj });
Enter fullscreen mode Exit fullscreen mode

14. Merging Two Objects

const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
Enter fullscreen mode Exit fullscreen mode

15. Checking for Palindrome Strings

function isPalindrome(str) { 
  const cleanedStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); 
  return cleanedStr === cleanedStr.split('').reverse().join(''); 
}
Enter fullscreen mode Exit fullscreen mode

16. Counting Occurrences in an Array

const countOccurrences = (arr) => 
  arr.reduce((acc, val) => (acc[val] ? acc[val]++ : acc[val] = 1, acc), {});
Enter fullscreen mode Exit fullscreen mode

17. Getting the Day of the Year from a Date Object

const dayOfYear = date => 
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
Enter fullscreen mode Exit fullscreen mode

18. Filtering Unique Values from an Array

const uniqueValues = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

19. Converting Degrees to Radians

const degreesToRads = deg => (deg * Math.PI) / 180;
Enter fullscreen mode Exit fullscreen mode

20. Delaying Function Execution

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
Enter fullscreen mode Exit fullscreen mode

21. Flattening a Nested Array

const flattenArray = arr => arr.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

22. Getting a Random Item from an Array

const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];
Enter fullscreen mode Exit fullscreen mode

23. Capitalizing the First Letter of a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Enter fullscreen mode Exit fullscreen mode

24. Finding the Max Value in an Array

const maxVal = arr => Math.max(...arr);
Enter fullscreen mode Exit fullscreen mode

25. Finding the Min Value in an Array

const minVal = arr => Math.min(...arr);
Enter fullscreen mode Exit fullscreen mode

26. Shuffling an Array

function shuffleArray(arr) { 
  return arr.sort(() => Math.random() - 0.5); 
}
Enter fullscreen mode Exit fullscreen mode

27. Removing Falsy Values from an Array

const removeFalsy = arr => arr.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

28. Generating a Range of Numbers

const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);
Enter fullscreen mode Exit fullscreen mode

29. Checking if Two Arrays are Equal

const arraysEqual = (a, b) => 
  a.length === b.length && a.every((val, i) => val === b[i]);
Enter fullscreen mode Exit fullscreen mode

30. Checking if a Number is Even

const isEven = num => num % 2 === 0;
Enter fullscreen mode Exit fullscreen mode

31. Checking if a Number is Odd

const isOdd = num => num % 2 !== 0;
Enter fullscreen mode Exit fullscreen mode

32. Removing Whitespace from a String

const removeSpaces = str => str.replace(/\s+/g, '');
Enter fullscreen mode Exit fullscreen mode

33. Checking If a String is JSON

function isJSON(str) { 
  try { 
    JSON.parse(str); 
    return true; 
  } catch { 
    return false; 
  } 
}
Enter fullscreen mode Exit fullscreen mode

34. Deep Cloning an Object

const deepClone = obj => JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

35. Checking if a Number is Prime

function isPrime(num) {
  if (num <= 1) return false;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

36. Finding Factorial of a Number

const factorial = num => 
  num <= 1 ? 1 : num * factorial(num - 1);
Enter fullscreen mode Exit fullscreen mode

37. Getting Current Timestamp

const timestamp = Date.now();
Enter fullscreen mode Exit fullscreen mode

38. Formatting Date as YYYY-MM-DD

const formatDate = date => date.toISOString().split('T')[0];
Enter fullscreen mode Exit fullscreen mode

39. Generating UUID (Simple)

const uuid = () => 
  'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
Enter fullscreen mode Exit fullscreen mode

40. Checking if an Object has a Property

const hasProp = (obj, key) => key in obj;
Enter fullscreen mode Exit fullscreen mode

41. Getting Query Parameters from URL

const getQueryParams = url => 
  Object.fromEntries(new URLSearchParams(new URL(url).search));
Enter fullscreen mode Exit fullscreen mode

42. Escaping HTML Special Characters

const escapeHTML = str => 
  str.replace(/[&<>'"]/g, tag => ({
    '&':'&amp;','<':'&lt;','>':'&gt;',
    "'":'&#39;', '"':'&quot;'
  }[tag]));
Enter fullscreen mode Exit fullscreen mode

43. Unescaping HTML Special Characters

const unescapeHTML = str => 
  str.replace(/&(amp|lt|gt|#39|quot);/g, match => ({
    '&amp;':'&','&lt;':'<','&gt;':'>',
    '&#39;':"'", '&quot;':'"'
  }[match]));
Enter fullscreen mode Exit fullscreen mode

44. Sleep Function using Promise

const sleep = ms => new Promise(res => setTimeout(res, ms));
Enter fullscreen mode Exit fullscreen mode

45. Sum of Array Elements

const sumArray = arr => arr.reduce((a, b) => a + b, 0);
Enter fullscreen mode Exit fullscreen mode

46. Average of Numbers in Array

const avgArray = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
Enter fullscreen mode Exit fullscreen mode

47. Finding Intersection of Two Arrays

const intersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x));
Enter fullscreen mode Exit fullscreen mode

48. Finding Difference of Two Arrays

const difference = (arr1, arr2) => arr1.filter(x => !arr2.includes(x));
Enter fullscreen mode Exit fullscreen mode

49. Checking if All Elements are Equal

const allEqual = arr => arr.every(val => val === arr[0]);
Enter fullscreen mode Exit fullscreen mode

50. Generating a Random Hex Color

const randomHexColor = () => 
  '#' + Math.floor(Math.random()*16777215).toString(16);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
a-k-0047 profile image
ak0047

Really helpful list, thank you!