DEV Community

Parth Raval
Parth Raval

Posted on

20 Most Useful JavaScript Snippets

20 Most Useful JavaScript Snippets

Enhance your coding efficiency with these essential 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) { /* countdown logic */ }
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, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }
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(function(item) { return 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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more