30 Essential JavaScript Snippets You Should Know
Boost Your Productivity with these Essential JavaScript Snippets
Introduction
JavaScript is a versatile and powerful programming language that plays a critical role in web development. Whether you're a seasoned developer or just starting with JavaScript, using code snippets can significantly enhance your productivity and improve code readability. In this blog, we'll explore 30 essential JavaScript snippets that can make your coding life easier and more efficient.
1. Convert String to number
const number = parseInt(string)
2. Get the Current Date in YYYY-MM-DD Format:
const getCurrentDate = () => new Date().toISOString().slice(0, 10);
3. Remove Duplicates from an Array
const removeDuplicates = (arr) => [...new Set(arr)];
4. Find the Largest Number in an Array:
const findLargestNumber = (num) => Math.max(...num)
5. Check if Element Exists in an Array:
const elementExists =(arr,elem) => arr.includes(elem)
6. Generate a Random Number within a Range:
const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
7. Truncate a String:
const truncateString = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
8. Convert String to CamelCase:
const toCamelCase = (str) => str.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
9. Merge Two Arrays:
const mergedArray = (arr1, arr2) => [...arr1, ...arr2];
or
const mergedArray = (arr1, arr2) => arr1.concat(arr2);
10. Check if an Object is Empty:
const isEmptyObject = (obj) => Object.keys(obj).length === 0;
11. Sort Array In Ascending Order:
const sortedArray = (arr) => arr.sort((a, b) => a - b);
12. Reverse an Array:
const reversedArray = (arr) => arr.reverse();
13. Find the Difference Between Two Dates:
const dateDifferenceInDays = (date1, date2) => Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
14. Calculate the Sum of an Array
const sumArray = (arr) => arr.reduce((total, current) => total + current, 0);
15. Format Number with Commas:
const formatNumberWithCommas = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
16. Validate Email Address:
const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
17. Check if a String is Palindrome:
const isPalindrome = (str) => str === str.split('').reverse().join('');
18. Convert Degrees to Radians:
const degreesToRadians = (degrees) => degrees * (Math.PI / 180);
19. Shuffle an Array:
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
20. Convert Object to Array:
const array =(obj) => object.entries(obj);
21. Check if an Object is Empty:
const isEmptyObject = (obj) => Object.keys(obj).length === 0;
22. Capitalize the First Letter of a String:
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
23. Check if a Number is Even or Odd:
const isEven = (num) => num % 2 === 0;
24. Convert Object to JSON String:
const objectToJson = (obj) => JSON.stringify(obj);
25. Check if a Value is an Array:
const isArray = (value) => Array.isArray(value);
26. Find the Index of the First Occurrence of an Element in an Array:
const findIndexOfElement = (arr, element) => arr.indexOf(element);
27. Get current URL:
const currentUrl = window.location.href;
28. Set a Cookie
document.cookie = "name=value; expires=date; path=path; domain=domain; secure";
29. Copy text to Clipboard:
const copyText = (text) => navigator.clipboard.writeText(text);
30. Check if the User is Scrolling Up or Down:
let lastScrollTop = 0;
window.addEventListener('scroll', () => {
const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
const direction = scrollPosition > lastScrollTop ? 'down' : 'up';
lastScrollTop = scrollPosition <= 0 ? 0 : st;
});
Conclusion
In this blog, we've explored 30 JavaScript snippets that cover various tasks like array manipulation, string operations, date calculations, and more. By using these snippets, you can save time, write cleaner code, and boost your productivity as a JavaScript developer. Thanks for reading!