Author: Joe Seifi
Translator: Frontend Xiaozhi
Mobile: https://mp.weixin.qq.com/s/p5b8a2pRHJUXDihmb4t2rA
There are dreams and dry goods. search 16091ee1ab668f [Moving to the World] Follow this brushing wisdom who is still doing dishes in the early morning.This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.
Logical assignment is an extension of existing mathematical and binary logic operators. Let's review it first, and then see what we can get by combining them.
First, we look at the JS conditions and operator
distinction between unconditional 😎 operator.
Unconditional vs conditional
Mathematical operators such as +
are unconditional.
In const x = 1 + 2
, no matter what, we always add LHS
to RHS
and assign the result to x
.
LHS and RHS are concepts in the field of mathematics, meaning the left side of the equation and the right side of the equation. In our current scenario, it is the left and right sides of the assignment operator. When the variable appears on the left side of the assignment operator, the LHS query is performed; otherwise, the RHS query is performed 😨.
We can even write some strange codes, such as const x = false +2
. JS first false
converted to LHS Number
, thus obtained const x = Number(false)+ 2
, as a result is const x = 0 + 2. It adds LHS to RHS, and finally assigns it to
x
, resulting in 2
.
Logical operators, such as &&
are conditional
In const x = true && 0 + 2
, first calculate the LHS, which is true
. Because the value of LHS is true
, we then run the RHS operation, which has a value of 2, and also runs the assignment operation, and the result is 2
.
Compared with const x = false && 0 + 2
, LHS is false
, so RHS is completely ignored.
You may be wondering why you should avoid calculating RHS? Two common reasons are to get better performance and avoid side effects💪.
Binary logic operators
&& || ??
In JSX, we often use &&
and ||
to conditionally render the interface. ??
is the nullish (null value) coalescing operator. It has just passed a proposal recently and will soon become popular. They are all binary logic operators.
- Use
&&
test whether the result of LHS is true. - Use
||
test whether the result of LHS is an imaginary value. - Use
??
test whether LHS is invalid.
Null Value vs Nullish
What are imaginary values in JS😏?
- null
- undefined
- false
- NaN
- 0
- "" (empty string)
The following two sisters are considered nullish values 😧.
- null
- undefined
It is worth noting that the use of binary logic operators does not necessarily return the Boolean value, but returns the
LHS
or RHS
value of the expression. In order to clarify the main points of these expression types, it is helpful to review this sentence in the ECMAScript documentation:
&&
or||
is not necessarily a boolean, but one of the two operand expressions.
Some examples
// &&
/ /如果 LHS 是真值,计算并返回 RHS,否则返回 LHS
true && 100**2 // 10000
"Joe" && "JavaScript" // "JavaScript"
false && 100**2 // false
"" && 100**2 // ""
NaN && 100**2 // NaN
null && 100**2 // null
undefined && 100**2 // undefined
Logical assignment operator
&&= ||= ??=
This operator combines assignment with conditional logical operators, so it is named "logical assignment" 😚. They just a shorthand, e.g., x && = y
is x && (x = y)
abbreviated.
The value returned from the logical assignment is not the updated assignment, but the value of the calculated expression.
Due to previous ECMAScript features, such as default parameters and nullish merge operators, you can say that there must be some redundancy in the functionality provided by logical assignment. Although this shorthand looks very smooth, and I believe it will come in handy when we discover more use cases.
Logical AND assignment (&&=)
// 逻辑与
LHS &&= RHS
// 等价于
LHS && (LHS = RHS)
// 事例
// if x is truthy, assign x to y, otherwise return x
// 如果 x 为真值,则将 y 赋值给 x, 否则返回 x
let x = 1
const y = 100
x &&= y // x 为 100
// 与上面对应的长的写法
x && (x = y)
Logical OR assignment (||=)
// 逻辑或
LHS ||= RHS
// 等价于
LHS || (LHS = RHS)
// 事例
// 如果 x 为真值,返回 x,否则将 y 赋值给 x
let x = NaN
const y = 100
x ||= y // x 为 100
// 与上面对应的长的写法
x || (x = y)
Logical nullish assignment (??=)
// 逻辑 nullish
LHS ??= RHS
// 等价于
LHS ?? (LHS = RHS)
// 事例
// if x.z is nullish, assign x.z to y
let x = {}
let y = 100;
x.z ??= y // x 为 { z: 100 }
// 与上面对应的长的写法
x.z ?? (x.z = y)
Example of logical assignment in implementation
JSX in React
let loading = true
const spinner = <Spinner />
loading &&= spinner
DOM
el.innerHTML ||= 'some default'
object
// 如果对象没有 onLoad 方法,则设置一个方法
const config = {};
config.onLoad ??= () => console.log('loaded!')
const myObject = { a: {} }
myObject.a ||= 'A'; // 被忽略,因为 myObject 中 a 的值为真值
myObject.b ||= 'B'; // myObject.b 会被创建,因为它不丰 myObject 中
// {
// "a": {}
// "b": "B"
// }
myObject.c &&= 'Am I seen?'; // 这里的 myObject.c 为虚值,所以什么都不会做
How to use logical assignment in the project
Chrome already supports logical assignment. For backward compatibility, please use transformer. If you are using Babel, please install the plugin:
npm install @babel/plugin-proposal-logical-assignment-operators
And add the following content .babelrc
{
"plugins": ["@babel/plugin-proposal-logical-assignment-operators"]
}
Logical assignment is a brand new concept, so there is not much related knowledge yet. If you have other good examples of logical assignment, please leave a comment below😜.
code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .
Original: https://seifi.org/javascript/javascript-logical-assignment-operators-deep-dive.html
communicate with
There are dreams and dry goods. search 16091ee1ab6ce3 [Daily Move to the World] still doing dishes in the early morning.This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。