DEV Community

Paul
Paul

Posted on

9 JavaScript One-Liners That Replace 50 Lines of Code

We have all, at one time or another, looked at some horrid wall of JavaScript code cursing silently within ourselves, knowing pretty well that there should be a better way.

After some time spent learning, I have found some neat one-liners that will obliterate many lines of verbose code.

These are truly useful, readable tips that take advantage of modern JavaScript features for tackling common problems.

So, whether you are cleaning up code or just starting a fresh project, these tricks can help with more elegant and maintainable code.

Here are 9 such nifty one-liners you can use today.

Flattening a Nested Array

Ever tried flattening an array that goes so deep? Back in the day, that meant lots of complicated multiple loops, temporary arrays, and altogether too much code.

But now it's executed very nicely in a powerful single-liner:

const flattenArray = arr => arr.flat(Infinity);

const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

If you would do this in a more traditional way, you would have something like this:

function flattenTheHardWay(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenTheHardWay(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

All hard work is taken care of by the flat(), and adding Infinity tells it to go down to any level that it may. Simple, clean, and it works.

Object Transform: Deep Clone Without Dependencies

If you need a true deep clone of an object without pulling in lodash? Here's a zero-dependency solution that handles nested objects, arrays, and even dates:

const deepClone = obj => JSON.parse(JSON.stringify(obj));

const complexObj = {
  user: { name: 'Alex', date: new Date() },
  scores: [1, 2, [3, 4]],
  active: true
};

const cloned = deepClone(complexObj);
Enter fullscreen mode Exit fullscreen mode

The old way? You'd have to type something like this:

function manualDeepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);

  const clone = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clone[key] = manualDeepClone(obj[key]);
    }
  }
  return clone;
}
Enter fullscreen mode Exit fullscreen mode

Quick heads-up: This one-liner does have a few limitations - it won't handle functions, symbols, or circular references. But for 90% of use cases, it's pretty much spot on.

String Processing: Convert CSV to Array of Objects

This is a nice little one-liner that takes CSV data and spits out a manipulable array of objects, ideally for use in API responses or reading in data:

const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));

const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;

const parsed = csvToObjects(csvData);
// Result:
// [
//   { name: 'Peboy', age: '30', city: 'New York' },
//   { name: 'Peace', age: '25', city: 'San Francisco' },
//   { name: 'Lara', age: '35', city: 'Chicago' }
// ]
Enter fullscreen mode Exit fullscreen mode

Old-fashioned? Oh, you would probably be writing something like this:

function convertCSVTheHardWay(csv) {
  const lines = csv.split('\n');
  const headers = lines[0].split(',');
  const result = [];

  for (let i = 1; i < lines.length; i++) {
    const obj = {};
    const currentLine = lines[i].split(',');

    for (let j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentLine[j];
    }
    result.push(obj);
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

It's an effective way of doing data transformation with a one-liner, but add some error handling before plunging it into production.

Array Operations: Remove Duplicates and Sort

Here's a shortened one-liner that removes duplicates and sorts your array at the same time, perfect for cleaning a data set:

const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);

// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]

// For string sorting

const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

This is what the old way used to look like:

function cleanArrayManually(arr) {
  const unique = [];
  for (let i = 0; i < arr.length; i++) {
    if (unique.indexOf(arr[i]) === -1) {
      unique.push(arr[i]);
    }
  }
  return unique.sort((a, b) => a - b);
}
Enter fullscreen mode Exit fullscreen mode

The Set takes care of duplicates perfectly, and then the spread operator turns it back into an array. And you just call sort() afterwards!

DOM Manipulation: Query and Transform Multiple Elements

Here's a powerful one-liner that lets you query and transform multiple DOM elements in one go:

const modifyElements = selector => Array.from(document.querySelectorAll(selector)).forEach(el => el.style);

// Use it like this:
const updateButtons = modifyElements('.btn')
  .map(style => Object.assign(style, {
    backgroundColor: '#007bff',
    color: 'white',
    padding: '10px 20px'
}));

// Or even simpler for class updates:
const toggleAll = selector => document.querySelectorAll(selector).forEach(el => el.classList.toggle('active'));
Enter fullscreen mode Exit fullscreen mode

The traditional approach would be:

function updateElementsManually(selector) {
  const elements = document.querySelectorAll(selector);
  for (let i = 0; i < elements.length; i++) {
    const el = elements[i];
    el.style.backgroundColor = '#007bff';
    el.style.color = 'white';
    el.style.padding = '10px 20px';
  }
}
Enter fullscreen mode Exit fullscreen mode

This works in all modern browsers and saves you from writing repetitive DOM manipulation code.

Parallel API Calls with Clean Error Handling

This is another clean line, one-liner that does parallel calls to APIs and does so in very clean error handling.

const parallelCalls = urls => Promise.allSettled(urls.map(url => fetch(url).then(r => r.json())));


// Put it to work:
const urls = [
  'https://api.example.com/users',
  'https://api.example.com/posts',
  'https://api.example.com/comments'
];


// One line to fetch them all:
const getData = async () => {
  const results = await parallelCalls(urls);
  const [users, posts, comments] = results.map(r => r.status === 'fulfilled' ? r.value : null);
};
Enter fullscreen mode Exit fullscreen mode

More verbose would be:

async function fetchDataManually(urls) {
  const results = [];
  for (const url of urls) {
    try {
      const response = await fetch(url);
      const data = await response.json();
      results.push({ status: 'fulfilled', value: data });
    } catch (error) {
      results.push({ status: 'rejected', reason: error });
    }
  }
  return results;
}
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled is the hero here; it doesn't fail if one request fails and it gives back clean status information for each call.

Date/Time Formatting: Clean Date Strings Without Libraries

Here's a sweet one-liner that turns dates into clean, readable strings without any external dependencies:

const formatDate = date => new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'short' }).format(date);

const now = new Date();
console.log(formatDate(now));
// Output: "Thursday, December 3, 2024 at 2:30 PM"

// Want a different format? Easy:
const shortDate = date => new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(date);
// Output: "Dec 3, 2024"
Enter fullscreen mode Exit fullscreen mode

The old-school way would look like this:

function formatDateManually(date) {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  const dayName = days[date.getDay()];
  const monthName = months[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';

  return `${dayName}, ${monthName} ${day}, ${year} at ${hours % 12}:${minutes.toString().padStart(2, '0')} ${ampm}`;
}
Enter fullscreen mode Exit fullscreen mode

Intl.DateTimeFormat handles all the heavy lifting, including localization. No more manual date string building!

Event Handling: Debounce Without the Bloat

Here's a clean one-liner that creates a debounced version of any function - perfect for search input or window resize handlers:

const debounce=(fn,ms)=>{let timeout;return(...args)=>{clearTimeout(timeout);timeout=setTimeout(()=>fn(...args),ms);};};

// Put it to work:
const expensiveSearch=query=>console.log('Searching for:',query);
const debouncedSearch=debounce(expensiveSearch,300);

// Use it in your event listener:
searchInput.addEventListener('input',e=>debouncedSearch(e.target.value));
Enter fullscreen mode Exit fullscreen mode

The traditional way would look like this:

function createDebounce(fn, delay) {
  let timeoutId;

  return function debounced(...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      fn.apply(this, args);
      timeoutId = null;
    }, delay);
  };
}
Enter fullscreen mode Exit fullscreen mode

This one-liner covers all basic debouncing use cases and saves you from calling functions unnecessarily, especially when inputs are generated in rapid succession like typing or resizing.

Local Storage: Object Storage with Validation

Here's just another clean one-liner that handles object storage in localStorage with built-in validation and error handling:

const store = key => ({ get: () => JSON.parse(localStorage.getItem(key)), set: data => localStorage.setItem(key, JSON.stringify(data)), remove: () => localStorage.removeItem(key) });

// Use it like this:
const userStore = store('user');

// Save data
userStore.set({ id: 1, name: 'John', preferences: { theme: 'dark' } });

// Get data
const userData = userStore.get();

// Remove data
userStore.remove();
Enter fullscreen mode Exit fullscreen mode

The old way would need something like this:

function handleLocalStorage(key) {
  return {
    get: function() {
      try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : null;
      } catch (e) {
        console.error('Error reading from localStorage', e);
        return null;
      }
    },
    set: function(data) {
      try {
        localStorage.setItem(key, JSON.stringify(data));
      } catch (e) {
        console.error('Error writing to localStorage', e);
      }
    },
    remove: function() {
      try {
        localStorage.removeItem(key);
      } catch (e) {
        console.error('Error removing from localStorage', e);
      }
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

The wrapper gives you a clean API for localStorage operations and handles all the JSON parsing/stringify automatically.

Wrapping Up

These one-liners aren't just about writing less code – they're about writing smarter code. Each one solves a common JavaScript challenge in a clean, maintainable way. While these snippets are powerful, remember that readability should always come first. If a one-liner makes your code harder to understand, break it down into multiple lines.

Feel free to mix and match these patterns in your projects, and don't forget to check browser compatibility for newer JavaScript features like flat() or Intl.DateTimeFormat if you're supporting older browsers.

Got your own powerful JavaScript one-liners? I'd love to see them!

Follow me on X for more JavaScript tips, tricks, and discussions about web development. I regularly share code snippets and best practices that make our dev lives easier.

Stay curious, keep coding, and remember: good code is not about how little you write, but how clearly you express your intent.

Top comments (20)

Collapse
 
gitkearney profile image
Kearney Taaffe

A lot of these one liners are just bad coding standards in general. Each line should have 1 function/operation.

Take for example your "Debounce Event Handling" example. If you need to debug that with a breakpoint, you really can't without formatting it. And the "trad" way is more readable.

Also just looking at this ),ms);};}; That's seriously bad readability there.

Code IS READ more than it is WRITTEN make things easier on your readers

Collapse
 
gopikrishna19 profile image
Gopikrishna Sathyamurthy

This. Just because it can be written in one line doesn't mean it should 😊. White space is free. Write elegant readable code and let the bundler do its job. No need to write like a bundler. The article could be better named as "using modern JavaScript"

Collapse
 
jonrandy profile image
Jon Randy 🎖️

For object cloning, just use the built in structuredClone function

Collapse
 
moopet profile image
Ben Sinclair

Some of these are things where you're better off using a library or core function.
For example, the CSV parsing will explode if you escape or quote commas.

Collapse
 
cptcrunchy profile image
Jason Gutierrez • Edited

Id also add that it didnt take into account the hidden Byte Order Marker (BOM) that .xlsx files tend to have.

Remember we write code for colleagues and future selves.

Collapse
 
gopikrishna19 profile image
Gopikrishna Sathyamurthy

@peboycodes some of us here are probably a senior dev, or been developing for quite some time. The common theme is that just because we could we shouldn't. While you demonstrated a quite a few APIs in JS, to us, one liners are usually pain to read and debug. To an up and coming developer, these may look cool, and I'm afraid it is just that, nothing more. A good code reduces cognitive overload, reduces complexity, increases maintainability and performance. One liners like .flat are great, however, fitting a map, reduce and other logic, with minified variables is no so good. You are showing a lot of efficiencies in your examples, and I don't want all of our comments to diminish the value of that. Great work ✨. I wish you good luck in your long journey as a developer. I strongly believe you'll write another article talking about things we commented on, because we have been there in this phase as well 😅

Collapse
 
miketalbot profile image
Mike Talbot ⭐

In addition to what @jonrandy said, JSON.parse(JSON.stringify(item)) is not a true deep clone of an object - if before doing that, you had the same reference repeated in multiple objects or arrays, then after you have multiple copies of that reference. There are times when stringify/parse work out - but you should pick structuredClone by default.

Collapse
 
rvraaphorst profile image
Ronald van Raaphorst

Well, putting everything on one line sure does make it a 'one-liner' ;)
Still, thanks for pointing to some usefull API's.

Collapse
 
skhmt profile image
Mike 🐈‍⬛

The key takeaway people should get from this article is: just because you can do something in one line, doesn't mean that it should be done in one line.

Debugging is harder, readability is sacrificed, and one-liners often sacrifice error checking and edge cases to reasonably fit on one line.

And of course, use structuredClone, not parse(stringify()).

Collapse
 
retakenroots profile image
Rene Kootstra • Edited

In the frontend i would debounce with requestAnimationFrame...

Collapse
 
oculus42 profile image
Samuel Rouse

With .flat(Infinity) you should be prepared for circular references to throw an error.

const a = [];
const b = [a]
a.push(b);
a.flat(Infinity); // RangeError: Maximum call stack size exceeded
Enter fullscreen mode Exit fullscreen mode

It may be unlikely in most cases, recognize that using Infinity – or even numbers like 10000 –  .flat() can throw a RangeError.

Collapse
 
amankrokx profile image
Aman Kumar • Edited

If you use something called JavaScript minifier along with bundler (if code is split across multiple files) you can not just replace more lines of code into one.

Here's a dijkstra algorithm one liner that I never use.

let V=9;function minDistance($,t){let r=Number.MAX_VALUE,e=-1;for(let n=0;n<V;n++)!1==t[n]&&$[n]<=r&&(r=$[n],e=n);return e}function printSolution($){console.log("Vertex         Distance from Source<br>");for(let t=0;t<V;t++)console.log(t+"          "+$[t]+"<br>")}function dijkstra($,t){let r=Array(V),e=Array(V);for(let n=0;n<V;n++)r[n]=Number.MAX_VALUE,e[n]=!1;r[t]=0;for(let o=0;o<V-1;o++){let i=minDistance(r,e);e[i]=!0;for(let l=0;l<V;l++)!e[l]&&0!=$[i][l]&&r[i]!=Number.MAX_VALUE&&r[i]+$[i][l]<r[l]&&(r[l]=r[i]+$[i][l])}printSolution(r)}let graph=[[0,4,0,0,0,0,0,8,0],[4,0,8,0,0,0,0,11,0],[0,8,0,7,0,4,0,0,2],[0,0,7,0,9,14,0,0,0],[0,0,0,9,0,10,0,0,0],[0,0,4,14,10,0,2,0,0],[0,0,0,0,0,2,0,1,6],[8,11,0,0,0,0,1,0,7],[0,0,2,0,0,0,6,7,0]];dijkstra(graph,0);
Enter fullscreen mode Exit fullscreen mode