JavaScript is a versatile language with a lot of powerful features. Sometimes, the simplest solutions can be the most effective. Here are 10 JavaScript one-liners that can make your coding life easier and more efficient.
1. Swapping Two Variables
Swapping values between two variables is a common task. Instead of using a temporary variable, you can do it in one line with destructuring assignment.
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 5
2. Checking if a Number is Even or Odd
You can check if a number is even or odd using the modulus operator.
const isEven = num => num % 2 === 0;
console.log(isEven(4)); // true
console.log(isEven(7)); // false
3. Generating a Random Number in a Range
Generating a random number within a specific range can be done in one line.
const randomInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInRange(1, 10)); // e.g., 5
4. Removing Duplicates from an Array
Use the Set
object to remove duplicates from an array.
const removeDuplicates = arr => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]
5. Flattening an Array
Flatten a nested array using the flat
method.
const flattenArray = arr => arr.flat(Infinity);
console.log(flattenArray([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
6. Checking if an Element Exists in an Array
Use the includes
method to check if an element exists in an array.
const existsInArray = (arr, element) => arr.includes(element);
console.log(existsInArray([1, 2, 3], 2)); // true
console.log(existsInArray([1, 2, 3], 4)); // false
7. Converting an Array to a String
Convert an array to a string using the join
method.
const arrayToString = arr => arr.join('');
console.log(arrayToString(['H', 'e', 'l', 'l', 'o'])); // "Hello"
8. Reversing a String
Reverse a string using the split
, reverse
, and join
methods.
const reverseString = str => str.split('').reverse().join('');
console.log(reverseString('hello')); // "olleh"
9. Getting the Current Date in YYYY-MM-DD Format
Format the current date as YYYY-MM-DD
.
const getCurrentDate = () => new Date().toISOString().split('T')[0];
console.log(getCurrentDate()); // e.g., "2023-10-01"
10. Capitalizing the First Letter of a String
Capitalize the first letter of a string.
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalizeFirstLetter('hello')); // "Hello"
Conclusion
These one-liners can save you time and make your code more concise. Whether you're swapping variables, checking for even numbers, or formatting dates, these snippets can be a handy addition to your JavaScript toolkit. Happy coding!
Top comments (1)
One more of those.
Several "utilities" are effectively renames of something else. flattenArray -> array.flat(). Same thing, zero gain, and the cherry on top: You use more RAM.
Then the eternal problem of people thinking things are magical:
str.spit('').reverse().join('')
. This creates an array (wasted RAM), then runs a loop, then runs another loop. This is a good candidate for the least performer of the year.Now that's a much better "utility".