A collection of useful one-liner JavaScript snippets for your next project.
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
Description: The capitalize
function takes a string as input and returns a new string with the first character converted to uppercase while leaving the rest of the string unchanged.
const calculatePercent = (value, total) => Math.round((value / total) * 100);
Description: Calculates the percentage of value
relative to total
, rounded to the nearest integer. It includes error handling for non-numeric inputs and checks for a zero total to prevent division by zero.
const getRandomItem = (items) => items[Math.floor(Math.random() * items.length)];
Description: Returns a random element from an array.
const isPalindrome = (str) => str === str.split("").reverse().join("");
Description: Checks if a given string is a palindrome (reads the same backward as forward).
const reversedString = (str) => str.split("").reverse().join("");
Description: Reverses the characters in a string.
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
Description: Randomly shuffles the elements of an array.
const isEven = (num) => num % 2 === 0;
Description: Returns true
if the number is even, false
otherwise.
const objectLength = (obj) => Object.keys(obj).length;
Description: Returns the number of properties in an object.
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
Description: Creates a deep clone of an object. This method is simple but may not work for objects with functions or undefined values.
const isTruthy = (num) => !!num;
Description: Converts a number to its boolean equivalent (truthy or falsy).