Home > Web Front-end > JS Tutorial > Learn these 20+ JavaScript one-liners to help you code like a pro

Learn these 20+ JavaScript one-liners to help you code like a pro

青灯夜游
Release: 2021-05-17 09:41:51
forward
2099 people have browsed it

This article introduces you to 20 JavaScript one-liners that can help you write code like a professional. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Learn these 20+ JavaScript one-liners to help you code like a pro

JavaScript continues to grow and develop,

because it is one of the easiest languages ​​to get started with, and therefore new to the market becomes a tech geek Opened the door. (Question mark face?)

Indeed, JavaScript can do many wonderful things! There is still much to learn.

And, whether you're new to JavaScript or more of a professional developer, learning something new is always a good thing.

This article has compiled some very useful one-liners (20) that can help you improve your work efficiency and help debug your code.

What is a single line of code?

One-liner is a coding practice in which we perform certain functions with only one line of code.

01 - Get a Boolean value randomly

This function will return a Boolean value (true or false) using the Math.random() method.
Math.random Create a random number between 0 and 1, then we check if it is greater or less than 0.5.
This means there is a 50/50 chance of getting it right or wrong.

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
Copy after login

02 - Check if the date is a weekend

With this feature you will be able to check if the provided date is a weekday or a weekend.

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
Copy after login

03 - Check if a number is even or odd

Simple utility function to check if a number is even or odd.

Learn these 20+ JavaScript one-liners to help you code like a pro

const isEven = (num) => num % 2 === 0;

console.log(isEven(5));
// false
console.log(isEven(4));
// true
Copy after login

04-Get unique values ​​in an array (array deduplication)

Very simple way to remove all duplicate values ​​from an array . This function converts an array to a Set and then returns an array.

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
Copy after login

05-Checking if a variable is an array

A clean and easy way to check if a variable is an array.

Of course, there can also be other methods

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
Copy after login

06-Generate a random number between two numbers

This will take two numbers as arguments 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(1, 50));
// could be anything from 1 - 50
Copy after login

07 - Generate a random string (unique ID?)

Maybe you need a temporary unique ID, here is a trick you can use on the go Generate a random string.

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(randomString());
// could be anything!!!
Copy after login

08-Scroll to the top of the page

The window.scrollTo() method puts a The X and Y coordinates scroll to.
If we set them to zero and zero, we will scroll to the top of the page.

Learn these 20+ JavaScript one-liners to help you code like a pro

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

scrollToTop();
Copy after login

09 - Switching Boolean

Switching Boolean values ​​is one of the very basic programming problems that can be solved in many different ways.
Instead of using an if statement to determine which value to set the boolean to, you can use a function! Flip the current value. non-operator.

Learn these 20+ JavaScript one-liners to help you code like a pro

// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
//or
const toggleBool = b => !b;
Copy after login

10-Swap two variables

The code below is to swap two variables without using the third variable and using only one line of code One of the simpler ways to use a variable.

Learn these 20+ JavaScript one-liners to help you code like a pro

[foo, bar] = [bar, foo];
Copy after login

11-Calculate the number of days between two dates

To calculate the number of days between two dates,
we first Find the absolute value between the two dates, then divide it by 86400000 (equal to the number of milliseconds in a day), and finally round the result and return it.

1Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
Copy after login

12 - Copy text to clipboard

PS: You may need to add a check to see if navigator.clipboard exists .writeText

1Learn these 20+ JavaScript one-liners to help you code like a pro

const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text);
};
Copy after login

13 - Different ways to merge multiple arrays

There are two ways to merge arrays. One of them is to use the concat method. The other uses the spread operator ().

PS: We can also use the "settings" object to copy anything from the final array.

1Learn these 20+ JavaScript one-liners to help you code like a pro

// 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])];
Copy after login

14-获取javascript语言的实际类型

人们有时会使用库来查找JavaScript中某些内容的实际类型,这一小技巧可以节省你的时间(和代码大小)。

1Learn these 20+ JavaScript one-liners to help you code like a pro

const trueTypeOf = (obj) => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};

console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
Copy after login

15-在结尾处截断字符串

需要从头开始截断字符串,这不是问题!

1Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(
  truncateString(&#39;Hi, I should be truncated because I am too loooong!&#39;, 36),
);
// Hi, I should be truncated because...
Copy after login

16-从中间截断字符串

从中间截断字符串怎么样?

该函数将一个字符串作为第一个参数,然后将我们需要的字符串大小作为第二个参数,然后从第3个和第4个参数开始和结束需要多少个字符

Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(
  truncateStringMiddle(
    &#39;A long story goes here but then eventually ends!&#39;, // string
    25, // 需要的字符串大小
    13, // 从原始字符串第几位开始截取
    17, // 从原始字符串第几位停止截取
  ),
);
// A long story ... eventually ends!
Copy after login

17-大写字符串

好吧,不幸的是,JavaScript没有内置函数来大写字符串,但是这种解决方法可以实现。

1Learn these 20+ JavaScript one-liners to help you code like a pro

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

console.log(capitalize(&#39;hello world&#39;));
// Hello world
Copy after login

18-检查当前选项卡是否在视图/焦点内

此简单的帮助程序方法根据选项卡是否处于视图/焦点状态而返回truefalse

1Learn these 20+ JavaScript one-liners to help you code like a pro

const isTabInView = () => !document.hidden;  // Not hidden

isTabInView();
// true/false
Copy after login

19-检查用户是否在Apple设备上

如果用户使用的是Apple设备,则返回true

1Learn these 20+ JavaScript one-liners to help you code like a pro

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

console.log(isAppleDevice);
// true/false
Copy after login

20-三元运算符

当你只想在一行中编写if..else语句时,这是一个很好的代码保护程序。

Learn these 20+ JavaScript one-liners to help you code like a pro

// Longhand
const age = 18;
let greetings;

if (age < 18) {
  greetings = &#39;You are not old enough&#39;;
} else {
  greetings = &#39;You are young!&#39;;
}

// Shorthand
const greetings = age < 18 ? &#39;You are not old enough&#39; : &#39;You are young!&#39;;
Copy after login

21-短路评估速记

在将变量值分配给另一个变量时,可能要确保源变量不为null,未定义或为空。
可以编写带有多个条件的long if语句,也可以使用短路评估。

2Learn these 20+ JavaScript one-liners to help you code like a pro

// Longhand
if (name !== null || name !== undefined || name !== &#39;&#39;) {
  let fullName = name;
}

// Shorthand
const fullName = name || &#39;buddy&#39;;
Copy after login

希望对你有所帮助!

英文原文地址:https://dev.to/ovi/20-javascript-one-liners-that-will-help-you-code-like-a-pro-4ddc

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Learn these 20+ JavaScript one-liners to help you code like a pro. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template