Sunday, May 19, 2024
HomeJava20 Finest JavaScript Snippets - Java Code Geeks

20 Finest JavaScript Snippets – Java Code Geeks


Listed here are 20 helpful JavaScript snippets that may enable you to when working in your initiatives:

1. Get present date and time:

const now = new Date();

2. Examine if a variable is an array:

Array.isArray(variable);

3. Merge two arrays:

const newArray = array1.concat(array2);

4. Take away duplicates from an array:

const uniqueArray = [...new Set(array)];

5. Type an array in ascending order:

array.kind((a, b) => a - b);

6. Reverse an array:

array.reverse();

7. Convert string to quantity:

const quantity = parseInt(string);

8. Generate a random quantity between two values:

const randomNumber = Math.flooring(Math.random() * (max - min + 1)) + min;

9. Examine if a string incorporates a substring:

string.consists of(substring);

10. Get the size of an object:

Object.keys(object).size;

11. Convert object to array:

const array = Object.entries(object);

12. Examine if an object is empty:

Object.keys(object).size === 0 && object.constructor === Object

13. Get present URL:

const currentUrl = window.location.href;

14. Redirect to a brand new URL:

window.location.exchange(url);

15. Set a cookie:

doc.cookie = "identify=worth; expires=date; path=path; area=area; safe";

16. Get a cookie:

const cookieValue = doc.cookie.exchange(/(?:(?:^|.*;s*)names*=s*([^;]*).*$)|^.*$/, "$1");

17. Examine if a cookie exists:

doc.cookie.break up(';').some((merchandise) => merchandise.trim().startsWith('identify="))

18. Take away a cookie:

doc.cookie = "identify=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=path; area=area; safe";

19. Get the present viewport dimensions:

const viewportWidth = Math.max(doc.documentElement.clientWidth || 0, window.innerWidth || 0);
const viewportHeight = Math.max(doc.documentElement.clientHeight || 0, window.innerHeight || 0);

20. Copy textual content to clipboard:

navigator.clipboard.writeText(textual content);

These JavaScript snippets might help save time and simplify your code when engaged on net initiatives.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments