10 JavaScript One-Liners That Will Help You Improve Your Productivity
Tags: javascript, webdev, beginners, productivity
Published: 2022-03-04 11:45:11

There are over 10 million Javascript developers around the world and the numbers are increasing every day. Although JavaScript is more famous for its dynamic nature, it also has many other great features. In this blog, we will see 10 useful JavaScript one-liners that you should know to improve your productivity.

## 1. Generating a Random Number Within a Range

There are lots of cases where we need a random number to be generated within a range. The [`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function can do the work for us to generate a random number, and then we can transform it to the range we want.

```js
const max = 20;
const min = 10;

const random = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random);

//output: 17
//output: 10
```

## 2. Reverse a String

There are a couple different ways to reverse a string. This is one of the most simple ones using the [`split()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), [`reverse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), and [`join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) methods.

```js
const reverse = (str) => str.split('').reverse().join('');
const str = 'hello world';

console.log(reverse(str));

// output: dlrow olleh
```

## 3. Generate a Random Hex Code

Does your application rely on random color generation? Look no further, the following snippet got you covered!

```js
const color =
   '#' +
   Math.floor(Math.random() * 0xffffff)
      .toString(16)
      .padEnd(6, '0');

console.log(color);

//output: #ed19ed
```

## 4. Shuffle an Array

While using algorithms that require some degree of randomization, you will often find shuffling arrays quite a necessary skill, In JavaScript, we don’t have a module as python has [`random.shuffle()`](https://www.w3schools.com/python/ref_random_shuffle.asp) but still, there is a way to shuffle an array in just one line of code.

```js
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

const arr = Array.from({ length: 10 }, (_, i) => i + 1);
console.log('array: ', arr);
console.log('shuffled array: ', shuffleArray(arr));

//output:
// array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// shuffled array: [5, 7, 8, 9, 1, 2, 3, 4, 10, 6]
```

## 5. Scroll To Top/Scroll To Bottom

Beginners very often find themselves struggling with scrolling elements into view properly. The easiest way to scroll elements is to use the [`scrollIntoView`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method.

```js
//Add behavior: "smooth" for a smooth scrolling animation.
const scrollToTop = (element) =>
   element.scrollIntoView({ behavior: 'smooth', block: 'start' });

const scrollToBottom = (element) =>
   element.scrollIntoView({ behavior: 'smooth', block: 'end' });
```

## 6. Check if Someone’s Using Dark Mode

If you want the content you display to respect the color scheme of the person using your website, JavaScript includes a way to detect whether someone is using dark mode so you can adjust colors accordingly.

```js
const isDarkMode1 =
   window.matchMedia &&
   window.matchMedia('(prefers-color-scheme: dark)').matches;

// or if you like to use it as a function
const isDarkMode2 = () =>
   window.matchMedia &&
   window.matchMedia('(prefers-color-scheme: dark)').matches;

console.log(isDarkMode1);
console.log(isDarkMode2());

//output:
// true
// true
```

## 7. Copy to Clipboard

Copying text to the clipboard is very useful and also a hard problem to solve. There are various solutions that you can find on the internet, but the one below can be one of the smallest and smartest solutions.

```js
const copyToClipboard = (text) =>
   navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
```

## 8. Get the Number of Days Between Two Dates

When determining the age of a certain value (like a user’s account), you’ll have to calculate the number of days that have passed since a certain point.

```js
const ageDays = (old, recent) =>
   Math.ceil(Math.abs(old - recent) / (1000 * 60 * 60 * 24)) + ' Day(s)';

const firstDate = new Date('2021-06-10');
const secondDate = new Date('2022-03-03');

console.log(ageDays(firstDate, secondDate));

// output: 266 Day(s)
```

## 9. Get a Random Boolean

The[`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function in Javascript can be used to generate a random number between a range. To generate a random boolean we need to get random a number between 0 to 1, then we check whether it is above or below 0.5.

```js
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());

// output: false
```

## 10. Check if the current user is on an Apple device

We can use [`navigator.platform`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform) to check the platform on which the browser is running.

```js
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);

console.log(navigator.platform);
console.log(isAppleDevice);

// output:
// Win32
// false
```

**Note:** The recommended alternative to this property is [navigator.userAgentData.platform](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/platform). However, [navigator.userAgentData.platform](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/platform) is not yet supported by some major browsers, and the specification which defines it has not yet been adopted by any standards group (specifically, it is not part of any specification published by the W3C or WHATWG).

---

**Also read:** [How to Use Three.js And React to Render a 3D Model of Your Self](https://blog.nourdinedev.com/how-to-use-three.js-and-react-to-render-a-3d-model/)

---

[**My blog**](https://blog.nourdinedev.com)
[**My website**](https://blog.nourdinedev.com)
[**Find me on Upwork**](https://www.upwork.com/freelancers/~01569971d23265ceb8)
[**Find me on twitter**](https://twitter.com/NourdineDev)
[**Find me on linkedin**](https://www.linkedin.com/in/nourdine-labib/)
[**Find me on github**](https://github.com/Nourdinedev)