10 Useful JavaScript Snippets you should know about

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 5 min read
10 Useful JavaScript Snippets you should know about Banner Image
10 Useful JavaScript Snippets you should know about Banner Image

JavaScript is the ubiquitous language of the web, powering interactivity and dynamic features on countless websites. But even experienced developers can benefit from having a toolbox of useful code snippets. These bite-sized functions can save you time and effort, making your code cleaner and more efficient.

In this blog, we'll explore 10 essential JavaScript snippets that you'll find yourself using again and again:

1. Simple Form Validation:

Ensuring users enter valid data in forms is crucial. This snippet performs basic validation on an email input field:

const emailInput = document.getElementById("email");
const emailError = document.getElementById("emailError");

emailInput.addEventListener("blur", function() {
  const email = emailInput.value;
  const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (!emailRegex.test(email)) {
    emailError.textContent = "Please enter a valid email address.";
    emailInput.classList.add("error"); // Add a CSS class for styling the error message
  } else {
    emailError.textContent = "";
    emailInput.classList.remove("error");
  }
});

Explanation:

This code retrieves the email input field and error message element. A blur event listener is attached to the input, which triggers when the user leaves the field. It validates the email using a regular expression (emailRegex) and displays an error message (and adds a CSS class for styling) if the format is invalid.

2. Debouncing Function Calls:

Debouncing helps prevent functions from being called too frequently, especially for user input events like typing. This snippet demonstrates a simple debounce implementation:

function debounce(func, delayMs) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delayMs);
  };
}

const handleSearch = debounce((searchTerm) => {
  console.log(`Searching for: ${searchTerm}`);
}, 500);

// Usage: handleSearch("apple") will only trigger the search after 500ms of inactivity after typing "apple"

Explanation:

The debounce function creates a closure. It takes the original function (func) and a delay (delayMs). It returns a new function that clears any existing timer and sets a new one with setTimeout. This ensures

3. Countdown Timer:

function countdown(targetDate, elementId) {
  const targetTime = new Date(targetDate).getTime();
  const element = document.getElementById(elementId);

  const interval = setInterval(() => {
    const now = new Date().getTime();
    const difference = targetTime - now;

    const days = Math.floor(difference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((difference % (1000 * 60)) / 1000);

    element.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;

    if (difference <= 0) {
      clearInterval(interval);
      element.textContent = "Time's Up!";
    }
  }, 1000);
}

countdown("2024-04-12", "countdown-display");  // Set your target date here

Explanation:

This code creates a countdown timer that displays the remaining time until a specified date on a webpage element.

4. Copy Text to Clipboard:

function copyToClipboard(text) {
  // Modern approach using Clipboard API (if supported)
  if (navigator.clipboard && navigator.clipboard.writeText) {
    return navigator.clipboard.writeText(text);
  }

  // Fallback for older browsers
  const textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("copy");
  textArea.remove();
}

// Usage:
const someText = "This text will be copied to the clipboard!";
copyToClipboard(someText);

Explanation:

  1. Function Definition: The copyToClipboard function takes a string argument text which is the text you want to copy.
  2. Modern Approach (Clipboard API):
    • We check if the browser supports the navigator.clipboard API and the writeText method.
    • If supported, we use navigator.clipboard.writeText(text) which is the recommended way for modern browsers. This method returns a promise that resolves if the copy operation is successful or rejects if there's an error.
  3. Fallback for Older Browsers:
    • If the Clipboard API is not supported, we create a temporary invisible text area element.
    • We set the value of the text area to the text argument.
    • We append the text area to the document body (but make it invisible with CSS if needed).
    • We use select() to select the text in the text area.
    • We use document.execCommand("copy") to trigger the copy operation to the clipboard.
    • Finally, we remove the temporary text area element.

5. Generate Random Hex Codes:

Creating random colors is a common task in web development. This snippet utilizes the Math.floor and toString methods to generate random hexadecimal color codes:

function getRandomHexColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

const randomColor = getRandomHexColor();

console.log(randomColor); // Output: # followed by 6 random hex characters

Explanation:

This function defines getRandomHexColor which creates a string with a hash (#) followed by six hexadecimal characters. It loops six times, generating a random number between 0 and 15 using Math.floor(Math.random() * 16). The corresponding character from the letters string (containing hexadecimal digits and letters A-F) is then added to the color string.

6. Get The Current URL

Extracting the current URL of the webpage can be useful for various functionalities. Here's a simple snippet to achieve this:

const getURL = () => window.location.href

getURL();

Explanation:

This code uses the window.location.href property to access the complete URL of the current window (webpage).

7. Capitalize the First Letter of a String:

This snippet capitalizes the first letter of a string while leaving the rest unchanged:

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

const name = "john doe";
const capitalizedName = capitalizeFirstLetter(name);
console.log(capitalizedName); // Output: John Doe

8. Check if a String is a URL:

Verifying if a string is a valid URL can be helpful in various scenarios. Here's a basic check:

function isURL(str) {
  const urlRegex = /^(http|https):\/\/\S+$/;
  return urlRegex.test(str);
}

const validURL = "https://www.example.com";
const invalidURL = "notAWebsite";

console.log(isURL(validURL)); // Output: true
console.log(isURL(invalidURL)); // Output: false

9. Looping Through an Object's Key-Value Pairs:

Iterating through properties of an object is a common task. This snippet demonstrates two ways to achieve this:

const person = { name: "Alice", age: 30, profession: "developer" };

// Using for...in loop
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// Using Object.entries() and forEach() (ES6+)
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

// Output (both methods):
// name: Alice
// age: 30
// profession: developer

10. Removing Duplicate Values:

Duplicate values in arrays can be a pain to deal with. This snippet employs the Set object to efficiently remove duplicates:

const fruits = ["apple", "banana", "apple", "orange", "banana"];

const uniqueFruits = [...new Set(fruits)];

console.log(uniqueFruits); // Output: ["apple", "banana", "orange"]

Explanation:

Here, we create a new Set object from the fruits array. Sets inherently don't allow duplicates. We then use the spread operator (...) to create a new array (uniqueFruits) containing the unique values from the set.

Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

I am a Front-End Developer specializing in Frontend at Dvago.pk.

Copyright © 2024 Mbloging. All rights reserved.