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

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.

Also read: What to Look for in a Programming Laptop

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:

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

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

let myarray = Array.from({length:52},(v,k)=>k+1);
 
console.log(shuffleArray(myarray));

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:

const isWeekend = (date) => date.getDay() % 6 == 0;

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

const isWeekday = (date) => date.getDay() % 6 !== 0;

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

console.log(isWeekend(new Date()));

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:

if(!isWeekend(new Date())) {
    console.log("Today falls on a weekday.");
 
} else {
    console.log("Today falls on a weekend.");
}
Javascript Weekend

Also read: 5 Questions to Help You Learn the Fundamentals of Programming

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:

const decimalFormat = (n, places) => ~~(Math.pow(10, places) * n) / Math.pow(10, places);

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.

let deciwow = 299.39542014592
 
console.log(decimalFormat(deciwow, 2));

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:

const cToF = (celsius) => celsius * 9/5 + 32;

And for Fahrenheit to Celsius:

const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;

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:

cToF(-2);

That expression yields a temperature of 28.4 degrees Fahrenheit.

Javascript Temperature

Also read: What’s the Difference Between Java and JavaScript?

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:

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

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

if (isDarkMode) {
    console.log("This screen is in dark mode.");
} else {
    console.log("This screen is not using dark mode.");
}

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:

const getAverage = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;

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

let dataset = [2, 14, 88, 204, 1515, 1294, 12, 144];
 
console.log(getAverage(dataset));

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:

const genUUID = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, genUUID));

Here, I test the output:

console.log(genUUID());
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:

const ageDays = (old, recent) => Math.ceil(Math.abs(old - recent) / (1000 * 60 * 60 * 24));

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:

console.log(ageDays(new Date('2012-12-28'), new Date()));

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:

const rangeRandom = (low, high) => Math.floor(Math.random() * (high - low + 1)) + low;

Testing this should be easy:

console.log(rangeRandom(400, 20000));
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

Miguel Leiva-Gomez
Miguel Leiva-Gomez - Staff Writer

Miguel has been a business growth and technology expert for more than a decade and has written software for even longer. From his little castle in Romania, he presents cold and analytical perspectives to things that affect the tech world.