DEV Community

Cover image for Top 30 JavaScript Snippets To Boost Your Productivity
Aishat Agunbiade
Aishat Agunbiade

Posted on

Top 30 JavaScript Snippets To Boost Your Productivity

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 the top 30 JavaScript snippets that can make your coding life easier and more efficient.

1. Convert String to number

const number = parseInt(string)
Enter fullscreen mode Exit fullscreen mode

2. Get the Current Date in YYYY-MM-DD Format:

const getCurrentDate = () => new Date().toISOString().slice(0, 10);

Enter fullscreen mode Exit fullscreen mode

3. Remove Duplicates from an Array

const removeDuplicates = (arr) => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

4. Find the Largest Number in an Array:

const findLargestNumber = (num) => Math.max(...num)
Enter fullscreen mode Exit fullscreen mode

5. Check if Element Exists in an Array:

const elementExists =(arr,elem) => arr.includes(elem)
Enter fullscreen mode Exit fullscreen mode

6. Generate a Random Number within a Range:

const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
Enter fullscreen mode Exit fullscreen mode

7. Truncate a String:

const truncateString = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;

Enter fullscreen mode Exit fullscreen mode

8. Convert String to CamelCase:

const toCamelCase = (str) => str.replace(/[-_](.)/g, (_, c) => c.toUpperCase());

Enter fullscreen mode Exit fullscreen mode

9. Merge Two Arrays:

const mergedArray = (arr1, arr2) => [...arr1, ...arr2];
or
const mergedArray = (arr1, arr2) => arr1.concat(arr2);

Enter fullscreen mode Exit fullscreen mode

10. Check if an Object is Empty:

const isEmptyObject = (obj) => Object.keys(obj).length === 0;

Enter fullscreen mode Exit fullscreen mode

11. Sort Array In Ascending Order:

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

Enter fullscreen mode Exit fullscreen mode

12. Reverse an Array:

const reversedArray = (arr) => arr.reverse();
Enter fullscreen mode Exit fullscreen mode

13. Find the Difference Between Two Dates:

const dateDifferenceInDays = (date1, date2) => Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);

Enter fullscreen mode Exit fullscreen mode

14. Calculate the Sum of an Array

const sumArray = (arr) => arr.reduce((total, current) => total + current, 0);

Enter fullscreen mode Exit fullscreen mode

15. Format Number with Commas:

const formatNumberWithCommas = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

Enter fullscreen mode Exit fullscreen mode

16. Validate Email Address:

const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

Enter fullscreen mode Exit fullscreen mode

17. Check if a String is Palindrome:

const isPalindrome = (str) => str === str.split('').reverse().join('');

Enter fullscreen mode Exit fullscreen mode

18. Convert Degrees to Radians:

const degreesToRadians = (degrees) => degrees * (Math.PI / 180);

Enter fullscreen mode Exit fullscreen mode

19. Shuffle an Array:

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);

Enter fullscreen mode Exit fullscreen mode

20. Convert Object to Array:

const array =(obj) => object.entries(obj);
Enter fullscreen mode Exit fullscreen mode

21. Check if an Object is Empty:

const isEmptyObject = (obj) => Object.keys(obj).length === 0;

Enter fullscreen mode Exit fullscreen mode

22. Capitalize the First Letter of a String:

const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);

Enter fullscreen mode Exit fullscreen mode

23. Check if a Number is Even or Odd:

const isEven = (num) => num % 2 === 0;
Enter fullscreen mode Exit fullscreen mode

24. Convert Object to JSON String:

const objectToJson = (obj) => JSON.stringify(obj);

Enter fullscreen mode Exit fullscreen mode

25. Check if a Value is an Array:

const isArray = (value) => Array.isArray(value);

Enter fullscreen mode Exit fullscreen mode

26. Find the Index of the First Occurrence of an Element in an Array:

const findIndexOfElement = (arr, element) => arr.indexOf(element);

Enter fullscreen mode Exit fullscreen mode

27. Get current URL:

const currentUrl = window.location.href;
Enter fullscreen mode Exit fullscreen mode

28. Set a Cookie

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

Enter fullscreen mode Exit fullscreen mode

29. Copy text to Clipboard:

const copyText = (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

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;
});

Enter fullscreen mode Exit fullscreen mode

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. Happy Coding!

Top comments (0)