7 More Killer One-Liners in JavaScript
Tags: javascript, webdev, programming, productivity
Published: 2022-04-24 05:33:47

---
canonical_url: https://tapajyoti-bose.medium.com/7-more-killer-one-liners-in-javascript-1cd180d82695
---

This is a continuation of the [previous list of **javascript** one-liners](https://tapajyoti-bose.medium.com/7-killer-one-liners-in-javascript-33db6798f5bf). If you haven't checked out the article, you are highly encouraged to accomplish so.

Let's crack on with the new list!

![getting-ready](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hc3iurzter7av2p2bu5p.gif)

# 1. Sleep Function

**JavaScript** has **NO** built-in `sleep` function to wait for a given duration before continuing the execution flow of the code.

Luckily, generating a function for this purpose is straightforward

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

# 2. Go Back to the Previous Page

Need to send the user back to the page they came from? `history` object to the rescue!

```javascript
const navigateBack = () => history.back();
// Or
const navigateBack = () => history.go(-1);
```

# 3. Compare Objects

**Javascript** behaves in mysterious ways when comparing objects. Comparing objects with the `===` operator checks only the **reference of the objects**, so the following code always returns `false`:

```javascript
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
obj1 === obj2; // false
```

To solve this very issue, you can create a **deep comparison** function:

```javascript
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// examples
isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
isEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false

// works with arrays too
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 2, 4]); // false
```

# 4. Generate Random id

Need multiple **unique identifiers** but not looking to add the `uuid` package? Try out this simple utility function:

```javascript
const uuid = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
```

**NOTE:** The function is a **one-liner**, but spread across multiple lines for readability.

# 5. Get Selected Text

Want to have access to **the text user selects**? `window` just has a method to help you out!

```javascript
const getSelectedText = () => window.getSelection().toString();
```

# 6. Check if an Element is Focused

You can effortlessly check if an element is currently **focused** without setting up the `focus` & `blur` **listener**.

```javascript
const hasFocus = (element) => element === document.activeElement;
```

# 7. Count by the Properties of an Array of Objects

Need to count the number of items in an **array** that match a particular `property`? Using `reduce` on **arrays** can achieve the task with ease!

```javascript
const countElementsByProp = (arr, prop) =>
  arr.reduce(
    (prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev),
    {}
  );

// example
countElementsByProp(
  [
    { manufacturer: "audi", model: "q8", year: "2019" },
    { manufacturer: "audi", model: "rs7", year: "2020" },
    { manufacturer: "ford", model: "mustang", year: "2019" },
    { manufacturer: "ford", model: "explorer", year: "2020" },
    { manufacturer: "bmw", model: "x7", year: "2020" },
  ],
  "manufacturer"
); // { 'audi': 2, 'ford': 2, 'bmw': 1 }
```

**NOTE:** This too is a **one-liner**, but spread across multiple lines for readability.

**That's all folks!**

![thumbs-up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hh3w8x99pw4mqb8j7t8.gif)

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)