DEV Community

Cover image for Mastering Javascript One-Liners to Look Like a Pro
ben ajaero
ben ajaero

Posted on

Mastering Javascript One-Liners to Look Like a Pro

Mastering Javascript One-Liners to Look Like a Pro

Javascript one-liners are all about writing succinct, efficient, and elegant pieces of code that not only perform a task with the least verbosity but also exhibit the power and expressiveness of modern ES Javascript. It’s about enhancing your coding style, making it clean, readable, and—above all—professional.

Introduction to Javascript One-Liners

A single line of Javascript can accomplish what used to take multiple lines, thanks to the evolution of ES6 and beyond, offering new functional features that make coding less of an effort and more of an art. These Javascript one-liners are not just about writing less code; they're about improving code quality, reducing errors, and making it highly approachable for other developers to understand.

Writing Clean and Efficient Code

When you utilize Javascript one-liners, you're taking advantage of modern syntactic sugar that allows for writing more with less. It’s no longer about the length but the impact and quality of your code that distinguishes you as a pro Javascript developer.

Enhancing Readability and Maintainability

The beauty of these one-liners lies in their ability to be both functional and readable While they may be compact, they're formatted in a way that makes them easily understandable to others who may inherit your code which is vital for maintainability.

One-Liners That Sharp Your Coding Style

Let's explore a few one-liners and understand their simplicity and power:

Generate a Random String

This is perfect for when you need a unique ID or a nonce for a session token. This one-liner shows just how expressive Javascript can be.

const randomString = () => Math.random().toString(36).slice(2);
Enter fullscreen mode Exit fullscreen mode

Check If a Day is a Weekday

Something so useful yet so simple. It’s quick checks like these that can save you a ton of time.

const isWeekday = (date) => date.getDay() % 6 !== 0;
Enter fullscreen mode Exit fullscreen mode

Copying Content to Clipboard

It’s all about enhancing user experience with minimal code.

const copyToClipboard = (content) => navigator.clipboard.writeText(content);
Enter fullscreen mode Exit fullscreen mode

Shuffle an Array

Great for randomising elements such as when you’re making a quiz or a game.

const shuffleArray = array => array.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

Convert RGBA to Hexadecimal and Vice Versa

Such conversions are handy for developing color pickers or design related tools.

const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('');
const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16));
  return `rgba(${r}, ${g}, ${b}, 1)`;
};
Enter fullscreen mode Exit fullscreen mode

Capitalize the First Letter of a String

Ideal for form inputs or when normalizing data for display.

const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
Enter fullscreen mode Exit fullscreen mode

Calculate Percentage

This is essential for applications that involve reports and analytics.

const calculatePercent = (value, total) => Math.round((value / total) * 100);
Enter fullscreen mode Exit fullscreen mode

Get a Random Element From an Array

It’s always fun to surprise users with something random.

const getRandomItem = (items) => items[Math.floor(Math.random() * items.length)];
Enter fullscreen mode Exit fullscreen mode

Remove Duplicate Elements

Essential for data processing to ensure uniqueness.

const removeDuplicates = (arr) => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

Sorting Elements By a Certain Property

Perfect for lists that require dynamic ordering.

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
Enter fullscreen mode Exit fullscreen mode

Convert String to camelCase

el casing is integral in Javascript for variable naming conventions.

const toCamelCase = (str) => str.trim().replace(/_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
Enter fullscreen mode Exit fullscreen mode

Folding a Long Line Without Breaking Words

Ideal for text formatting in UI elements space is constrained.

const foldLine = (line, maxChars) => line.replace(new RegExp(`(.{1,${maxChars}})(\\s+|$)`, 'g'), '$1\n').trim();
Enter fullscreen mode Exit fullscreen mode

Escape HTML Special Characters

To prevent XSS attacks, escaping input is crucial:

const escapeHTML = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]));
Enter fullscreen mode Exit fullscreen mode

Reverse a String

It's simple yet frequently for algorithms and logic puzzles.

const reverseString = str => str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Snippets in Modern Editors

For developers using frameworks like React, IDEs offer snippets such as af, rfc, and rafce, which generate anonymous function, React functional component, and React arrow function component with export respectively.

Javascript One-Liners FAQs

What is a Javascript one-liner?

A Javascript one-liner is a succinct line of code that executes a specific task or function in a compact and efficient manner.

Why are one-liners useful?

One-liners are useful for writing cleaner, more readable code, reducing the potential for errors, and saving developers' time.

Can one-liners be used in any Javascript project?

Yes, Javascript one-liners can be integrated into a variety of projects, providing they are written in modern ES Javascript.

How will using Javascript one-liners make me look like a pro?

Using Javascript one-liners demonstrates a mastery of language features and an ability to write elegant, efficient code.

Are there one-liner snippets for frameworks like React?

Yes, many code editors offer LSP (Language Server Protocol) enabled snippets for frameworks like React that allow for quick scaffolding of components and structures with simple keystrokes.

Conclusion

Adopting Javascript one-liners is a step towards upping your developer game and coding like a true pro. It shows a commitment to not just getting the job done, but doing it with finesse, simplicity, and perhaps most importantly, in a maintainable and scalable way. Whether it’s randomising strings, checking weekdays, or escaping HTML, one-liners allow you to code elegantly with modern ES Javascript at the forefront. As the language continues to evolve, so too will the potential for these compact gems of code. Embrace them and watch your coding transform from functional to fantastic.


Check out our agency site, Cox Code: https://www.coxcode.io

Dialogue with me on X: @benajaero

Top comments (25)

Collapse
 
oculus42 profile image
Samuel Rouse • Edited

There are a lot of great one-liners in here that can be very useful, but we may need to be more careful with array shuffling. For some purposes a simple random shuffle will suffice, but most shuffles have bias in them, and the amount of bias can depend on the JavaScript engine.

The Fisher-Yates shuffle is reliable and unbiased.

For a good visualization of differences, take a look at Mike Bostock's page Will It Shuffle? and try it in different browsers to see the variation.

Collapse
 
benajaero profile image
ben ajaero

That's true I considered including the bias, however I thought it might confuse people more.
The Fisher-Yates algorithm is great!

Collapse
 
mrlinxed profile image
Mr. Linxed • Edited

Remember that one-liners are not always better/faster/easier.

Readability goes over being clever.

Especially when a one-liner only passes its parameters to another method like this one

const copyToClipboard = (content) => navigator.clipboard.writeText(content);
Enter fullscreen mode Exit fullscreen mode

What's wrong with just:

navigator.clipboard.writeText(content);
Enter fullscreen mode Exit fullscreen mode

If anything, the copyToClipboard should check if the clipboard API is available to use.

Collapse
 
codingjlu profile image
codingjlu

Hex to rgb can be one-lined too (not sure why you include the alpha channel if you're not doing anything to it though...):

const hexToRgb = hex => `rgb(${hex.match(/\w\w/g).map(val => parseInt(val, 16))})`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
uiuxsatyam profile image
Satyam Anand

We love one liners but it can be challenging and sometimes confusing, especially for junior developers.

Btw, thanks for sharing this. Keep posting ❤️👍

Collapse
 
boly38 profile image
Brice • Edited

I agree that we must keep attention that "one line code" cant suffice. For me a good/pro code portion is a code easy to read/understand/adopt/maintain/extend.
Lenght of the code could be a way de improve the adoption but for ex. a var name or method name or statement complexity of a block.. are impotant too. If a junior is able to quickly adopt and extend your code. Then you're a pro 😎
Thanks for this great article 👌

Collapse
 
benajaero profile image
ben ajaero

Thanks Brice!

Collapse
 
benajaero profile image
ben ajaero

Thank you!

Collapse
 
michaeltharrington profile image
Michael Tharrington

Just have to say that I'm really digging this cover image. It reminds me of synthwave music!

Collapse
 
benajaero profile image
ben ajaero

Thanks Michael! It was definitely inspired.

Collapse
 
kodipe profile image
Konrad Przydział • Edited

From my perspective one-liners are ok as long as they are readable. Nowadays there are a lot of bundlers, compilers etc. which are able to make it more compact so we don't write code for making computer happy. We do it for other developers who need to spend time to understand it.

One good advice: Be pro instead of look like a pro.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

There should be a disclaimer that wanting to look like a pro is not being a pro. Writing these and explaining the benefits and drawbacks is being a pro

Collapse
 
kevinbism profile image
Kevin Ramirez

Great post!

Collapse
 
benajaero profile image
ben ajaero

Thank you!

Collapse
 
valvonvorn profile image
Collapse
 
codingmaster97 profile image
codingmaster97

Javascript is great

Some comments may only be visible to logged-in visitors. Sign in to view all comments.