JavaScript

20 Best JavaScript Snippets

Here are 20 useful JavaScript snippets that can help you when working on your projects:

1. Get current date and time:

const now = new Date();

2. Check if a variable is an array:

Array.isArray(variable);

3. Merge two arrays:

const newArray = array1.concat(array2);

4. Remove duplicates from an array:

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

5. Sort an array in ascending order:

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

6. Reverse an array:

array.reverse();

7. Convert string to number:

const number = parseInt(string);

8. Generate a random number between two values:

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

9. Check if a string contains a substring:

string.includes(substring);

10. Get the length of an object:

Object.keys(object).length;

11. Convert object to array:

const array = Object.entries(object);

12. Check if an object is empty:

((typeof object)=="object") && Object.keys(object).length==0;

13. Get current URL:

const currentUrl = window.location.href;

14. Redirect to a new URL:

window.location.replace(url);

15. Set a cookie:

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

16. Get a cookie:

const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");

17. Check if a cookie exists:

document.cookie.split(';').some((item) => item.trim().startsWith('name='))

18. Remove a cookie:

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=path; domain=domain; secure";

19. Get the current viewport dimensions:

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

20. Copy text to clipboard:

navigator.clipboard.writeText(text);

These JavaScript snippets can help save time and simplify your code when working on web projects.

Java Code Geeks

JCGs (Java Code Geeks) is an independent online community focused on creating the ultimate Java to Java developers resource center; targeted at the technical architect, technical team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Michel Bruyère
Michel Bruyère
1 year ago

12 is wrong.

Correct way:

((typeof object)=="object") && Object.keys(object).length==0;

Test the type before checked the length.
Checked the length, can do an unpredictable result.
For example, checking the length of a numeric is nonsense.

Back to top button