13 JavaScript one-liners that will make you look like an expert

13 JavaScript one-liners that will make you look like an expert

1. Get a random Boolean value ( true / false )

This function uses the Math.random() method and returns a boolean value ( true or alse ). Math.random creates a random number between 0 and 1, and we just check if it is above or below 0.5, which gives us a 50% chance of getting true or false.

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());

2. Check if the provided date is a working day

Using this method, we can check whether the date provided in the function is a weekday or a weekend day.

const isWeekday = (date) => date.getDay() % 6 !== 0;

console.log(isWeekday(new Date(2021, 7, 6)));
// true because it is Fridayconsole.log(isWeekday(new Date(2021, 7, 7)));
// false because it is Saturday

3. Reverse a string

There are several different ways to reverse a string. This is the simplest one, using the split(), reverse(), and join() methods.

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// 'dlrow olleh'

4. Check if the current tab is hidden

Document.hidden (read-only property) returns a Boolean value indicating whether the page is hidden ( true ) or not ( false ).

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();

Off-site: I accidentally discovered that the iQiyi advertising playback time will only count down when the current tab is activated. When you leave the current tab, the countdown stops. I searched on Baidu and found this thing document.hidden .

document.hidden is a new API added to h5, which has compatibility issues when used.

var hidden
if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
}
console.log("Is the current page hidden: " + document[hidden])

5. Check if a number is even or odd

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// true
console.log(isEven(3));
// false

6. Get the time from a date

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// "17:30:00"

console.log(timeFromDate(new Date()));
// Print the current time

7. Keep n decimal places

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Example toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726

8. Check if an element is currently in focus

We can check whether an element is currently focused using the document.activeElement property.

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Returns true if in focus, false if not in focus

9. Check if the current browser supports touch events

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// If touch events are supported, true will be returned, otherwise false will be returned.

10. Check if the current browser is on an Apple device

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);

11. Scroll to the top of the page

const goToTop = () => window.scrollTo(0, 0);
goToTop();

12. Get the average value of the parameter

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

13. Fahrenheit/Celsius conversion

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Example celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0

This concludes our article on 13 JavaScript one-line programs that will make you look like an expert. For more JavaScript content, please search 123WORDPRESS.COM’s previous articles or continue browsing the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of custom swiper component in JavaScript
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • Implementing carousel effects with JavaScript
  • javascript to switch pictures by clicking a button
  • Summary of various methods for JavaScript to determine whether it is an array
  • JavaScript to achieve fireworks effects (object-oriented)
  • JavaScript Canvas implements Tic-Tac-Toe game
  • Detailed discussion of the differences between loops in JavaScript
  • Summary of several common ways to abbreviate javascript code

<<:  MySQL 8.0.19 installation and configuration tutorial under Windows 10

>>:  Summary of solutions for MySQL not supporting group by

Recommend

HTML pop-up div is very useful to realize mobile centering

Copy code The code is as follows: <!DOCTYPE ht...

Vue implements an Input component that gets the key display shortcut key effect

I encountered a requirement to customize shortcut...

CSS: visited pseudo-class selector secret memories

Yesterday I wanted to use a:visited to change the...

HTML Basics_General Tags, Common Tags and Tables

Part 1 HTML <html> -- start tag <head>...

General Guide to Linux/CentOS Server Security Configuration

Linux is an open system. Many ready-made programs...

How to install Oracle_11g using Docker

Install Oracle_11g with Docker 1. Pull the oracle...

Native JS to achieve special effects message box

This article shares with you a special effect mes...

HTML table tag tutorial (35): cross-column attribute COLSPAN

In a complex table structure, some cells span mul...

Detailed explanation of MySQL deadlock and database and table sharding issues

Record the problem points of MySQL production. Bu...

vue_drf implements SMS verification code

Table of contents 1. Demand 1. Demand 2. SDK para...

The implementation of Youda's new petite-vue

Table of contents Preface Introduction Live Easy ...

ElementUI implements sample code for drop-down options and multiple-select boxes

Table of contents Drop-down multiple-select box U...

Vue image cropping component example code

Example: tip: This component is based on vue-crop...