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 .
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
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';
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
val It's true , be a Value ifTrue , Otherwise, the value is ifFalse
const a = val ? ifTrue : ifFalse
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
&& 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
To a number | 0 It can be rounded , Negative numbers also apply ,num | 0
1.3 | 0 // 1 -1.9 | 0 // -1
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
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
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 .
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 .