Introduction

JavaScript, the versatile and ubiquitous programming language, is known for its ability to perform a wide range of tasks. Whether you’re a seasoned developer or just getting started, you can supercharge your coding skills by mastering one-liners—short, elegant code snippets that accomplish complex tasks with minimal code. In this article, we’ll explore some awesome JavaScript one-liners, dissect their functionality, and show you how they can enhance your coding prowess.

The Magic of JavaScript One-Liners

One-liners in JavaScript are like little nuggets of wisdom. They demonstrate the beauty and power of the language by encapsulating complex operations into concise code snippets. These one-liners can simplify your code, make it more readable, and boost your productivity. Let’s dive into some examples to see how they work.

1. Reversing a String

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

This one-liner takes an input string, splits it into an array of characters, reverses the order of the characters, and then joins them back together into a string. It’s a quick and efficient way to reverse a string without using loops or additional variables.

2. Checking for Palindromes

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

Here’s another one-liner that checks if a given string is a palindrome (reads the same forwards and backwards). It does so by reversing the string and comparing it to the original string. If they match, it’s a palindrome.

3. Finding the Maximum Value in an Array

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

To find the maximum value in an array, you can use the Math.max method combined with the spread operator (...) to apply it to an array of numbers. This one-liner eliminates the need for loops or manual tracking of the maximum value.

4. Calculating the Sum of Array Elements

javascript
const arraySum = arr => arr.reduce((total, current) => total + current, 0);

The reduce method is a powerful tool for array manipulation. This one-liner calculates the sum of all elements in an array by iteratively adding each element to the accumulator (total).

5. Generating an Array of Random Numbers

javascript
const randomNumbers = (min, max, count) => Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min);

This one-liner creates an array of random numbers within a specified range (min to max) and with a specified count. It uses the Array.from method and an arrow function to generate the numbers.

6. Removing Duplicates from an Array

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

If you have an array with duplicate elements and you want to remove them, this one-liner comes to the rescue. It leverages JavaScript’s Set object to eliminate duplicates and spreads the result back into an array.

7. Flattening an Array

javascript
const flattenArray = arr => arr.flat(Infinity);

When dealing with nested arrays, flattening them into a single array can be challenging. This one-liner uses the flat method with the Infinity depth to flatten an array of any level of nesting.

8. Checking if an Object is Empty

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

To determine if an object is empty, you can use this one-liner. It checks if the number of keys in the object is zero, which is a reliable indicator of emptiness.

9. Swapping Variables

javascript
let a = 5, b = 10;
[a, b] = [b, a];

Swapping the values of two variables in JavaScript can be done in a single line using array destructuring. This one-liner demonstrates a neat trick to exchange the values of a and b without using a temporary variable.

10. Shuffling an Array

javascript
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);

If you want to randomize the order of elements in an array, this one-liner does the job. It uses the sort method with a random sorting function, ensuring that the array gets shuffled.

11. Checking for Even and Odd Numbers

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

These two one-liners help you determine whether a number is even or odd. They use the modulo operator to check for divisibility by 2.

12. Creating a Countdown

javascript
const countdown = seconds => {
const interval = setInterval(() => {
if (seconds <= 0) {
clearInterval(interval);
console.log("Countdown complete!");
} else {
console.log(`${seconds} seconds remaining`);
seconds--;
}
}, 1000);
};

This one-liner creates a countdown timer in the console. It uses the setInterval function to decrement the seconds variable and display the remaining time.

13. Getting the Current Date in ISO Format

javascript
const currentDateISO = () => new Date().toISOString();

If you need the current date and time in ISO format, this one-liner provides it. It uses the toISOString method of the Date object.

14. Checking if a Variable is Undefined or Null

javascript
const isNullOrUndefined = value => value === undefined || value === null;

This one-liner helps you check if a variable is either undefined or null. It returns true if the variable matches either condition.

15. Repeating a String

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

To repeat a string a certain number of times, you can use the repeat method with this one-liner. It simplifies the process of creating repeated strings.

16. Finding the Intersection of Two Arrays

javascript
const intersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));

When you need to find the common elements between two arrays, this one-liner does the job. It uses the filter method to keep only the elements that exist in both arrays.

17. Capitalizing the First Letter of a String

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

This one-liner capitalizes the first letter of a string. It’s handy when you want to format names or titles in a consistent way.

18. Checking if a Number is Prime

javascript
const isPrime = num => {
for (let i = 2, sqrt = Math.sqrt(num); i <= sqrt; i++) {
if (num % i === 0) return false;
}
return num > 1;
};

Determining if a number is prime is a common mathematical task. This one-liner checks for prime numbers efficiently by iterating up to the square root of the number.

19. Finding the Factorial of a Number

javascript
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);

This one-liner calculates the factorial of a number using recursion. It’s a concise way to solve this classic mathematical problem.

20. Getting the Average of Numbers in an Array

javascript
const average = arr => arr.reduce((total, current) => total + current, 0) / arr.length;

To find the average of numbers in an array, this one-liner combines the reduce method with simple division to calculate the mean.

21. Finding the Longest Word in a Sentence

javascript
const longestWord = sentence => sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest, '');

When you have a sentence and want to find the longest word in it, this one-liner comes in handy. It splits the sentence into words and finds the longest one using the reduce method.

22. Checking if a String Contains a Substring

javascript
const containsSubstring = (str, sub) => str.includes(sub);

This one-liner checks if a string contains a specific substring. It’s a quick way to perform substring searches in JavaScript.

23. Converting a String to Title Case

javascript
const toTitleCase = str => str.toLowerCase().replace(/(?:^|\s)\w/g, match => match.toUpperCase());

Converting a string to title case (where the first letter of each word is capitalized) is a common text formatting task. This one-liner does it using regular expressions and string manipulation.

24. Getting the Last Element of an Array

javascript
const lastElement = arr => arr[arr.length - 1];

If you need to access the last element of an array, this one-liner provides a straightforward solution. It uses the length of the array to access the last element.

25. Parsing Query Parameters from a URL

javascript
const parseQueryParams = url => {
const params = {};
new URL(url).searchParams.forEach((value, key) => {
params[key] = value;
});
return params;
};

When you have a URL with query parameters and want to extract them as key-value pairs, this one-liner is your friend. It uses the URL object to parse the URL and retrieve the parameters.

26. Generating a Range of Numbers

javascript
const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => start + i);

Creating an array containing a range of numbers is a common task in many programming scenarios. This one-liner generates an array of numbers starting from start and ending at end.

27. Calculating the Fibonacci Sequence

javascript
const fibonacci = n => Array.from({ length: n }, (_, i, arr) => i > 1 ? arr[i - 1] + arr[i - 2] : i);

The Fibonacci sequence is a classic mathematical concept. This one-liner generates the first n Fibonacci numbers using a concise approach.

28. Checking for Anagrams

javascript
const isAnagram = (str1, str2) => str1.split('').sort().join('') === str2.split('').sort().join('');

To determine if two strings are anagrams (they can be rearranged to form each other), this one-liner sorts both strings and compares them.

29. Finding the Unique Values in an Array

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

When you want to find the unique values in an array without duplicates, this one-liner is your go-to solution. It leverages the Set object and array spreading.

30. Checking if a Year is a Leap Year

javascript
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;

Determining if a year is a leap year is a common programming task. This one-liner checks the conditions that define leap years.

31. Converting Fahrenheit to Celsius

javascript
const fahrenheitToCelsius = fahrenheit => (fahrenheit - 32) * 5 / 9;

If you need to convert temperatures from Fahrenheit to Celsius, this one-liner provides the formula for the conversion.

32. Checking if a Number is a Perfect Square

javascript
const isPerfectSquare = num => Math.sqrt(num) % 1 === 0;

This one-liner checks if a number is a perfect square by calculating its square root and checking if it’s an integer.

33. Generating a UUID (Universally Unique Identifier)

javascript
const generateUUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};

Creating a UUID, a unique identifier, is essential in many applications. This one-liner generates a version 4 UUID following the UUID specification.

34. Counting Occurrences of Elements in an Array

javascript
const countOccurrences = (arr, element) => arr.reduce((count, value) => value === element ? count + 1 : count, 0);

Counting the occurrences of a specific element in an array can be achieved with this one-liner. It uses the reduce method to tally the count.

35. Getting the Current Time in 24-Hour Format

javascript
const currentTime24h = () => new Date().toLocaleTimeString('en-US', { hour12: false });

For obtaining the current time in 24-hour format, this one-liner uses the toLocaleTimeString method with options to disable the 12-hour format.

36. Checking if a Year is a Leap Year

javascript
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;

Determining if a year is a leap year is a common programming task. This one-liner checks the conditions that define leap years.

37. Generating a UUID (Universally Unique Identifier)

javascript
const generateUUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};

Creating a UUID, a unique identifier, is essential in many applications. This one-liner generates a version 4 UUID following the UUID specification.

38. Counting Occurrences of Elements in an Array

javascript
const countOccurrences = (arr, element) => arr.reduce((count, value) => value === element ? count + 1 : count, 0);

Counting the occurrences of a specific element in an array can be achieved with this one-liner. It uses the reduce method to tally the count.

39. Getting the Current Time in 24-Hour Format

javascript
const currentTime24h = () => new Date().toLocaleTimeString('en-US', { hour12: false });

For obtaining the current time in 24-hour format, this one-liner uses the toLocaleTimeString method with options to disable the 12-hour format.

40. Trimming Whitespace from the Beginning and End of a String

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

This one-liner removes leading and trailing whitespace from a string, making it useful for cleaning user inputs.

41. Reversing the Words in a Sentence

javascript
const reverseWords = sentence => sentence.split(' ').reverse().join(' ');

To reverse the order of words in a sentence, this one-liner splits the sentence into words, reverses their order, and then joins them back together.

42. Generating a Random Hex Color Code

javascript
const randomHexColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;

When you need a random hexadecimal color code, this one-liner generates one using a combination of Math.random and toString(16).

43. Removing Falsy Values from an Array

javascript
const removeFalsyValues = arr => arr.filter(Boolean);

If you want to filter out falsy values (such as null, undefined, false, 0, and empty strings) from an array, this one-liner uses the filter method with the Boolean function as the callback.

44. Generating an Array of Unique Random Numbers

javascript
const uniqueRandomNumbers = (min, max, count) => {
if (count > max - min + 1) throw new Error('Cannot generate unique numbers with this range and count.');
const numbers = new Set();
while (numbers.size < count) {
numbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
}
return Array.from(numbers);
};

When you need an array of unique random numbers within a specified range, this one-liner generates them while ensuring uniqueness.

45. Capitalizing Every Word in a Sentence

javascript
const capitalizeWords = sentence => sentence.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

To capitalize the first letter of every word in a sentence, this one-liner splits the sentence into words, capitalizes the first letter of each word, and then joins them back together.

46. Checking if an Array Contains Only Unique Values

javascript
const hasUniqueValues = arr => new Set(arr).size === arr.length;

If you want to determine whether an array contains only unique values, this one-liner uses a Set to remove duplicates and then compares the length to the original array.

47. Getting the Current Year

javascript
const currentYear = () => new Date().getFullYear();

For obtaining the current year, this one-liner uses the getFullYear method of the Date object.

48. Creating a Range of Dates

javascript
const dateRange = (startDate, endDate) => {
const dates = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};

When you need to generate a range of dates between two given dates, this one-liner creates an array of dates within the specified range.

49. Getting the Number of Days Between Two Dates

javascript
const daysBetweenDates = (date1, date2) => Math.floor(Math.abs(date2 - date1) / (24 * 60 * 60 * 1000));

Calculating the number of days between two dates is simplified with this one-liner. It subtracts the two dates, converts the difference to milliseconds, and then calculates the days.

50. Checking if a String Contains Only Numbers

javascript
const containsOnlyNumbers = str => /^\d+$/.test(str);

To check if a string contains only numeric characters, this one-liner uses a regular expression to validate the string.

51. Finding the Median of an Array

javascript
const median = arr => {
const sorted = [...arr].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
};

This one-liner calculates the median of an array of numbers. It first sorts the array and then determines whether to take the middle value or the average of the two middle values.

52. Checking if a String Is a Palindrome (Case-Insensitive)

javascript
const isPalindromeIgnoreCase = str => {
const cleanedStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleanedStr === cleanedStr.split('').reverse().join('');
};

This one-liner checks if a string is a palindrome while ignoring case and non-alphanumeric characters. It cleans the string, converts it to lowercase, and then performs the palindrome check.

53. Finding the Mode (Most Frequent Element) in an Array

javascript
const mode = arr => {
const frequencyMap = new Map();
arr.forEach(item => {
frequencyMap.set(item, (frequencyMap.get(item) || 0) + 1);
});
let maxFrequency = 0;
let modeValue = null;
frequencyMap.forEach((frequency, value) => {
if (frequency > maxFrequency) {
maxFrequency = frequency;
modeValue = value;
}
});
return modeValue;
};

When you need to find the mode (the most frequently occurring element) in an array, this one-liner constructs a frequency map and identifies the mode value.

54. Getting the Nth Element from the End of an Array

javascript
const nthFromEnd = (arr, n) => arr[arr.length - n];

To retrieve the Nth element from the end of an array, this one-liner uses the array’s length property.

55. Calculating the Distance Between Two Coordinates (Haversine Formula)

javascript
const haversineDistance = (lat1, lon1, lat2, lon2) => {
const toRadians = deg => deg * (Math.PI / 180);
const earthRadius = 6371; // Radius of the Earth in kilometers
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return earthRadius * c;
};

Calculating the distance between two coordinates on the Earth’s surface is a common task in location-based applications. This one-liner uses the Haversine formula to compute the distance.

56. Converting an RGB Color to Hexadecimal

javascript
const rgbToHex = (r, g, b) => `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;

When you need to convert RGB values to a hexadecimal color code, this one-liner does the conversion and ensures that each component is represented by at least two characters.

57. Calculating the Factorial of a Number (Iterative)

javascript
const factorialIterative = n => {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
};

This one-liner calculates the factorial of a number using an iterative approach, which can be more efficient for large numbers compared to the recursive approach.

58. Getting the Largest Even and Odd Numbers in an Array

javascript
const largestEvenOdd = arr => {
const evens = arr.filter(num => num % 2 === 0);
const odds = arr.filter(num => num % 2 !== 0);
return {
largestEven: Math.max(...evens),
largestOdd: Math.max(...odds),
};
};

When you need to find the largest even and odd numbers in an array, this one-liner filters the array and then uses Math.max to find the largest even and odd values.

59. Checking if an Array is Sorted

javascript
const isSorted = arr => arr.every((value, index, array) => index === 0 || value >= array[index - 1]);

This one-liner checks if an array is sorted in ascending order. It uses the every method to ensure that each element is greater than or equal to the previous element.

60. Reversing the Case of Letters in a String

javascript
const reverseCase = str => str.replace(/[a-zA-Z]/g, char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase());

To reverse the case (change uppercase letters to lowercase and vice versa) of letters in a string, this one-liner uses regular expressions and string manipulation.

61. Checking if an Array Contains Consecutive Numbers

javascript
const containsConsecutiveNumbers = arr => {
const sorted = [...arr].sort((a, b) => a - b);
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] !== sorted[i - 1] + 1) {
return false;
}
}
return true;
};

This one-liner checks if an array contains consecutive numbers. It first sorts the array and then verifies that each element is one greater than the previous element.

62. Truncating a String

javascript
const truncateString = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;

When you want to truncate a string to a specified maximum length and add an ellipsis (...) if necessary, this one-liner does the job.

63. Checking if Two Strings Are Anagrams (Case-Insensitive)

javascript
const areAnagramsIgnoreCase = (str1, str2) => {
const cleanStr1 = str1.replace(/[^a-zA-Z]/g, '').toLowerCase();
const cleanStr2 = str2.replace(/[^a-zA-Z]/g, '').toLowerCase();
return cleanStr1.split('').sort().join('') === cleanStr2.split('').sort().join('');
};

This one-liner checks if two strings are anagrams while ignoring case and non-alphabetic characters. It cleans and compares the strings similarly to a previous example.

64. Generating a Range of Dates with Custom Step

javascript
const dateRangeWithStep = (startDate, endDate, stepInDays) => {
const dates = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + stepInDays);
}
return dates;
};

When you need to generate a range of dates with a custom step between them, this one-liner allows you to specify the step in days.

65. Calculating the Distance Between Two Coordinates (Vincenty Formula)

javascript
const vincentyDistance = (lat1, lon1, lat2, lon2) => {
const toRadians = deg => deg * (Math.PI / 180);
const a = 6378137; // Equatorial radius of the Earth in meters
const f = 1 / 298.257223563; // Flattening factor
const b = (1 - f) * a; // Polar radius of the Earth in meters
const L = toRadians(lon2 – lon1);
const U1 = Math.atan((1 – f) * Math.tan(toRadians(lat1)));
const U2 = Math.atan((1 – f) * Math.tan(toRadians(lat2)));
const sinU1 = Math.sin(U1);
const cosU1 = Math.cos(U1);
const sinU2 = Math.sin(U2);
const cosU2 = Math.cos(U2);let lambda = L;
let lambdaP;
let iterLimit = 100;
let sinLambda, cosLambda, sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM, C;do {
sinLambda = Math.sin(lambda);
cosLambda = Math.cos(lambda);
sinSigma = Math.sqrt((cosU2 * sinLambda) ** 2 + (cosU1 * sinU2 – sinU1 * cosU2 * cosLambda) ** 2);
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
sigma = Math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
cosSqAlpha = 1 – sinAlpha ** 2;
cos2SigmaM = cosSigma – 2 * sinU1 * sinU2 / cosSqAlpha;
C = f / 16 * cosSqAlpha * (4 + f * (43 * cosSqAlpha));
lambdaP = lambda;
lambda = L + (1 – C) * f * sinAlpha *
(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2)));
} while (Math.abs(lambda – lambdaP) > 1e-12 && –iterLimit > 0);if (iterLimit === 0) {
throw new Error(‘Vincenty formula failed to converge’);
}const uSq = cosSqAlpha * ((a ** 2 – b ** 2) / (b ** 2));
const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320175 * uSq)));
const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (7447 * uSq)));
const deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM ** 2) –
B / 6 * cos2SigmaM * (-3 + 4 * sinSigma ** 2) * (-3 + 4 * cos2SigmaM ** 2)));const s = b * A * (sigma – deltaSigma);return s;
};

If you need to calculate the distance between two coordinates on the Earth’s surface with high accuracy, this one-liner uses the Vincenty formula, which is more complex but provides precise results over a wide range of distances.

Conclusion

JavaScript one-liners are powerful tools that can streamline your coding tasks and make your code more concise and readable. These examples demonstrate the versatility and elegance of JavaScript, showcasing how you can perform a wide range of operations with minimal code. By mastering these one-liners and understanding the principles behind them, you’ll become a more efficient and effective JavaScript developer. So, go ahead, explore these one-liners, and incorporate them into your coding arsenal to take your JavaScript skills to the next level. Happy coding!