DEV Community

Cover image for 6 Killer Functions in JavaScript that Made My Life Easier
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on • Originally published at tapajyoti-bose.Medium

6 Killer Functions in JavaScript that Made My Life Easier

This is somewhat of an extension to last week's 7 Killer One-Liners in JavaScript. If you haven't already read the article, you are highly encouraged to do so.

1. Check if an element is visible in the viewport

IntersectionObserver is a great way to check if an element is visible in the viewport.

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};

const options = {
  threshold: 1.0,
};

const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");

observer.observe(btn);
observer.observe(bottomBtn);
Enter fullscreen mode Exit fullscreen mode

You can customize the behavior of the observer using the option parameter. threshold is the most useful attribute, it defines the percentage of the element that needs to be visible in the viewport for the observer to trigger.

2. Detect device

You can use the navigator.userAgent to gain minute insights and detect the device running the application

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";

console.log(detectDeviceType());
Enter fullscreen mode Exit fullscreen mode

3. Hide elements

You can just toggle the visibility of an element using the style.visibility property and in case you want to remove it from the render flow, you can use the style.display property.

const hideElement = (element, removeFromFlow = false) => {
  removeFromFlow
    ? (element.style.display = "none")
    : (element.style.visibility = "hidden");
};
Enter fullscreen mode Exit fullscreen mode

If you don't remove an element from the render flow, it will be hidden, but its space will still be occupied. It is highly useful while rendering long lists of elements, the elements NOT in view (can be tested using IntersectionObserver) can be hidden to provide a performance boost.

4. Get the parameters from the URL

JavaScript makes fetching the parameters from any address a walk in the park using the URL object.

const url = new URL(window.location.href);
const paramValue = url.searchParams.get("paramName");
console.log(paramValue);
Enter fullscreen mode Exit fullscreen mode

5. Deep copy an object with ease

You can deep copy any object by converting it to a string and back to an object.

const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

6. wait function

JavaScript does ship with a setTimeout function, but it does not return a Promise object, making it hard to use in async functions. So we have to write our own wait/sleep function.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const asyncFunc = async () => {
  await wait(1000);
  console.log("async");
};

asyncFunc();
Enter fullscreen mode Exit fullscreen mode

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas

Top comments (2)

Collapse
 
nevulo profile image
Nevulo

Great post, helpful snippets, especially deep cloning an object as opposed to passing by reference.

I'd also recommend the global structuredClone method, which is fairly new and just being rolled out to newer browsers and in Node 17, but if you have access to it, it's a lot better for serialising JavaScript objects like Maps!

Collapse
 
nove1398 profile image
nove1398

Good bits of information