DEV Community

Cover image for 40+ Killer JavaScript One Liners πŸ”₯
Dreamy Developer
Dreamy Developer

Posted on

7 3

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 = () => Math.random() >= 0.5;
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

[04. Remove all duplicate values in an array]

const setArr = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

[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);
Enter fullscreen mode Exit fullscreen mode

[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));
Enter fullscreen mode Exit fullscreen mode

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

const randomString = () => Math.random().toString(36).slice(2);
Enter fullscreen mode Exit fullscreen mode

[08. Swapping Two Variables || Destructuring]

Destructuring assignment that swaps the variables values

let foo = 'πŸ₯³';
let bar = 'πŸ₯Ά';
[foo, bar] = [bar, foo];
Enter fullscreen mode Exit fullscreen mode

[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);
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ 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])];
Enter fullscreen mode Exit fullscreen mode

[11. Get the actual type of javascript primitives]

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

[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);
Enter fullscreen mode Exit fullscreen mode

[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());
Enter fullscreen mode Exit fullscreen mode

[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';
Enter fullscreen mode Exit fullscreen mode

[15. Reverse a string]

const reverse = str => str.split('').reverse().join('');
// OR
const reverse = str => [...str].reverse().join``
Enter fullscreen mode Exit fullscreen mode

[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)
Enter fullscreen mode Exit fullscreen mode

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

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

[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)
Enter fullscreen mode Exit fullscreen mode

[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);
Enter fullscreen mode Exit fullscreen mode

[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;
Enter fullscreen mode Exit fullscreen mode

[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'}
Enter fullscreen mode Exit fullscreen mode

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

const copy = (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

To paste text:

const text = navigator.clipboard.readText();
Enter fullscreen mode Exit fullscreen mode

[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"
Enter fullscreen mode Exit fullscreen mode

[24. Check if Date is Valid]

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

isDateValid("Feburary 10, 2022 09:19:00");
Enter fullscreen mode Exit fullscreen mode

[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
Enter fullscreen mode Exit fullscreen mode

[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=/`));
Enter fullscreen mode Exit fullscreen mode

[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
Enter fullscreen mode Exit fullscreen mode

[28. Get Selected Text]

Get the text the user has select using inbuilt getSelection property.

const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

[29. Detect Dark Mode]

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
Enter fullscreen mode Exit fullscreen mode

[30. Shuffle an Array]
Shuffling an array is super easy with sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
Enter fullscreen mode Exit fullscreen mode

[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")}`;
Enter fullscreen mode Exit fullscreen mode

[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
Enter fullscreen mode Exit fullscreen mode

[33. Get Min & max value of an array]

const getMinMax = (arr) => [Math.min(...arr), Math.max(...arr)];
Enter fullscreen mode Exit fullscreen mode

[34. Reload the current page]

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

// Or
const reload = () => (location.href = location.href);
Enter fullscreen mode Exit fullscreen mode

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

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

[36. Convert a letter to associate emoji]

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

[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;
Enter fullscreen mode Exit fullscreen mode

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

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

[39. Wait for an amount of time]

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
Enter fullscreen mode Exit fullscreen mode

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

const toObj = (arr) => Object.fromEntries(arr);
Enter fullscreen mode Exit fullscreen mode

[41. Get union of arrays]

const union = (...arr) => [...new Set(arr.flat())];
Enter fullscreen mode Exit fullscreen mode

[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]]
Enter fullscreen mode Exit fullscreen mode

[43. Remove falsy values from array]

const removeFalsy = (arr) => arr.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

That’s all Aliens! πŸ‘½
Hope you found this helpful, see you in the next one πŸ˜‰

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
jacksonkasi profile image
Jackson Kasi β€’

wow, it's really help for meπŸ‘πŸ‘πŸ‘πŸ”₯

Collapse
 
manuartero profile image
Manuel Artero Anguita 🟨 β€’ β€’ Edited

Truly liked this one!! :)

--
Since there are a couple of random related I need to do some self-promotion πŸ™‡ @manutero/randomjs

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️