7 Useful 1-Liner Methods for JavaScript: Simplifying Your Code

1. Array Summation - Sum all numbers in an array.

const sum = arr => arr.reduce((acc, val) => acc + val, 0);

2. Capitalizing the First Letter of a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

3. Checking if a Date is a Weekday

const isWeekday = date => date.getDay() % 6 !== 0;

4. Generating a Random Hex Color

const randomColor = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6, '0')}`;

5. Removing Duplicate Values from an Array

const unique = arr => [...new Set(arr)];

6. Toggling a Class in an Element

const toggleClass = (el, className) => el.classList.toggle(className);

7. Checking if a String is a Palindrome

const isPalindrome = str => str === str.split('').reverse().join('');