Go back Modern JavaScript One-Liners: Elegance in Simplicity /* by Maulik Macwan - December 18, 2024 */ Tech Update AtyantikFrontendjavascript JavaScript has come a long way, and modern features like ES6 and beyond have given developers powerful syntax to solve problems concisely and efficiently. Modern JavaScript One-Liners are a great way to write elegant and expressive code that accomplishes tasks in a single line. Here, we’ll explore some practical, JavaScript one-liners that you can use to simplify your code, with a breakdown of what makes each one work. 1. Flattening Arrays Nested arrays can be difficult to work with, especially when you need to access all their elements as a single-level array. JavaScript’s flat() method provides an easy way to flatten arrays to a specified depth. const flattened = arr.flat(<depth>); Explanation: The flat() method takes a depth argument that determines how deep the array should be flattened. It recursively processes nested arrays to reduce their structure. Example: const arr = [1, [2, [3, [4]], 5]]; const flattened = arr.flat(2); // [1, 2, 3, [4], 5] // Use 'Infinity' to recursively flatten an array to its deepest level const flattened = arr.flat(Infinity); // [1, 2, 3, 4, 5] 2. Filtering Unique Values in an Array Removing duplicate values from an array is a common requirement. By leveraging ES6’s Set, this task becomes trivial and highly efficient with Modern JavaScript One-Liners. const unique = [...new Set(arr)]; Explanation: A Set automatically eliminates duplicates, and the spread operator (...) converts it back into an array for further use. Example: const arr = [1, 2, 3, 3, 4, 5, 5]; const unique = [...new Set(arr)]; // [1, 2, 3, 4, 5] 3. Swapping Variables Without a Temp Variable Swapping values between two variables usually requires a temporary variable. With destructuring, this becomes unnecessary in Modern JavaScript One-Liners. [a, b] = [b, a]; Explanation: Array destructuring directly swaps the values in a single, intuitive operation. Example: let a = 10, b = 20; [a, b] = [b, a]; console.log(a, b); // 20 10 4. Shorthand for Ternary with Logical AND (&&) Simplify conditional expressions when one outcome is based on a single condition being true. const result = condition && value; Explanation: If the condition is true, then only the value is returned. It’s a compact way to avoid writing verbose conditionals in your Modern JavaScript One-Liners. Example: const isLoggedIn = true; const user = isLoggedIn && 'Atyantik User'; // 'Atyantik User' 5. Converting a String to a Number Convert strings to numbers quickly using the unary + operator in Modern JavaScript One-Liners. const num = +str; Explanation: The + operator coerces the string into its numeric representation if it’s a valid number. Example: const str = "1990"; const num = +str; // 1990 6. Filling an Array Need an array pre-filled with values? Use Array() and fill() to achieve this effortlessly in Modern JavaScript One-Liners. const filledArray = Array(length).fill(value); Explanation: This creates an array of a specified length and fills it with the provided value. Example: const filledArray = Array(5).fill(1); // [1, 1, 1, 1, 1] 7. Generate a Random Integer in a Range To get a random integer between min and max using Modern JavaScript One-Liners, you can use Math.random() and Math.floor(): const randomInt = Math.floor(Math.random() * (max - min + 1)) + min; Explanation: Math.random() generates a random number between 0 and 1. By scaling it with (max – min + 1) and adding min, we ensure it falls within the desired range. Example: const randomInt = Math.floor(Math.random() * (10 - 1 + 1)) + 1; // Random integer between 1 and 10 8. Reversing a String Reversing a string in JavaScript is simple with split(), reverse(), and join(). This is an example of Modern JavaScript One-Liners: const reversed = str.split('').reverse().join(''); Explanation: This one-liner splits the string into an array of characters, reverses that array, and joins it back into a string. Example: const str = "Atyantik"; const reversed = str.split('').reverse().join(''); // 'kitnaytA' 9. Extracting a Specific Property from an Array of Objects Using map(), you can extract a specific property from an array of objects: const names = arr.map(obj => obj.name); Explanation: The map() method creates a new array populated with the results of calling a provided function on every element in the array, in this case extracting the name property using Modern JavaScript One-Liners. Example: const arr = [{ name: "Bob" }, { name: "John" }]; const names = arr.map(obj => obj.name); // ['Bob', 'John'] 10. Checking for Palindrome Checking if a string is a palindrome (the same forward and backward) can be done in one line with Modern JavaScript One-Liners: const isPalindrome = str === str.split('').reverse().join(''); Explanation: This splits the string, reverses it, and joins it back together, then checks if the result is equal to the original string. Example: const str = "rotator"; const isPalindrome = str === str.split('').reverse().join(''); // true Conclusion JavaScript one-liners are not just about squeezing functionality into fewer lines—they’re about leveraging powerful language features to write clear, efficient, and elegant code. Modern JavaScript One-Liners, while they can be great for reducing verbosity, it’s important to use them judiciously; make sure your code remains readable and maintainable. Mastering these patterns helps you think more functionally and makes your coding experience much more enjoyable.