21 Must Have JavaScript One Liners
Published: 2022-10-31 13:53:56

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
```js
const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello guys!"));
// !syug olleh
```

# 2. Flatten an array
```js
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
```js
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
```js
const getRandomBooleanValue = () => Math.random() >= 0.5;
console.log(getRandomBooleanValue());
// false
console.log(getRandomBooleanValue());
// true
```

# 5. Find an average array value
```js
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
```js
const darkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
```

# 7. Scroll to the top of the page
```js
const scrollToTop =() => window.scrollTo({top: 0, behavior: 'smooth'});
```

# 8. Find number of specified character in a string
```js
const getCharAmount = (string, char) => string.split(char).length - 1;
console.log(getCharAmount("hello", "l"));
// 2
console.log(getCharAmount("hello", "q"));
// 0
```

# 9. Redirect URL
```js
const redirectUrl = url => location.href = url;
redirectUrl("https://youtube.com");
```

# 10. Detect whether an array is empty
```js
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
```js
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
```js
const getSelectedText = () => window.getSelection().toString();
```

# 13. Check whether expression is an array
```js
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
```js
const isOdd = (number) => number % 2 === 1;
console.log(isOdd(1));
// true
console.log(isOdd(2));
// false
```

# 15. Detect whether an element is in focus
```js
const isElementFocussed = (element) => element === document.activeElement;
```

# 16. Convert celsius to fahrenheit and vice versa
```js
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
```js
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
```js
const convertFirstCharToUppercase = (str) =>
  `${str[0].toUpperCase()}${str.slice(1)}`;
console.log(convertFirstCharToUppercase("jaxongir"));
// Jaxongir
```

# 19. Converting 24-hour clock to 12-hour clock
```js
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
```js
const replaceStringCharacter = (str, char) => str.replace(/e/i, char);
console.log(replaceStringCharacter("geat", "re"));
// great
```

# 21. Remove undefined or null from an array
```js
const removeNullAndUndefined = (arr) =>
  arr.filter((val) => val != null || val != undefined);
console.log(removeNullAndUndefined([1, null, undefined, 4]));
// [1, 4]
```