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();
console.log(currentDate);

 

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);
console.log(isInArray);

 

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);
console.log(mergedArray);

 

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 = [...new Set(duplicateArray)];
console.log(uniqueArray);

 

 

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);
console.log(sortedArray);

 

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();
console.log(reversedArray);

 

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('');
console.log(charArray);

 

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;
console.log(randomNum);

 

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);
console.log(containsSubstring);

 

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;
console.log(objectLength);

 

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);
console.log(objectToArray);

 

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;
console.log(currentURL);

 

14. Redirect to a new URL

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

const newURL = "https://www.example.com";
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');
console.log(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");
console.log(cookieExists);

 

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!";
navigator.clipboard.writeText(textToCopy)
  .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 Create a Livewire Image Upload in Laravel 10?
How to Create a Livewire Image...

Livewire has revolutionized the way developers build interactive web applications with its real-time capabilities. And w...

Read More

Aug-02-2023

Laravel 11 Use Quill Rich Text Editor Example
Laravel 11 Use Quill Rich Text...

Hello, laravel web developers! In this article, we'll see how to use Quill rich text editor in laravel 11. Here, we&...

Read More

Sep-04-2024

How to Resize Image before Upload in Laravel 11
How to Resize Image before Upl...

Hello, laravel web developers! In this article, we'll see how to resize images before uploading in laravel 11. Here,...

Read More

May-13-2024

How To Add Bootstrap Modal In React JS
How To Add Bootstrap Modal In...

In this article, we will see how to add a bootstrap modal in react js. In this example, we will use the bootstrap m...

Read More

Sep-09-2022