JavaScript
20 Best JavaScript Snippets
Here are 20 useful JavaScript snippets that can help you when working on your projects:
1. Get current date and time:
1 | const now = new Date(); |
2. Check if a variable is an array:
1 | Array.isArray(variable); |
3. Merge two arrays:
1 | const newArray = array1.concat(array2); |
4. Remove duplicates from an array:
1 | const uniqueArray = [... new Set(array)]; |
5. Sort an array in ascending order:
1 | array.sort((a, b) => a - b); |
6. Reverse an array:
1 | array.reverse(); |
7. Convert string to number:
1 | const number = parseInt(string); |
8. Generate a random number between two values:
1 | const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; |
9. Check if a string contains a substring:
1 | string.includes(substring); |
10. Get the length of an object:
1 | Object.keys(object).length; |
11. Convert object to array:
1 | const array = Object.entries(object); |
12. Check if an object is empty:
1 | (( typeof object)== "object" ) && Object.keys(object).length==0; |
13. Get current URL:
1 | const currentUrl = window.location.href; |
14. Redirect to a new URL:
1 | window.location.replace(url); |
15. Set a cookie:
1 | document.cookie = "name=value; expires=date; path=path; domain=domain; secure" ; |
16. Get a cookie:
1 | const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1" ); |
17. Check if a cookie exists:
1 | document.cookie.split( ';' ).some((item) => item.trim().startsWith( 'name=' )) |
18. Remove a cookie:
1 | document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=path; domain=domain; secure" ; |
19. Get the current viewport dimensions:
1 2 | const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0); |
20. Copy text to clipboard:
1 | navigator.clipboard.writeText(text); |
These JavaScript snippets can help save time and simplify your code when working on web projects.
12 is wrong.
Correct way:
Test the type before checked the length.
Checked the length, can do an unpredictable result.
For example, checking the length of a numeric is nonsense.