JavaScript is a versatile language, and knowing efficient code snippets can save time and boost productivity. Here are 20 code snippets that you can use in your day-to-day JavaScript development.
1. Get Current Date and Time
Explanation: This snippet creates a new Date object, giving you the current date and time.
2. Check if a Variable is an Array
Explanation: Use Array.isArray() to check if a variable is an array. This is crucial when working with unknown data types.
3. Merge Two Arrays
Explanation: You can merge two arrays using the concat() method, which creates a new array.
4. Remove Duplicates from an Array
Explanation: The Set object automatically removes duplicates, and by spreading it into an array, you get a unique list.
5. Sort an Array in Ascending Order
Explanation: Sorting an array of numbers in ascending order is easily done with the sort() function.
6. Reverse an Array
Explanation: This snippet reverses the order of elements in an array.
7. Convert String to Number
Explanation: Use parseInt() to convert a string into an integer.
8. Generate a Random Number Between Two Values
Explanation: This generates a random number between min and max.
9. Check if a String Contains a Substring
Explanation: includes() checks if a string contains a given substring.
10. Get the Length of an Object
Explanation: Object.keys() returns an array of an object’s properties, and you can get its length.
11. Convert Object to Array
Explanation: Convert an object to an array using Object.values().
12. Check if an Object is Empty
Explanation: If an object has no keys, it's considered empty.
13. Get Current URL
Explanation: This returns the current page URL.
14. Redirect to a New URL
Explanation: You can redirect users to a different page by changing window.location.href.
15. Set a Cookie
Explanation: This sets a cookie with a name, value, and expiration date.
16. Get a Cookie
Explanation: Retrieve the value of a cookie using document.cookie and a regex.
17. Check if a Cookie Exists
Explanation: This checks if a specific cookie exists.
18. Remove a Cookie
Explanation: Deleting a cookie is as simple as setting its expiration date in the past.
19. Get Current Viewport Dimensions
Explanation: These properties return the width and height of the browser window.
20. Copy Text to Clipboard
Explanation: Use the Clipboard API to copy text to the clipboard.
Conclusion: These snippets can make your JavaScript coding faster and more efficient. Happy coding!
