9 JavaScript/Node.js One-Liners You Should Know

Use these useful Javascript one liner codes to help you quickly accomplish simple tasks.

Javascript One Liner Featured

As the web and applications become more complex, JavaScript and Node.js are increasingly becoming commonplace requirements in a developer’s repertoire. To improve your code-foo and minimize the headaches you encounter, you can define some functions early in your code that quickly accomplish simple tasks.

Do note that Javascript is not the same as Java. Check out the differences here.

1. Shuffle Around Values in an Array

Just like shuffling a deck of cards, you can also shuffle the values in an array as often as you like in JavaScript with this one-liner:

Keeping with the deck of cards analogy, this is what it would look like if I’d like to shuffle 52 values:

The code should reveal randomly jumbled values in your console output.

Javascript Shufflearray

2. Check if a Date Is on a Weekend or Weekday

By using a simple remainder operand, you can easily check if a day falls on a weekend in JavaScript:

If you want to change that to check whether the day in question falls on a weekday, just reverse the last comparison:

In the following code, I check whether today is on a weekend:

As an alternative to defining separate isWeekday or isWeekend variables, you can just use the NOT operand while expressing an if-then-else statement for either one of the two variables like so:

Javascript Weekend

3. Cut a Number to a Specific Decimal Point

The output you give to your users needs to be as simple as possible and nothing makes your site or app more unappealing than seeing an enormous garbled string of numbers. To cut off less significant decimal points in a number and display it like that to the user, grab this nifty definition:

To test this, I define a numeric value with a ridiculous amount of decimal places and call this quick function to cut it to two decimal places.

The result should be less of an eyesore.

Javascript Decimals

4. Convert Temperatures

In JavaScript there is no standardized way to convert between Celsius in Fahrenheit, but with two simple one-liners, you can create your own standard.

For Celsius to Fahrenheit:

And for Fahrenheit to Celsius:

In my town, the temperature is -2 degrees Celsius. Using the Celsius to Fahrenheit conversion one-liner we can find out what this means to someone living in the US:

That expression yields a temperature of 28.4 degrees Fahrenheit.

Javascript Temperature

5. Check if Someone’s Using Dark Mode

If you want the content you display to respect the color scheme of the person using your code, JavaScript includes a way to detect whether someone is using dark mode so you can adjust colors accordingly. The method is a little convoluted to write, but you can shorten this using this one-liner:

Here’s an example of a check using this variable:

Note that this code only works in JavaScript for browsers. Node.js does not implement support for window.

6. Get the Average of an Array of Numbers

When dealing with datasets, JavaScript has a handy function attached to arrays that lets you perform the arithmetic necessary to get the sum total of all the values of one particular table then divide these numbers by the length of the table. To do this elegantly in one line of code, you need only do this:

Here I make a dataset and pump out the average of all its values through the console:

Using this code, your output should be 409.125.

Javascript Average

7. Generate a UUID

If you want to collect statistics and data from people using your application (for example, by generating a cookie), one of the best ways to do this without being invasive is by generating a universally unique identifier (UUID). JavaScript doesn’t include an easy way to generate RFC4122-compliant UUIDs (although Node.js has the uuid npm package that provides this functionality out of the box).

In JS, you can pop out a freshly-minted UUID for your users with this one-line expression:

Here, I test the output:

Javascript Uuid

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. Here’s a simple one-liner that does that:

For an example use case, we pretend that we’re assessing the age of a user who created their account on December 28, 2012 and use this declaration to get the number of days between that date and today:

At the time of writing this, that should yield a result of 3298 days.

Javascript Days

9. Generate a Random Number Within a Range

Sometimes, it’s not enough to just generate some random number. You might just need to limit the conditions with which it is generated. With this one-liner, you’ll generate numbers within a certain specified range:

Testing this should be easy:

Javascript Randomrange

Frequently Asked Questions

1. Why use UUIDs in cookies?

Since cookies are by their very nature intrusive and occupy space on a user’s machine, you should aim to be as efficient and non-invasive as possible when using these instruments to gather data. Using a UUID provides a two-fold benefit. First, it minimizes the space occupied on client-based storage due to the identifier being only 128 bits in length. Secondly, it does depend on any personal data belonging to the user.

2. I get a “window is not defined” error in Node.js when detecting dark mode. What do I do?

Node.js cannot make calls to client-side modules because it does not have the same intrinsic client-server relationship that JavaScript has. The dark mode detection one-liner in this article is specifically meant for browser-based JavaScript.

3. Is this code universal to all browsers?

JavaScript code uses an interpreter that is supposed to function universally. While it theoretically works on all browsers, the way they interpret your code might differ slightly especially with very old software. In the case of all the one-liners expressed here, they should all return the same results regardless of the browser your user runs the code on. Be aware however that some features you use in JavaScript in general might not work on browsers like Pale Moon, Internet Explorer, or early-2000s versions of browsers that are currently actively developed.

Image credit: Profile side view of nice bearded guy by 123RF

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox