
P42 Code Assists for JavaScript and TypeScript
The P42 JavaScript Assistant adds 91 automated code assists (refactorings, quick fixes, and cleanups) to Visual Studio Code. P42 for GitHub also suggests improvements for the JavaScript code in GitHub repositories and pull requests.
This page lists the code assists by category:
- Core Refactorings
- Code Assists for React
- Code Assists for Logical Expressions
- Code Assists for Branching Statements
- Code Assists for Arrays and Loops
- Code Assists for Functions and Methods
- Code Assists for Strings and Template Literals
- Code Assists for Variables
- Code Assists for Syntax Conversion
- JavaScript Modernizations
- Lodash Modernizations
- Code Cleanups
- Other Code Assists
Code assists that belong to several categories appear more than once.
Core Refactorings
Visual Study Code already contains basic refactorings such as Rename and Extract Function. The JavaScript Assistant adds additional refactorings or extended functionality such as safety checking:
- Extract selected text into variable
Extract the selected text (including expressions from template literals) into a
const
variable. - Extract variable
Extract one or more occurrences of an expression into a
const
variable. - Inline return
Convert a variable assignment to a
return
statement. - Inline variable
Inline a variable value into its references.
Code Assists for React
In React, components often contain JSX, a syntax extension for JavaScript. The JavaScript Assistant provides code assists that make working with JSX and React easier:
- Add {…} to JSX attribute
Add
{…}
to JSX attribute string literal value. - Collapse JSX tag
Convert an empty JSX tag into a self-closing tag.
- Expand JSX tag
Expand a self-closing JSX tag.
- Extract React function component
Extract JSX element or fragment into a React Function Component.
- Remove {…} from JSX attribute
Remove
{…}
from a JSX attribute expression value that contains a string literal. - Remove unnecessary JSX fragment
Replace JSX Fragments
<></>
that only contain a single child with that child. - Surround with <>...</>
Wrap JSX elements in a JSX fragment
<>...</>
.
Code Assists for Logical Expressions
Boolean logic can be challenging to read, especially as expressions get more complex. The JavaScript Assistant provides several refactorings that can help you simplify and tease apart logical expressions to make them easier to understand:
- Convert string comparison chain to array.includes
Replace
|| value === 'aString'
and&& value !== 'aString'
chains witharray.includes()
. - Convert to optional chaining
Replace various guard expressions with the optional chaining operator (
?.
). - Flip operator
Swap the left and right operands and update the operator if necessary.
- Invert condition
Negate the condition of an if-statement or conditional expression and swap its content.
- Pull up negation
Move the not-operator (
!
) out of a binary expression. - Push down negation
Push the not-operator (
!
) into an expression and negate it. - Remove double negation
Remove double negation (
!!
) expressions. - Simplify binary expression
Replace binary expression with a more straightforward equivalent expression.
- Use == null comparison
Replace different nullish checks with
== null
.
Code Assists for Branching Statements
Branching statements such as if-else and switch are central elements in many programs. Restructuring them can increase the readability of your programs, often in combination with refactoring their conditions:
- Convert && to if statement
Convert
condition && aFunction();
and similar expression statements into if statements. - Convert conditional expression to if-else
Convert a conditional expression to an if-else statement.
- Convert if-else into conditional expression
Convert an
if
-else
return or assignment expression into a conditional expression. - Convert if-else to switch
Convert if-else statement chain with equality comparisons to switch statement.
- Introduce early return / continuepro
Change an if-statement into an early return or continue statement.
- Merge nested if inside else into else-if
Nested single
if
statements insideelse
blocks can be combined intoelse if
statements. - Merge nested if-statements
Combine two nested
if
statements without additional operations into a singleif
-statement, using&&
to combine the conditions. - Move duplicated first statement out of if-else
Move a first statement that appears in both the if and the else block out of the if-else statement.
- Move duplicated last statement out of if-else
Move a last statement that appears in both the if and the else block out of the if-else statement.
- Remove empty else block
Remove an empty 'else' block from an 'if' statement.
- Remove empty if block
Remove an empty 'if' block from an 'if' statement. Replaces it with the 'else' block when available.
- Remove redundant else if
Remove redundant else-if conditions and unreachable else statements.
- Remove unnecessary conditional expression
Replace a conditional expression with its condition or its result.
- Remove unnecessary else
Lift the else content of an
if
-else
with a return statement to the outer indentation level. - Separate repeated condition into nested if-else
Separate a repeated sub-condition that is fully covered into a nested if-else.
- Split if statement
Split the condition of an if statement on
||
or&&
when possible.
Code Assists for Arrays and Loops
JavaScript has several ways of defining loops and many array methods that work on the whole array. The JavaScript Assistant provides several code actions for converting between different types of for loops and for converting to more idiomatic array methods such as array.includes().
- Convert array.indexOf() into array.includes()
Replace
array.indexOf()
checks witharray.includes()
. - Convert string comparison chain to array.includes
Replace
|| value === 'aString'
and&& value !== 'aString'
chains witharray.includes()
. - Convert loop to .forEach
Replace regular
for
loops with.forEach()
loops. - Convert loop to for…of
Replace regular
for
loops andanArray.forEach
loops withfor…of
loops. - Convert loop to for
Replace
for…of
with a regularfor
loop that has an index variable. - Convert loop to .map()pro
Convert a loop with
.push()
into a.map()
call.
Code Assists for Functions and Methods
Functions and methods are essential building blocks of any non-trivial program. The following code actions make it easier to work with functions, methods, and their parameters:
- Add {…} to arrow function
Convert arrow function expression body into a block body.
- Convert function to arrow function
Replace function expressions with arrow functions, a more concise syntax.
- Convert function to object method
Convert property assignments with functions to method declarations.
- Convert named function to function expression
Converts a named function to a const declaration with a function expression.
- Lift default into parameter
Replace default value assignment expressions with default parameter values.
- Push parameter into IIFE/IIAF
Push a parameter of an immediately-invoked function expressions (IIFEs) or an immediately-invoked arrow functions (IIAFs) into the function body.
- Remove {…} from arrow function
Convert an arrow function block body into an expression body.
- Remove IIFE/IIAF
Remove immediately-invoked function expressions (IIFEs) and immediately-invoked arrow functions (IIAFs) without parameters.
Code Assists for Strings and Template Literals
Text manipulation has become more powerful with the introduction of template literals in JavaScript. The JavaScript Assistant offers several code actions to help you work with text, be it strings or template literals:
- Convert string comparison chain to array.includes
Replace
|| value === 'aString'
and&& value !== 'aString'
chains witharray.includes()
. - Convert string to template literal
Convert a string to a basic template literal without expressions.
- Convert template literal to string
Convert a simple template literal without expressions into a string.
- Extract selected text into variable
Extract the selected text (including expressions from template literals) into a
const
variable. - Inline into template
Inline a string or a basic template literal into an outer template literal.
- Remove unnecessary template literal
Simplify a template literal with a single inner expression and no prefix or suffix.
- Use string.endsWith()
string.endsWith()
checks if a string ends with another string. - Use string.startsWith()
string.startsWith()
checks if a string starts with another string. - Merge string concatenation
Merge string and template literal concatenation into a single template literal or string.
Code Assists for Variables
- Convert let to const
Replace
let
declarations that have no re-assignment withconst
declarations. - Convert to destructuring assignment
Convert a variable declaration that accesses an object property to a destructuring assignment.
- Extract variable
Extract one or more occurrences of an expression into a
const
variable. - Flatten array rest/spread propertypro
Merge a ...[] expression into the outer array literal or destructuring expression.
- Inline return
Convert a variable assignment to a
return
statement. - Lift default into parameter
Replace default value assignment expressions with default parameter values.
- Merge into preceding destructuring assignment
Combine an object destructuring assignment with its preceding sibling.
- Merge variable declaration and initialization
Convert the initial assignment of a variable into its declaration initializer.
- Move field initialization into constructorpro
Moves the assignment of the initial field value into the class constructor.
- Move initialization into field declarationpro
Moves the assignment of the initial field value into the field declaration.
- Push variable declaration into initial valuepro
Inlines a variable that is initialized with another variable into the declaration of that variable.
- Push parameter into IIFE/IIAF
Push a parameter of an immediately-invoked function expressions (IIFEs) or an immediately-invoked arrow functions (IIAFs) into the function body.
- Remove unused variable
Remove a variable that is not read or written.
- Replace with existing variablepro
Replace an expression with an existing variable.
- Convert var to let or const
Replace
var
with block-scoped variableslet
andconst
. - Split variable declaration sequence
Convert declarations with multiple variables into separate declarations for each variable.
- Split variable declaration and initialization
Separate the variable initialization from its declaration.
- Use nullish coalescence in default expression
Replace default value expression with nullish coalescing operator (
??
) expressions.
Code Assists for Syntax Conversion
It is often annoying to make small syntactical changes by editing text. Often more than one position needs to be edited, and the code is broken during the edit, leading to incorrect errors and auto-completions that get in the way. You can execute the following syntax conversions with code assists:
- Add {…} to arrow function
Convert arrow function expression body into a block body.
- Add {…} to JSX attribute
Add
{…}
to JSX attribute string literal value. - Add numeric separator
Increase the readability of long numbers and uncommon number formats by adding underscore separators.
- Collapse JSX tag
Convert an empty JSX tag into a self-closing tag.
- Collapse object property into shorthand
Shorten object properties when the property name is the same as the property value.
- Convert property access to dot notation
Convert bracket notation property access
o['a']
into dot notation property accesso.a
. - Convert property access to bracket notation
Convert dot notation property access
o.a
into bracket notation property accesso['a']
. - Expand JSX tag
Expand a self-closing JSX tag.
- Expand shorthand property
Expand a shorthand object property (e.g.
{ a }
) to a regular property (e.g.{ a: a }
). - Merge variable declaration and initialization
Convert the initial assignment of a variable into its declaration initializer.
- Pull operator out of assignment
Move an operator out of an assignment into a binary expression.
- Push operator into assignment
Move an operator from a binary expression into an assignment operator, e.g.,
+=
. - Remove {…} from arrow function
Convert an arrow function block body into an expression body.
- Remove {…} from JSX attribute
Remove
{…}
from a JSX attribute expression value that contains a string literal.
JavaScript Modernizations
The Javascript ecosystem is progressing rapidly. However, it is hard to keep codebases up-to-date with the newer JavaScript features, and codemods are not always an option due to their significant churn and potential for breakages. The JavaScript Assistant supports both codemod-like mass code refactoring and more opportunistic code modernization for the following upgrades:
- Add numeric separator
Increase the readability of long numbers and uncommon number formats by adding underscore separators.
- Collapse object property into shorthand
Shorten object properties when the property name is the same as the property value.
- Convert .apply() to spread syntax
Replace
.apply()
calls with the spread operator...
- Convert array.indexOf() into array.includes()
Replace
array.indexOf()
checks witharray.includes()
. - Convert string comparison chain to array.includes
Replace
|| value === 'aString'
and&& value !== 'aString'
chains witharray.includes()
. - Convert function to arrow function
Replace function expressions with arrow functions, a more concise syntax.
- Convert function to object method
Convert property assignments with functions to method declarations.
- Convert loop to for…of
Replace regular
for
loops andanArray.forEach
loops withfor…of
loops. - Convert Math.pow to exponentiation operator
Use the exponentiation operator
**
instead ofMath.pow()
. - Convert string to template literal
Convert a string to a basic template literal without expressions.
- Convert to destructuring assignment
Convert a variable declaration that accesses an object property to a destructuring assignment.
- Convert to optional chaining
Replace various guard expressions with the optional chaining operator (
?.
). - Lift default into parameter
Replace default value assignment expressions with default parameter values.
- Convert var to let or const
Replace
var
with block-scoped variableslet
andconst
. - Replace void 0 with undefined
Replace
void 0
and other constantvoid
expressions withundefined
. - Use == null comparison
Replace different nullish checks with
== null
. - Use nullish coalescence in default expression
Replace default value expression with nullish coalescing operator (
??
) expressions. - Use string.endsWith()
string.endsWith()
checks if a string ends with another string. - Use string.startsWith()
string.startsWith()
checks if a string starts with another string. - Merge string concatenation
Merge string and template literal concatenation into a single template literal or string.
Lodash Modernizations
With the introduction of various collection helpers and new syntax in ES6 and more recent JavaScript versions, some Lodash functions have become somewhat redundant.
- Replace _.every with array.everypro
Replace Lodash
_.every
witharray.every
. - Replace _.filter with array.filterpro
Replace Lodash
_.filter
witharray.filter
. - Replace _.each and _.forEach with array.forEachpro
Replace Lodash
_.each
and_.forEach
witharray.forEach
. - Replace _.map with array.mappro
Replace Lodash
_.map
witharray.map
. - Replace _.noop with arrow Functionpro
Replace
_.noop
with() => undefined
. - Replace _.some with array.somepro
Replace Lodash
_.some
witharray.some
.
Code Cleanups
Code cleanups remove unnecessary code. Such code can result from code churn, e.g., by applying other refactorings, adding new features, or fixing bugs. The JavaScript Assistant shows hints and automates the cleanup for the following situations:
- Flatten array rest/spread propertypro
Merge a ...[] expression into the outer array literal or destructuring expression.
- Remove console.log
Remove console.log statement.
- Remove double negation
Remove double negation (
!!
) expressions. - Remove empty else block
Remove an empty 'else' block from an 'if' statement.
- Remove empty if block
Remove an empty 'if' block from an 'if' statement. Replaces it with the 'else' block when available.
- Remove IIFE/IIAF
Remove immediately-invoked function expressions (IIFEs) and immediately-invoked arrow functions (IIAFs) without parameters.
- Remove redundant else if
Remove redundant else-if conditions and unreachable else statements.
- Remove unnecessary conditional expression
Replace a conditional expression with its condition or its result.
- Remove unnecessary else
Lift the else content of an
if
-else
with a return statement to the outer indentation level. - Remove unnecessary expression statement
Remove an expression statement that has no side-effects.
- Remove unnecessary JSX fragment
Replace JSX Fragments
<></>
that only contain a single child with that child. - Remove unnecessary template literal
Simplify a template literal with a single inner expression and no prefix or suffix.
- Remove unused variable
Remove a variable that is not read or written.
- Replace void 0 with undefined
Replace
void 0
and other constantvoid
expressions withundefined
. - Simplify binary expression
Replace binary expression with a more straightforward equivalent expression.
Other Code Assists
- Insert console.log for variable
Insert a 'console.log' statement for a selected variable when possible.
- Select expression occurrencespro
Start a multi-cursor selection on several occurrences of the same expression.
- Surround with try…catch
Surround a sequence of statements in a
try…catch
block.