Home > Web Front-end > JS Tutorial > body text

Most Useful JavaScript Snippets

Mary-Kate Olsen
Release: 2024-10-31 21:37:29
Original
807 people have browsed it

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);
Copy after login

2. Checking If an Object is Empty

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

3. Creating a Countdown Timer

function countdownTimer(minutes) { /* countdown logic */ }
Copy after login

4. Sorting an Array of Objects

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

5. Removing Duplicates from an Array

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

6. Truncating a String

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

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

8. Checking If a Value Exists in an Array

let isValueInArray = arr.includes(value);
Copy after login

9. Reversing a String

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

10. Creating a New Array from an Existing Array

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

11. Debouncing Function Calls

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

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)); } }; }
Copy after login

13. Cloning an Object

const cloneObject = (obj) => ({ ...obj });
Copy after login

14. Merging Two Objects

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

15. Checking for Palindrome Strings

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

16. Counting Occurrences in an Array

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

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);
Copy after login

18. Filtering Unique Values from an Array

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

19. Converting Degrees to Radians

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

20. Delaying Function Execution

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

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

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!