Home  >  Article  >  Web Front-end  >  Most Useful JavaScript Snippets

Most Useful JavaScript Snippets

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 21:37:29808browse

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);

2. Checking If an Object is Empty

function isEmptyObject(obj) { return Object.keys(obj).length === 0; }

3. Creating a Countdown Timer

function countdownTimer(minutes) { /* countdown logic */ }

4. Sorting an Array of Objects

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

5. Removing Duplicates from an Array

let uniqueArr = [...new Set(arr)];

6. Truncating a String

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

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(); }); }

8. Checking If a Value Exists in an Array

let isValueInArray = arr.includes(value);

9. Reversing a String

let reversedStr = str.split("").reverse().join("");

10. Creating a New Array from an Existing Array

let newArr = oldArr.map(function(item) { return item + 1; });

11. Debouncing Function Calls

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

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)); } }; }

13. Cloning an Object

const cloneObject = (obj) => ({ ...obj });

14. Merging Two Objects

const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });

15. Checking for Palindrome Strings

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

16. Counting Occurrences in an Array

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

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);

18. Filtering Unique Values from an Array

const uniqueValues = arr => [...new Set(arr)];

19. Converting Degrees to Radians

const degreesToRads = deg => (deg * Math.PI) / 180;

20. Delaying Function Execution

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

The above is the detailed content of Most Useful JavaScript Snippets. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn