Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer peopleโ€™s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer peopleโ€™s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 797

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T02:12:08+00:00 2024-11-25T02:12:08+00:00

40+ Killer JavaScript One Liners ๐Ÿ”ฅ

  • 62k

๐Ÿ‘‹ 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 ๐Ÿ˜‰

javascriptproductivityprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.