12 Javascript One liners That’ll make your life easier
Today we discuss one liners to improve productivity and skills, which we can use in our daily development life.
1. Uppercase the first character of each word in a string
This method is used to To achieve the capitalization of the first letter of each word in a string in JavaScript.
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
2. Convert a string to Camelcase
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('camel-case'); // camelCase
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld
3. Remove Duplicate from Array
By Using Set
we can easily remove duplicates in JavaScript. Its a life saver.
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
4. Check if number is even or odd
It’s very easy to find out given number is even or odd
const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false
5. Find Average of Numbers
You can find the average between multiple numbers using reduce
method.
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
6. Scroll to Top
You can use window.scrollTo(0, 0)
method to automatic scroll to top. Set both x
and y
as 0.
const goToTop = () => window.scrollTo(0, 0);
goToTop();
7. Reverse a String
You can easily reverse a string using split
, reverse
and join
methods.
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
8. Check if array is empty
Simple one liner to check if an array is empty, will return true
or false
.
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
9. Get Selected Text
Get the text the user has select using inbuilt getSelection
property.
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
10. Detect Dark Mode
Check if a user’s device is in dark mode with the following code.
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
11. Remove falsy values from array
Using this method, you will be able to filter out all falsy values in the array.
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
12. Calculate the number of different days between two dates
we can calculate the number of days between two dates with the following code.
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1")) // 90
Wrapping Up
Hope you enjoyed the article 🙌