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]
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 <p>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.</p> <h2> Object Transform: Deep Clone Without Dependencies </h2> <p>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:<br> </p> <pre class="brush:php;toolbar:false">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);
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; }
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' } // ]
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 <p>It's an effective way of doing data transformation with a one-liner, but add some error handling before plunging it into production.</p> <h2> Array Operations: Remove Duplicates and Sort </h2> <p>Here's a shortened one-liner that removes duplicates and sorts your array at the same time, perfect for cleaning a data set:<br> </p> <pre class="brush:php;toolbar:false">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']
This is what the old way used to look like:
function cleanArrayManually(arr) { const unique = []; for (let i = 0; i a - b); }
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 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]
The traditional approach would be:
function flattenTheHardWay(arr) { let result = []; for (let i = 0; i <p>This works in all modern browsers and saves you from writing repetitive DOM manipulation code.</p> <h2> Parallel API Calls with Clean Error Handling </h2> <p>This is another clean line, one-liner that does parallel calls to APIs and does so in very clean error handling.<br> </p> <pre class="brush:php;toolbar:false">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);
More verbose would be:
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; }
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 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' } // ]
The old-school way would look like this:
function convertCSVTheHardWay(csv) { const lines = csv.split('\n'); const headers = lines[0].split(','); const result = []; for (let i = 1; i <p>Intl.DateTimeFormat handles all the heavy lifting, including localization. No more manual date string building!</p> <h2> Event Handling: Debounce Without the Bloat </h2> <p>Here's a clean one-liner that creates a debounced version of any function - perfect for search input or window resize handlers:<br> </p> <pre class="brush:php;toolbar:false">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']
The traditional way would look like this:
function cleanArrayManually(arr) { const unique = []; for (let i = 0; i a - b); }
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 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'));
The old way would need something like this:
function updateElementsManually(selector) { const elements = document.querySelectorAll(selector); for (let i = 0; i <p>The wrapper gives you a clean API for localStorage operations and handles all the JSON parsing/stringify automatically.</p> <h2> Wrapping Up </h2> <p>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.</p> <p>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.</p> <p>Got your own powerful JavaScript one-liners? I'd love to see them! </p> <p>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.</p><p>Stay curious, keep coding, and remember: good code is not about how little you write, but how clearly you express your intent.</p>
The above is the detailed content of avaScript One-Liners That Replace Lines of Code. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
