Hi guys, in this post, I'm going to introduce JavaScript one liners that make you better JavaScript developer as they are very useful in most practical cases
1. Reverse a string
const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello guys!"));
// !syug olleh
2. Flatten an array
const flattenArray = (arr, flattenLevel = 1) => arr.flat(flattenLevel);
console.log(flattenArray([1, 2, [3, 4]]));
// [1,2,3,4]
console.log(flattenArray([1, 2, [3, 4, [5]]], 2));
// [1,2,3,4, 5]
3. Shuffle an array
const shuffleArray = (arr) => arr.sort((a, b) => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4, 5]));
// [2, 5, 4, 1, 3]
4. Get a random boolean value
const getRandomBooleanValue = () => Math.random() >= 0.5;
console.log(getRandomBooleanValue());
// false
console.log(getRandomBooleanValue());
// true
5. Find an average array value
const getAverageValue = (numbers) =>
numbers.reduce((total, currEl) => total + currEl, 0) / numbers.length;
console.log(getAverageValue([1, 2, 3, 4]));
// 2.5
console.log(getAverageValue([100, 900]));
// 500
6. Detect a dark mode
const darkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
7. Scroll to the top of the page
const scrollToTop =() => window.scrollTo({top: 0, behavior: 'smooth'});
8. Find number of specified character in a string
const getCharAmount = (string, char) => string.split(char).length - 1;
console.log(getCharAmount("hello", "l"));
// 2
console.log(getCharAmount("hello", "q"));
// 0
9. Redirect URL
const redirectUrl = url => location.href = url;
redirectUrl("https://youtube.com");
10. Detect whether an array is empty
const isArrayEmpty = (arr) => !Array.isArray(arr) || !arr.length;
console.log(isArrayEmpty([1, 2]));
// false
console.log(isArrayEmpty([]));
// true
11. Return unique values from an array
const getUniqueArrayValues = (arr) =>
arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
console.log(getUniqueArrayValues([1, 2, 2, 3]));
// [1, 2, 3]
12. Get a selected text from DOM
const getSelectedText = () => window.getSelection().toString();
13. Check whether expression is an array
const isArray = (expression) => Array.isArray(expression);
console.log(isArray(1));
// false
console.log(isArray({ name: "Jaxongir" }));
// false
console.log(isArray(["JavaScript"]));
// false
14. Check a number if it's odd or even
const isOdd = (number) => number % 2 === 1;
console.log(isOdd(1));
// true
console.log(isOdd(2));
// false
15. Detect whether an element is in focus
const isElementFocussed = (element) => element === document.activeElement;
16. Convert celsius to fahrenheit and vice versa
const convertCelsiusToFahrenheit = (celsius) =>
Math.floor((celsius * 9) / 5 + 32);
const convertFahrenheitToCelsius = (fahrenheit) =>
Math.floor((fahrenheit - 32) * (5 / 9));
console.log(convertCelsiusToFahrenheit(21));
// 69
console.log(convertCelsiusToFahrenheit(-50));
// -58
console.log(convertFahrenheitToCelsius(33));
// 0
console.log(convertFahrenheitToCelsius(22));
// -6
17. Check if two arrays are the same
const isArraysTheSame = (arr1, arr2) =>
arr1.length === arr2.length &&
arr1.every((val, index) => val === arr2[index]);
console.log(isArraysTheSame([1, 2], [1, 2]));
// true
console.log(isArraysTheSame([1, 2], [1, 3]));
// false
18. Convert first character to an uppercase
const convertFirstCharToUppercase = (str) =>
`${str[0].toUpperCase()}${str.slice(1)}`;
console.log(convertFirstCharToUppercase("jaxongir"));
// Jaxongir
19. Converting 24-hour clock to 12-hour clock
const convert24hTo12h = (hour) =>
`${hour % 12 === 0 ? 12 : hour % 12}${hour > 23 || hour < 12 ? "am" : "pm"}`;
console.log(convert24hTo12h(1));
20. Replace character of string with another character
const replaceStringCharacter = (str, char) => str.replace(/e/i, char);
console.log(replaceStringCharacter("geat", "re"));
// great
21. Remove undefined or null from an array
const removeNullAndUndefined = (arr) =>
arr.filter((val) => val != null || val != undefined);
console.log(removeNullAndUndefined([1, null, undefined, 4]));
// [1, 4]
Top comments (0)