40+ Killer JavaScript One Liners 🔥
Tags: javascript, programming, productivity, webdev
Published: 2022-02-15 12:54:31

## 👋 Hey Everyone! Comment your Best One-liner JS code. 🙏
-----

[1. Get a random boolean]
> This function will return a boolean (true or false) using Math.random() method. It’s a 50/50 chance to get either true or false.

```js
const RandomBoolean = () => Math.random() >= 0.5;
```

[02. Check if the provided date is a weekday or Weekend]

```js
const isWeekend = date => [0, 6].indexOf(date.getDay()) !== -1;
```

[03. Check if a number is even or odd]

```js
const isEven = num => num % 2 === 0;
// OR
const isEven = (n) => !(n & 1);
```

[04. Remove all duplicate values in an array]

```js
const setArr = arr => [...new Set(arr)];
```

[05. Check if a variable is an array]
> A clean and easy way to check if a variable is an array.

```js
const isArray = (arr) => Array.isArray(arr);
```

[06. Generate a random number between two numbers]
> This will take two numbers as params and will generate a random number between those two numbers!

```js
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(55, 999));
```

[07. Generate a random string (unique id?)]
```js
const randomString = () => Math.random().toString(36).slice(2);
```

[08. Swapping Two Variables || Destructuring]
> Destructuring assignment that swaps the variables values
```js
let foo = '🥳';
let bar = '🥶';
[foo, bar] = [bar, foo];
```

[09. Calculate number of days between two dates]
> To calculate the days between two dates, we first find the absolute between two dates and then divide it with 24 * 60 * 60 * 1000 = 86400000 which is equal to milliseconds in a single day, and at the end, we round the result and return it.

```js
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
```

> 🔥 You can use Math.round or Math.floor instead of Math.ceil.

[10. Different ways of merging multiple arrays]

```js
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];

// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
```

[11. Get the actual type of javascript primitives]

```js
const trueType = obj => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
```

[12. Truncate]

```js
// string at the end
const truncateString = (string, length) => {
  return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};

// string from the middle
const truncateStringMiddle = (string, length, start, end) => {
  return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};

// A number to a fixed decimal point
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
```

[13. Capitalizing a string]

```js
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
// OR capitalize all starting words in a sentence
const capitalize = (str, lower = false) =>
  (lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, match => match.toUpperCase());
```

[14. Check if the current tab is in view/focus]
> This simple helper method returns true or false depending on if a tab is in view/focus

```js
const isTabInView = () => document.hidden;
isTabInView(); // true/false
// OR
document.hidden ? 'hidden' : 'visible';
```

[15. Reverse a string]

```js
const reverse = str => str.split('').reverse().join('');
// OR
const reverse = str => [...str].reverse().join``
```

[16. Check if an element is currently in focus]
> We can check if an element is currently in focus using the document.activeElement property.

```js
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
```

[17. Check if the current user has touch events supported]

```js
const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
```

[18. Scroll to top of the page]

```js
const goToTop = () => window.scrollTo(0, 0, 'smooth');
goToTop();
// OR
const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" });
// Scroll to bottom of the page
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight)
```

[19. Get average value of arguments]
> We can use the reduce method to get the average value of the arguments.

```js
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
```

[20. Convert Fahrenheit / Celsius]

> Dealing with temperatures can be confusing at times. These 2 functions will help you convert Fahrenheit to Celsius and the other way around.

```js
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
```

[21. Get query parameters from the URL]
> To obtain query parameters, we must first divide the URL at “?” and then replace “=” with “:” and **“&” **with “,”.

```js
const getQueryParams = URL =>
  JSON.parse('{"' + decodeURI(URL.split('?')[1]).replace(/&/g, '","').replace(/=/g, '":"') + '"}');

getQueryParams('https://www.com?search=api&test=true')
// {search: 'api', test: 'true'}
```

[22. Clipboard API]
To copy a text, we can use JavaScript navigator.

```js
const copy = (text) => navigator.clipboard.writeText(text);
```
To paste text:

```js
const text = navigator.clipboard.readText();
```

[23. Get Value of a brower Cookie]
Retrieve the value of a cookie by accessing with document.cookie
```js
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"
```

[24. Check if Date is Valid]

```js
const isDateValid = (...val) => !Number.isNaN(+new Date(...val));

isDateValid("Feburary 10, 2022 09:19:00");
```

[25. Find which is the day by a given date in year.]
```js
const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // Result: 272
```

[26. Clear All Cookies]
> You can easily clear all cookies stored in a web page by accessing the cookie using document.cookie and clearing it.

```js
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
```

[27. Check if array is empty && Object Is Empty]
```js
const isNotEmpty = arr => arr?.some(x => x);
// OR
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

// Object Is Empty
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
```

[28. Get Selected Text]
> Get the text the user has select using inbuilt getSelection property.
```js
const getSelectedText = () => window.getSelection().toString();
```

[29. Detect Dark Mode]
```js
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
```

[30. Shuffle an Array]
Shuffling an array is super easy with sort and random methods.
```js
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
```

[31. Generate Random Hex]

```js
const randomHex = () => '#' + Math.floor(Math.random() * 16777215).toString(16);
// OR
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
```

[32. Convert RGB to Hex]
```js
const rgbToHex = (r, g, b) =>
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); // Result: #0033ff
```

[33. Get Min & max value of an array]
```js
const getMinMax = (arr) => [Math.min(...arr), Math.max(...arr)];
```

[34. Reload the current page]
```js
const reload = () => location.reload();

// Or
const reload = () => (location.href = location.href);
```

[35. Check if a string consists of a repeated character sequence]

```js
const consistsRepeatedSubstring = (str) => `${str}${str}`.indexOf(str, 1) !== str.length;
```

[36. Convert a letter to associate emoji]

```js
const letterToEmoji = (c) => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);
```

[37. Calculate the angle of a line defined by two points]

```js
// In radians
const radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x);

// In degrees
const degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
```

[38. Convert radians to degrees && degrees to radians]

```js
const radsToDegs = (rad) => (rad * 180) / Math.PI;
// &&
const degsToRads = (deg) => (deg * Math.PI) / 180.0;
```

[39. Wait for an amount of time]

```js
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
```

[40. Create an object from the pairs of key and value]

```js
const toObj = (arr) => Object.fromEntries(arr);
```

[41. Get union of arrays]

```js
const union = (...arr) => [...new Set(arr.flat())];
```

[42. Partition an array based on a condition]

```js
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);

partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]
```

[43. Remove falsy values from array]

```js
const removeFalsy = (arr) => arr.filter(Boolean);
```

*That’s all Aliens! 👽 
Hope you found this helpful, see you in the next one 😉*