complete/prefer-plusplus
💼 This rule is enabled in the ✅ recommended config.
📝 Require ++ or -- operators instead of assignment operators where
applicable.
🔧 This rule is automatically fixable by the
--fix CLI option.
Rule Details
Section titled “Rule Details”The
operator-assignment
ESLint rule converts x = x + 1 to x += 1. This is a fantastic rule because
it makes code more concise and easier to read. (Technically, the code would be
more confusing for people who don’t know what the “+=” operator does, but this
is not an issue in most cases.)
Building on this logic, it also makes sense to convert x += 1 to x++, which
is even more concise and easier to read. (Again, we make the assumption that
everyone knows what the “++” operator does, which should be a pretty safe bet.)
However, the ++ operator is historically controversial in JavaScript. For
example,
the Airbnb style guide gives this justification:
Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like
num += 1instead ofnum++ornum ++. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.
This justification does not apply if you use the combination of:
- The Prettier auto-formatter (which automatically inserts semicolons for you)
- The
complete/no-unsafe-plusplusrule (which prevents usage of++iwhere swapping it toi++would change the functionality of the program) - The
complete/prefer-postfix-plusplusrule (which prevents usage of++iin favor ofi++)
Together, these heavily restrict the usage of the operator, making the only legal usage equal to that of “+= 1”.
// Badi += 1;
// Goodi++;Options
Section titled “Options”This rule is not configurable.
