Member-only story
Unlock the Power of JavaScript with These 60 Must-Know One-Liners
JavaScript is known for its flexibility and power, and one of the most elegant ways to harness that power is through concise one-liners. These snippets of code can save time, improve readability, and help you write efficient solutions to everyday challenges. In this post, I’m sharing 60 JavaScript one-liners that I regularly use in my development work. Whether you’re a novice or a seasoned developer, these tricks will come in handy!
- Check if an Array is Empty:
const isEmpty = arr => Array.isArray(arr) && !arr.length;
2. Find the Maximum Value in an Array:
const max = arr => Math.max(...arr);
3. Flatten a Nested Array:
const flatten = arr => arr.flat(Infinity);
4. Get the First and Last Elements of an Array:
const getFirstAndLast = arr => arr.length ? [arr[0], arr[arr.length - 1]] : [];
5. Convert a String to Title Case:
const titleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());
6. Get a Random Item from an Array:
const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];