DEV Community

Cover image for 10 JavaScript One-Liners That Will Help You Improve Your Productivity
Nourdine Labib
Nourdine Labib

Posted on • Edited on • Originally published at blog.nourdinedev.com

10 JavaScript One-Liners That Will Help You Improve Your Productivity

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 function can do the work for us to generate a random number, and then we can transform it to the range we want.

const max = 20;
const min = 10;

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

//output: 17
//output: 10
Enter fullscreen mode Exit fullscreen mode

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(), reverse(), and join() methods.

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

console.log(reverse(str));

// output: dlrow olleh
Enter fullscreen mode Exit fullscreen mode

3. Generate a Random Hex Code

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

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

console.log(color);

//output: #ed19ed
Enter fullscreen mode Exit fullscreen mode

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() but still, there is a way to shuffle an array in just one line of code.

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]
Enter fullscreen mode Exit fullscreen mode

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

//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' });
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

const copyToClipboard = (text) =>
   navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

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.

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)
Enter fullscreen mode Exit fullscreen mode

9. Get a Random Boolean

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

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

// output: false
Enter fullscreen mode Exit fullscreen mode

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

We can use navigator.platform to check the platform on which the browser is running.

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

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

// output:
// Win32
// false
Enter fullscreen mode Exit fullscreen mode

Note: The recommended alternative to this property is navigator.userAgentData.platform. However, navigator.userAgentData.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


My blog
My website
Find me on Upwork
Find me on twitter
Find me on linkedin
Find me on github

Top comments (0)