7 JavaScript One-Liners to Save Your Day

7 JavaScript One-Liners to Save Your Day

Do this instead of writing your own functions

In this blog, we are going to cover some JavaScript one-liners that might save your day.

1. Shuffle the array and return an array

You can shuffle the array using the random method of the math module.

const shuffle = array => array.sort(() => 0.5-Math.random());

//output

shuffle([1,5,2,45])

[5,2,1,25]

Math.random() returns a random number between 0 and 1. So if it happens to give you a number less than 0.5 then you get a negative number and if it’s over that then you get a positive.

The reason 0.5 is chosen in this compare function is that if you subtract 0.5 from each of the endpoints of 0 and 1, you get a new range of -0.5 and +0.5, but +0.5 is not included because the original 1 is not included in the result of the Math.random() function.

So when a random number is returned from this range, there is an almost equal chance it will be either positive or negative, and sometimes it will also be zero.

2. Generate a random string

Sometimes there may be a situation where you need to generate random strings, use this snippet of code to obtain that.

const randomstr = Math.random().toString(36).substring(7)

It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.

3. Detecting dark mode

There may be situations where you want to do some extra things when dark mode is activated, use this snippet of code to check whether the dark mode is on or off.

const isDark = window.matchMedia && window.matchMedia(`(prefers-color-scheme:dark)`).match

4. Remove duplicates from an array

Removing duplicate elements is one of the common things that we do in an array, use this one-liner to achieve this.

const num = [1,2,2,2,5,66,666,55,5]
const name = ["adarsh","gupta","adarsh","raj","ratesh","raj"]

const uniquenum = [... new Set(num)]
// [1,2,5,66,666,55]

const uniquenames = [... new Set(name)
// ["adarsh","gupta","raj","ratesh"]

5. Reverse a string

Reverse a string has never been such easy, firstly we convert it into an array (an array of characters), now we reverse that array then we convert that array into a string.

Use this one-liner to achieve this:

const rev = (str) => str.split("").reverse().join("")

6. Check if an array is not empty

Checking if an array is empty or not using the isArray method and confirming it by checking the length of Object.keys(arr) by passing the array.

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

const isArrayNotEmpty = (arr) => Array.isArray(arr) &&

Object.keys(arr).length > 0; // Examples

isArrayNotEmpty([]); // false

isArrayNotEmpty([1, 2, 3]); // true

7. Swapping two variables

The below code is one of the simpler ways to swap two variables without using a third variable and with just one line of code.

[var1, var2] = [var2, var1];

Conclusion

We have learned 5 awesome JavaScript one-liners on this blog. I hope you have found these useful. Be sure to follow me on Twitter as I'm active on there too.

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favourite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.

Give it a try →

Learn more

[How We Build Micro Frontends
Building micro-frontends to speed up and scale our web development process.blog.bitsrc.io](https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc "blog.bitsrc.io/how-we-build-micro-front-end..")

[How we Build a Component Design System
Building a design system with components to standardize and scale our UI development process.blog.bitsrc.io](https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833 "blog.bitsrc.io/how-we-build-our-design-syst..")

[The Composable Enterprise: A Guide
To deliver in 2022, the modern enterprise must become composable.blog.bitsrc.io](https://blog.bitsrc.io/the-composable-enterprise-a-guide-609443ae1282 "blog.bitsrc.io/the-composable-enterprise-a-..")

[How to build a composable blog
Creating a blog from scratch requires quite a lot. There are a number of moving parts that come together to create a…bit.cloud](bit.cloud/blog/how-to-build-a-composable-bl.. "bit.cloud/blog/how-to-build-a-composable-bl..")

[Extendable UI Components
I was recently tasked with building a user-card component for the bit.cloud platform. I was also tasked with building…bit.cloud](bit.cloud/blog/extendable-uis-how-to-build-.. "bit.cloud/blog/extendable-uis-how-to-build-..")