What is @babel/plugin-proposal-logical-assignment-operators?
The @babel/plugin-proposal-logical-assignment-operators package allows Babel to compile logical assignment operators into ES5 or your target environment's JavaScript. Logical assignment operators combine logical operations with assignment expressions, enabling more concise and expressive code.
What are @babel/plugin-proposal-logical-assignment-operators's main functionalities?
Logical AND assignment (&&=)
This feature allows the assignment of the right operand to the left operand only if the left operand is truthy. It's equivalent to `a = a && b;`.
a &&= b;
Logical OR assignment (||=)
This feature enables the assignment of the right operand to the left operand if the left operand is falsy. It simplifies the expression `a = a || b;`.
a ||= b;
Logical nullish assignment (??=)
This feature assigns the right operand to the left operand only if the left operand is null or undefined, making the code `a = a ?? b;` more concise.
a ??= b;
Other packages similar to @babel/plugin-proposal-logical-assignment-operators
@babel/plugin-proposal-optional-chaining
Similar in its proposal nature and goal to enhance JavaScript's expressiveness, this package allows for optional chaining (`?.`) in JavaScript, enabling reading the value of a property located deep within a chain of connected objects without having to expressly validate each reference in the chain.
@babel/plugin-proposal-nullish-coalescing-operator
This package introduces the nullish coalescing operator (`??`), which is closely related to the logical nullish assignment operator provided by @babel/plugin-proposal-logical-assignment-operators. It allows developers to provide a default value for potentially null or undefined expressions.
@babel/plugin-proposal-logical-assignment-operator
Transforms logical assignment operators into short-circuited assignments
Example
In
a ||= b;
obj.a.b ||= c;
a &&= b;
obj.a.b &&= c;
Out
var _obj$a, _obj$a2;
a || (a = b);
(_obj$a = obj.a).b || (_obj$a.b = c);
a && (a = b);
(_obj$a2 = obj.a).b && (_obj$a2.b = c);
Installation
npm install --save-dev @babel/plugin-proposal-logical-assignment-operators
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["@babel/plugin-proposal-logical-assignment-operators"]
}
Via CLI
babel --plugins @babel/plugin-proposal-logical-assignment-operators script.js
Via Node API
require("@babel/core").transform("code", {
plugins: ["@babel/plugin-proposal-logical-assignment-operators"]
});
References