40+ Killer JavaScript One Liners 🔥

👋 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.

const RandomBoolean = …


This content originally appeared on DEV Community and was authored by Dreamy Developer

👋 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.

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

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

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

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

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

[04. Remove all duplicate values in an array]

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.

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!

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

[07. Generate a random string (unique id?)]

const randomString = () => Math.random().toString(36).slice(2);

[08. Swapping Two Variables || Destructuring]

Destructuring assignment that swaps the variables values

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.

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]

// 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]

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

[12. Truncate]

// 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]

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

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

[15. Reverse a string]

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.

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

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

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

[18. Scroll to top of the page]

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.

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.

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 “,”.

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.

const copy = (text) => navigator.clipboard.writeText(text);

To paste text:

const text = navigator.clipboard.readText();

[23. Get Value of a brower Cookie]
Retrieve the value of a cookie by accessing with document.cookie

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

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

[24. Check if Date is Valid]

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.]

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.

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]

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.

const getSelectedText = () => window.getSelection().toString();

[29. Detect Dark Mode]

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.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

[31. Generate Random Hex]

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]

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]

const getMinMax = (arr) => [Math.min(...arr), Math.max(...arr)];

[34. Reload the current page]

const reload = () => location.reload();

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

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

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

[36. Convert a letter to associate emoji]

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

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

// 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]

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

[39. Wait for an amount of time]

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

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

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

[41. Get union of arrays]

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

[42. Partition an array based on a condition]

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]

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

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


This content originally appeared on DEV Community and was authored by Dreamy Developer


Print Share Comment Cite Upload Translate Updates
APA

Dreamy Developer | Sciencx (2022-02-15T12:54:31+00:00) 40+ Killer JavaScript One Liners 🔥. Retrieved from https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/

MLA
" » 40+ Killer JavaScript One Liners 🔥." Dreamy Developer | Sciencx - Tuesday February 15, 2022, https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/
HARVARD
Dreamy Developer | Sciencx Tuesday February 15, 2022 » 40+ Killer JavaScript One Liners 🔥., viewed ,<https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/>
VANCOUVER
Dreamy Developer | Sciencx - » 40+ Killer JavaScript One Liners 🔥. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/
CHICAGO
" » 40+ Killer JavaScript One Liners 🔥." Dreamy Developer | Sciencx - Accessed . https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/
IEEE
" » 40+ Killer JavaScript One Liners 🔥." Dreamy Developer | Sciencx [Online]. Available: https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/. [Accessed: ]
rf:citation
» 40+ Killer JavaScript One Liners 🔥 | Dreamy Developer | Sciencx | https://www.scien.cx/2022/02/15/40-killer-javascript-one-liners-%f0%9f%94%a5/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.