6 Killer Functions in JavaScript that Made My Life Easier
Tags: javascript, webdev, programming, productivity
Published: 2022-02-20 05:39:13

---
canonical_url: https://tapajyoti-bose.medium.com/6-killer-utility-functions-in-javascript-86d52af43cd3
---

This is somewhat of an extension to last week's [7 Killer One-Liners in JavaScript](https://dev.to/ruppysuppy/7-killer-one-liners-in-javascript-one). 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**.

```javascript
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);
```

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**

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

console.log(detectDeviceType());
```

## 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.

```javascript
const hideElement = (element, removeFromFlow = false) => {
  removeFromFlow
    ? (element.style.display = "none")
    : (element.style.visibility = "hidden");
};
```

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.

```javascript
const url = new URL(window.location.href);
const paramValue = url.searchParams.get("paramName");
console.log(paramValue);
```

## 5. Deep copy an object with ease

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

```javascript
const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
```

## 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.

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

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

asyncFunc();
```

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

## Thanks for reading

Need a **Top Rated Front-End Development Freelancer** to chop away your development woes? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [Personal Website](https://tapajyoti-bose.vercel.app) and [GitHub](https://github.com/ruppysuppy)

Want to connect? Reach out to me on [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose/)

I am a freelancer who will start off as a **Digital Nomad** in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for **Weekly new Tidbits** on [Dev](https://dev.to/ruppysuppy)

**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](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)