Front end utility operator, some write code operation

JavaScript Art 2021-06-17 19:25:24
end utility operator write code


Some common operators can make your front-end code more concise . This article sorts out some JS The operator used in / The operator , The goal is to simplify the code .

1、?? The operator Null merge / Empty judgment

Null merge operator , If the first parameter is not null perhaps undefined, This operator will return the first parameter , otherwise , It will return the second parameter

null ?? 3 //3
undefined ?? 3 //3
7 ?? 3 //7
2、?. The operator null Transmission symbol ( Or chain decision operator )

stay js, If you read an attribute in an object , It is often necessary to judge whether the object exists first , In case of error .

let a = (obj && obj.name) || 'default';

The above code can be used null The conduction sign is abbreviated as

let a = obj ?. name || 'default';
3、??= The operator Logical null assignment operator

This assignment operator assigns a new value only if the current value is empty or undefined .

let a = null
const b = 5
console.log(a ??= b) // => 5
console.log(a = (a ?? b)) // => 5
4、 Ternary operator

val It's true , be a Value ifTrue , Otherwise, the value is ifFalse

const a = val ? ifTrue : ifFalse
5、~~ The operator Bitwise operators

You can use a double-digit operator instead of a positive number Math.floor( ), Instead of a negative number Math.ceil( ). The advantage of the double no positioning operator is that it performs the same operation faster .

Math.floor(4.9) === 4 //true
// Shorthand for :
~~4.9 === 4 //true

But be careful , For positive numbers ~~ Operation result and Math.floor( ) The results are the same , And for negative numbers, it's the same as Math.ceil( ) The result is the same :

~~4.5 // 4
Math.floor(4.5) // 4
Math.ceil(4.5) // 5
~~-4.5 // -4
Math.floor(-4.5) // -5
Math.ceil(-4.5) // -4
6、&& And || or Short circuit operator

&& To get a false operation , Judge from left to right , If you encounter a false value , It returns a false value , No more , Otherwise return the last true value

|| To get the truth , Judge from left to right , If you come across a truth value , Return the true value , No more , Otherwise return the last false value

let param1 = expr1 && expr2
let param2 = expr1 || expr2
7、| 0 integer

To a number | 0 It can be rounded , Negative numbers also apply ,num | 0

1.3 | 0 // 1
-1.9 | 0 // -1
8、& 1 Judge odd even number

To a number & 1 We can judge odd and even numbers , Negative numbers also apply ,num & 1

const num=3;
!!(num & 1) // true
!!(num % 2) // true
9、_ Numeric separator

ES2021 The numerical separator is introduced _ , Provide separation between numerical groups , Make a long number easier to read .Chrome Support for numeric separators has been provided , You can try it in your browser .

let number = 100_0000_0000_0000 // 0 It's too much. It's too much to see without a numeric divider
console.log(number) // Output 100000000000000

Besides , The decimal part of the decimal system can also use numeric dividers , Binary system 、 You can also use numeric dividers in hexadecimal

0x11_1 === 0x111 // true Hexadecimal
0.11_1 === 0.111 // true Decimal decimal
0b11_1 === 0b111 // true Binary system
10、void Operator

void Operator Evaluate a given expression , Then return undefined

It can be used to give expressions to functions that are called immediately in use (IIFE) when , You can use void Operator let JS The engine turned one function Keywords are recognized as function expressions instead of function declarations .

function iife() { console.log('foo') }() // Report errors , because JS Engine handle IIFE Identify for function declaration
void function iife() { console.log('foo') }() // Normal call
~function iife() { console.log('foo') }() // You can also use a bit operator
(function iife() { console.log('foo') })() // Or simply use parentheses to express the whole expression

It can also be used in arrow functions to avoid value leakage , Arrow function , It is allowed to return the value directly without using brackets in the function body . This feature brings users a lot of convenience , But sometimes it brings unnecessary trouble , If a function with no return value is called on the right side , When the return value changes , Can cause unexpected side effects .

const func = () => void customMethod() // Especially when passing a function to an event or callback function

Be on the safe side , When you don't want the return value of a function to be anything but null , You should use void To make sure to return undefined, such , When customMethod When the return value changes , And it doesn't affect the behavior of the arrow function .

11、js The priority of the operator

JavaScript Operator priority , Describes the order in which operations are performed when computing expressions . Perform operations with higher priority first , Then perform lower priority operations . for example , We often say to perform multiplication and division first , And then add and subtract .

Parentheses are used to change the order of computation determined by the priority of the operator . That is to say , First calculate the expression in parentheses , Then use its value for the rest of the expression .

In fact, in the process of calculation , Like any other language , It's better to put parentheses directly , Such as var a = 1; a = (a + 100) >>(a+1); and var a = 1; a = a + 100>>a+1; The result is 25, The order of operation is the same , The readability of the front is better ?

This article is from WeChat official account. - javascript art (gh_4e5484fd6b52) , author :zhangjing

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2021-05-14

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[JavaScript Art]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210528145605038K.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless