A checklist showing ten JavaScript one-liner techniques: flatten arrays, unique values, swap variables, logical AND, type conversion, fill arrays, random integers, reverse strings, extract properties, and palindrome checks.

Modern JavaScript one-liners that simplify your code

JavaScript has evolved dramatically with ES6 and beyond, giving software engineers powerful syntax to solve problems with elegance and efficiency. Modern JavaScript one-liners demonstrate how to write expressive code that accomplishes tasks in a single line. The keyphrase "JavaScript one-liners" captures a whole category of techniques that let you work functionally and concisely. Here, we explore practical patterns you can use to simplify your code, with a clear explanation of what makes each one work.

Flattening Nested Arrays#

Nested arrays can be difficult to work with when you need all elements as a single-level array. The flat() method provides an elegant solution that recursively processes nested arrays to a specified depth.

flatten.js · javascript
const arr = [1, [2, [3, [4]], 5]];
const flattened = arr.flat(2); // [1, 2, 3, [4], 5]
const deepFlat = arr.flat(Infinity); // [1, 2, 3, 4, 5]

The flat() method takes a depth argument that determines how deep the array should be flattened. Pass Infinity to flatten all levels. This is particularly useful when working with data from APIs or when combining multiple data sources.

Filtering Unique Values#

Removing duplicate values from an array is a common requirement. By leveraging ES6's Set, this task becomes trivial and highly efficient.

unique.js · javascript
const arr = [1, 2, 3, 3, 4, 5, 5];
const unique = [...new Set(arr)]; // [1, 2, 3, 4, 5]

A Set automatically eliminates duplicates, and the spread operator converts it back into an array for further use. This approach works with any data type and runs in linear time, making it suitable for performance-critical code.

Swapping Variables Without a Temporary Variable#

Swapping values between two variables usually requires a temporary variable. With destructuring, this becomes unnecessary and reads as intention.

swap.js · javascript
let a = 10, b = 20;
[a, b] = [b, a];
console.log(a, b); // 20 10

Array destructuring directly swaps values in a single operation. This pattern is clean, intuitive and makes the code's purpose immediately clear to you.

Shorthand Conditional with Logical AND#

Simplify conditional expressions when one outcome is based on a single condition being true. The logical AND operator provides a compact alternative to verbose ternary operations.

logical.js · javascript
const isLoggedIn = true;
const user = isLoggedIn && 'Atyantik User'; // 'Atyantik User'

If the condition is true, the value is returned. If false, undefined is returned. This pattern is readable when the condition and value have a clear relationship. Use it when only the truthy branch matters to your code.

Converting Strings to Numbers#

Convert strings to numbers quickly using the unary plus operator. This operator coerces the string into its numeric representation if it is a valid number.

convert.js · javascript
const str = "1990";
const num = +str; // 1990

The plus operator is faster than parseInt() for simple conversions and more readable for numeric type coercion. Invalid strings return NaN, which you can check with Number.isNaN() if needed.

Filling an Array with Values#

Need an array pre-filled with values? Combine Array() and fill() to achieve this effortlessly.

fill.js · javascript
const filledArray = Array(5).fill(1); // [1, 1, 1, 1, 1]

This creates an array of a specified length and fills it with the provided value. Useful for initializing arrays with default values or creating placeholder structures for data processing.

Generating a Random Integer in a Range#

Get a random integer between min and max using Math.random() and Math.floor(). This pattern scales the random value to your desired range.

random.js · javascript
const randomInt = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
// Random integer between 1 and 10

Math.random() generates a number between 0 and 1. By scaling it with (max - min + 1) and adding min, we ensure the result falls within the desired range. This approach handles both inclusive bounds correctly.

Reversing a String#

Reversing a string in JavaScript combines split(), reverse() and join() into one expressive line.

reverse.js · javascript
const str = "Atyantik";
const reversed = str.split('').reverse().join(''); // 'kitnaytA'

This one-liner splits the string into an array of characters, reverses that array, and joins it back into a string. Simple, memorable and efficient for string reversal.

Extracting a Specific Property from Objects#

Using map(), you can extract a specific property from an array of objects in a single line.

extract.js · javascript
const arr = [{ name: "Bob" }, { name: "John" }];
const names = arr.map(obj => obj.name); // ['Bob', 'John']

The map() method creates a new array populated with the results of calling a function on every element. Here it extracts the name property. This pattern is foundational for transforming data structures.

Checking for Palindromes#

Checking if a string is a palindrome (the same forward and backward) can be done in one line by comparing the original to its reversed version.

palindrome.js · javascript
const str = "rotator";
const isPalindrome = str === str.split('').reverse().join(''); // true

This splits the string, reverses it, joins it back together, then checks if the result equals the original string. It is a clean demonstration of how composing built-in methods produces elegant logic.

Mastering One-Liners#

JavaScript one-liners are not about squeezing functionality into fewer lines. They are about leveraging powerful language features to write clear, efficient and elegant code. The patterns here use modern ES6 features that modern JavaScript engines optimize heavily, so you get readability and performance together.

Use one-liners judiciously and make sure your code remains readable and maintainable. A one-liner that requires explanation defeats its own purpose. Mastering these patterns helps you think more functionally and makes your coding experience much more enjoyable. The goal is code that is both concise and immediately understandable to anyone reading it, as of December 2024.

When you build production applications that need to scale, these patterns form a solid foundation. For larger codebases or teams, understanding custom software development practices and web performance optimization helps you know when one-liners serve your code best and when a different approach works better for your goals.

Questions this post answers

What is a JavaScript one-liner?
A JavaScript one-liner is a single line of code that accomplishes a task that might normally require multiple lines. Modern JavaScript features like arrow functions, destructuring and method chaining allow developers to write concise solutions that are both elegant and maintainable. One-liners use built-in methods and operators to solve problems efficiently.
When should I use one-liners in production code?
Use one-liners when they remain readable and do not sacrifice clarity for brevity. The goal is elegant code that your team can understand without explanation. Avoid one-liners that obscure logic or make debugging harder. Strike a balance between conciseness and maintainability. A one-liner is valuable only when the next person reading it can grasp its purpose immediately.
Are JavaScript one-liners performant?
Yes. Methods like flat(), Set operations and map() are optimized by JavaScript engines and often perform as well as or better than manual loops. The performance gain comes from the fact that these built-in methods run compiled code rather than interpreted JavaScript. Choose the one-liner based on readability and correctness first, as performance differences are usually negligible for most applications.

Keep reading