10 One-Line Javascript Codes You Can’t stop

10 one-liner JavaScript codes that showcase some clever and efficient programming techniques:

  1. Generate an array of numbers from a to b:
const range = (a, b) => Array.from({length: b - a + 1}, (_, i) => i + a);
  1. Check if a string is empty or null:
isEmptyOrNull(str) { return !str || str.trim() === ''; }
  1. Reverse an array without modifying the original one (deep copy):
const reverseArray = arr => [...arr].reverse();
  1. Flatten nested arrays to a single level using recursion and reduce:
flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []); }
  1. Convert an object into its JSON string representation (deep copy):
toJsonString(obj) { return JSON.stringify(JSON.parse(JSON.stringify(obj))); }
  1. Check if a given character is present in the second half of strings:
isCharInSecondHalf(str, char) { const mid = str.length / 2; return str.substring(mid).includes(char); }
  1. Swap two variables without using an extra variable (destructuring):
swap(a, b) { [a, b] = [b, a]; }
  1. Count the number of words in all strings within nested arrays:
countWords(arrays) { return [].concat(...arrays).reduce((total, str) => total + (str.split(/\s+/g)?.length || 0), 0); }
  1. Remove falsy values from an array using filter method and default object properties access (__valueOf()) for primitives:
removeFalsy(arr) { return arr.filter(item => !!item); } // Simplified, JavaScript already does this with filter()
  1. Create a new Date object based on the current time plus seconds passed as input (using destructuring and spread operator):
newDateWithSeconds(currentTimeInMs = performance.now(), secsPassed) { return new Date(currentTimeInMs + secsPassed * 1000); }

These snippets demonstrate various JavaScript techniques, including ES6 features like arrow functions, template literals, array methods (such as map, reduce), destructuring assignment, and the spread operator. Note that some of these one-liners are more about illustrating best practices or clever tricks rather than being directly applicable in a production environment without context. Always consider readability when writing code for real-world applications!