Top 20 Best Javascript Tips and Tricks

Websolutionstuff | Aug-14-2023 | Categories : jQuery

Welcome to the fascinating world of JavaScript, where innovation and creativity converge to deliver dynamic and interactive web experiences. JavaScript, the powerful programming language that runs in your browser, has become an indispensable tool for me and web developers worldwide.

Its versatility and adaptability have allowed me to create countless stunning websites and applications.

As I continue to grow as a developer, I'm constantly on the lookout for the best practices and techniques to craft efficient and elegant code.

Whether you're a seasoned coder like me or just starting on your JavaScript journey, understanding the latest tips and tricks can significantly enhance your development skills and boost your productivity.

In this article, I'll be diving into the Top 20 Best JavaScript Tips and Tricks, which I've carefully curated to help you unlock the full potential of this incredible language.

From performance optimizations to creative solutions for common challenges, we'll explore practical examples and easy-to-follow explanations that will empower you to write cleaner, more maintainable code.

So, let's embark on this enriching journey together to discover the art of JavaScript mastery.

Whether you're seeking to sharpen your skills or gain new insights, these tips and tricks will equip you with the tools you need to excel in the ever-evolving world of web development.

Let's get started!

1. Get the current date and time

This code snippet demonstrates how to obtain the current date and time using JavaScript's Date object.

const currentDate = new Date();


2. Check if a variable in an array

The includes() method is used here to check if the myVariable exists within the myArray.

const myArray = [1, 2, 3, 4, 5];
const myVariable = 3;
const isInArray = myArray.includes(myVariable);


3. Merge two array

By using the concat() method, we can effortlessly merge array1 and array2 into a single array, mergedArray.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);


4. Remove duplicates from an array

The code above utilizes the Set object to eliminate duplicates, converting it back to an array using the spread operator.

const duplicateArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [ Set(duplicateArray)];



5. Sort an array in ascending order

With the sort() method and a custom comparator function, we can easily sort unsortedArray in ascending order.

const unsortedArray = [3, 1, 4, 2, 5];
const sortedArray = unsortedArray.sort((a, b) => a - b);


6. Reverse an array

The reverse() method allows us to reverse the order of elements in arrayToReverse.

const arrayToReverse = [1, 2, 3, 4, 5];
const reversedArray = arrayToReverse.reverse();


7. Converting string to array

Using the split() method with an empty string argument, we can convert myString into an array of characters.

const myString = "Hello, World!";
const charArray = myString.split('');


8. Generate a random number between values

The above code generates a random number between min and max, inclusive.

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


9. Check if a string contains a substring

Using the includes() method, we can determine whether myString contains the substring.

const myString = "Hello, World!";
const substring = "Hello";
const containsSubstring = myString.includes(substring);


10. Get the length of an object

By using Object.keys(), we can calculate the number of properties in myObject.

const myObject = { name: "John", age: 30, city: "New York" };
const objectLength = Object.keys(myObject).length;


11. Convert an object to an array

With Object.entries(), we can convert myObject into an array of key-value pairs.

const myObject = { name: "John", age: 30, city: "New York" };
const objectToArray = Object.entries(myObject);


12. Check if an object is empty

The isEmpty function checks whether an object is empty by counting its properties.

const emptyObject = {};
const nonEmptyObject = { name: "John" };
const isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty(emptyObject)); // true
console.log(isEmpty(nonEmptyObject)); // false


13. Get the current URL

Using window.location.href, we can easily retrieve the current URL of the webpage.

const currentURL = window.location.href;


14. Redirect to a new URL

To redirect to a new URL, assign the desired URL to window.location.href.

const newURL = "";
window.location.href = newURL;


15. Set a cookie

By manipulating the document.cookie, we can set a cookie with a specified expiration date and path.

const cookieName = "username";
const cookieValue = "JohnDoe";
document.cookie = `${cookieName}=${cookieValue}; expires=Thu, 06 Aug 2024 00:00:00 UTC; path=/`;



16. Get a cookie

The getCookie function allows us to retrieve the value of a specific cookie, such as the one set in the previous example.

const getCookie = (name) => {
  const cookieValue = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
  return cookieValue ? cookieValue.pop() : '';

const username = getCookie('username');


17. Check if a cookie exists

The includes() method is employed here to check if a specific cookie exists.

const cookieExists = document.cookie.includes("username");


18. Remove a cookie

To remove a cookie, set its expiration date to the past.

const cookieName = "username";
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;


19. Get the current viewport dimensions

Using window.innerWidth and window.innerHeight, we can retrieve the current width and height of the viewport.

const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
console.log(`Width: ${viewportWidth}, Height: ${viewportHeight}`);


20. Copy text to the clipboard

The navigator.clipboard.writeText() method enables copying the specified textToCopy to the user's clipboard.

const textToCopy = "Hello, World!";
  .then(() => console.log("Text copied to clipboard!"))
  .catch((error) => console.error("Failed to copy text: ", error));

With these twenty JavaScript tips and tricks at your disposal, you can elevate your web development expertise and tackle various coding challenges with ease. Embrace these techniques to make your JavaScript code more efficient, maintainable, and user-friendly.


You might also like:

Recommended Post
Featured Post
How To Add Toastr Notification In Laravel 10
How To Add Toastr Notification...

In this article, we will see how to add toastr notification in laravel 10. Here, we will learn about toastr notification...

Read More


How to Send Bulk Mail Using Queue in Laravel 9
How to Send Bulk Mail Using Qu...

In this article, we will see how to send bulk mail using queue in laravel 9. Laravel queue is used for sending bulk...

Read More


How to Clear Form Data Using jQuery
How to Clear Form Data Using j...

In this small tutorial we will see how to clear form data using we will reset form using jquery. many t...

Read More


How To Get Last 7 Days Record In Laravel 8
How To Get Last 7 Days Record...

In this example, we will see how to get the last 7 days record in laravel 8. You can simply get the last 7 days record u...

Read More