20 Best JavaScript Code Snippets for Everyday Use


 

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


const currentDate = new Date(); console.log(currentDate);

Explanation: This snippet creates a new Date object, giving you the current date and time.


2. Check if a Variable is an Array


const isArray = Array.isArray(variable); console.log(isArray);

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


const mergedArray = array1.concat(array2);

Explanation: You can merge two arrays using the concat() method, which creates a new array.


4. Remove Duplicates from an Array


const uniqueArray = [...new Set(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


const sortedArray = array.sort((a, b) => a - b);

Explanation: Sorting an array of numbers in ascending order is easily done with the sort() function.


6. Reverse an Array


const reversedArray = array.reverse();

Explanation: This snippet reverses the order of elements in an array.


7. Convert String to Number


const num = parseInt("42");

Explanation: Use parseInt() to convert a string into an integer.


8. Generate a Random Number Between Two Values


const randomNum = Math.random() * (max - min) + min;

Explanation: This generates a random number between min and max.


9. Check if a String Contains a Substring


const contains = str.includes(substring);

Explanation: includes() checks if a string contains a given substring.


10. Get the Length of an Object


const length = Object.keys(obj).length;

Explanation: Object.keys() returns an array of an object’s properties, and you can get its length.


11. Convert Object to Array


const array = Object.values(obj);

Explanation: Convert an object to an array using Object.values().


12. Check if an Object is Empty


const isEmpty = Object.keys(obj).length === 0;

Explanation: If an object has no keys, it's considered empty.


13. Get Current URL


const url = window.location.href;

Explanation: This returns the current page URL.


14. Redirect to a New URL


window.location.href = 'https://www.example.com';

Explanation: You can redirect users to a different page by changing window.location.href.


15. Set a Cookie


document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT";

Explanation: This sets a cookie with a name, value, and expiration date.


16. Get a Cookie


const cookieValue = document.cookie.match('(^|;)\\s*username\\s*=\\s*([^;]+)').pop();

Explanation: Retrieve the value of a cookie using document.cookie and a regex.


17. Check if a Cookie Exists


const exists = document.cookie.includes('username');

Explanation: This checks if a specific cookie exists.


18. Remove a Cookie


document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";

Explanation: Deleting a cookie is as simple as setting its expiration date in the past.


19. Get Current Viewport Dimensions


const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight;

Explanation: These properties return the width and height of the browser window.


20. Copy Text to Clipboard


navigator.clipboard.writeText('Text to copy');

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!

Post a Comment

Previous Post Next Post