45 Powerful JavaScript One-Liners That You Must Know

45 Powerful JavaScript One-Liners That You Must Know

JavaScript is known for its flexibility and concise syntax. One of the best ways to write more efficient and elegant code is by using one-liners. These short, compact snippets can often replace longer, more complex code. Whether you’re a beginner or a seasoned developer, mastering JavaScript one-liners can improve your coding efficiency and help you write cleaner code

Here are 45 powerful JavaScript one-liners that you must know:

1. Check if an Array is Empty

const isEmpty = arr => !arr.length;

This one-liner checks if an array is empty by verifying that its length is zero.

2. Get the Maximum Value in an Array

const max = arr => Math.max(...arr);

Using the spread operator, this one-liner finds the maximum number in an array.

3. Flatten an Array

const flatten = arr => arr.flat();

The flat() method flattens nested arrays into a single array.

4. Sum of an Array

const sum = arr => arr.reduce((a, b) => a + b, 0);

This one-liner uses reduce to sum all elements in an array.

5. Generate a Random Number Between Two Values

const randomInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

Generates a random integer between a specified range.

6. Remove Duplicates from an Arra

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

This one-liner removes duplicates by converting the array to a Set and back to an array.

7. Find the Intersection of Two Arrays

const intersect = (a, b) => a.filter(x => b.includes(x));

Finds common elements between two arrays.

8. Check if a String is a Palindrom

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

This one-liner checks if a string is the same forwards and backwards.

9. Convert an Object to Query String

const toQueryString = obj => Object.keys(obj).map(key => `${key}=${obj[key]}`).join('&');

Converts an object into a URL query string.

10. Capitalize the First Letter of a String

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

Capitalizes the first letter of a string.

11. Check if a Number is Even

const isEven = num => num % 2 === 0;

This one-liner returns true if the number is even.

12. Check if a Number is Odd

const isOdd = num => num % 2 !== 0;

This one-liner returns true if the number is odd.

13. Convert a String to a Number

const toNumber = str => +str;

This one-liner converts a string to a number using the unary plus (+) operator.

14. Convert a Number to a String

const toString = num => num.toString();

This one-liner converts a number to a string.

15. Merge Two Arrays

const merge = (arr1, arr2) => [...arr1, ...arr2];

This one-liner merges two arrays into one using the spread operator.

16. Find the First Non-Repeated Character in a String

const firstUniqueChar = str => [...str].find((c, i, arr) => arr.indexOf(c) === arr.lastIndexOf(c));

Finds the first non-repeated character in a string.

17. Get the Current Date

const currentDate = () => new Date().toLocaleDateString();

This one-liner returns the current date in a human-readable format.

18. Convert an Array to an Object

const toObject = arr => Object.assign({}, arr);

Converts an array into an object.

19. Check if a Value is a Number

const isNumber = value => typeof value === 'number' && !isNaN(value);

Checks if the value is a valid number.

20. Get the Current Time

const currentTime = () => new Date().toLocaleTimeString();

This one-liner returns the current time.

21. Get the Unique Elements of an Array

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

Returns a new array containing only unique elements.

22. Convert an Array of Strings to Uppercase

const uppercaseArray = arr => arr.map(str => str.toUpperCase());

This one-liner converts all elements in an array to uppercase.

23. Check if a String Contains a Substring

const contains = (str, sub) => str.includes(sub);

This one-liner checks if a string contains a specific substring.

24. Find the Index of an Element in an Array

const indexOf = (arr, el) => arr.indexOf(el);

Finds the index of a specified element in an array.

25. Get a Random Element from an Array

const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];

Returns a random element from an array.

26. Get the Last Element of an Array

const last = arr => arr[arr.length - 1];

Returns the last element of an array.

27. Deep Clone an Object

const clone = obj => JSON.parse(JSON.stringify(obj));

Creates a deep clone of an object using JSON.

28. Sort an Array in Ascending Order

const sortAsc = arr => arr.sort((a, b) => a - b);

Sorts an array in ascending order numerically.

29. Sort an Array in Descending Order

const sortDesc = arr => arr.sort((a, b) => b - a);

Sorts an array in descending order numerically.

30. Remove Leading and Trailing Whitespace from a String

const trim = str => str.trim();

Removes both leading and trailing whitespace from a string.

31. Check if a String Starts with a Substring

const startsWith = (str, sub) => str.startsWith(sub);

Checks if a string starts with a specified substring.

32. Check if a String Ends with a Substring

const endsWith = (str, sub) => str.endsWith(sub);

Checks if a string ends with a specified substring.

33. Get the Length of an Array

const length = arr => arr.length;

Returns the length of an array.

34. Repeat a String Multiple Times

const repeatString = (str, times) => str.repeat(times);

Repeats a string a specified number of times.

35. Get a Range of Numbers

const range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);

Generates an array with numbers in the specified range.

36. Get the Keys of an Object

const keys = obj => Object.keys(obj);

Returns an array of the object’s keys.

37. Get the Values of an Object

const values = obj => Object.values(obj);

Returns an array of the object’s values.

38. Find the Largest Number in an Array

const maxInArray = arr => Math.max(...arr);

Returns the largest number from an array.

39. Merge Two Objects

const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });

Merges two objects into one.

40. Get the Current Epoch Time

const epochTime = () => Date.now();

Returns the current time in milliseconds since the Unix epoch.

41. Convert an Object to a JSON String

const toJSON = obj => JSON.stringify(obj);

Converts an object to a JSON string.

42. Get the Value of a URL Parameter

const getURLParameter = (url, param) => new URL(url).searchParams.get(param);

Gets the value of a URL query parameter.

43. Find the Type of a Variable

const typeOf = value => typeof value;

Returns the type of a variable.

44. Check if an Object is Empty

const isEmptyObject = obj => Object.keys(obj).length === 0;

Checks if an object has no properties.

45. Convert a Value to a Boolean

const toBoolean = value => Boolean(value);

Converts a value to a boolean.

Mastering these JavaScript one-liners will not only make your code more concise but also improve its readability. As you become more familiar with these, you’ll develop an intuitive understanding of how to use JavaScript efficiently and elegantly.

See Also: