Skip to content

eslint/prefer-destructuring Style

🚧 An auto-fix is still under development.

What it does

Require destructuring from arrays and/or objects

Why is this bad?

With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression.

Examples

Examples of incorrect code for this rule:

js
// With `array` enabled
const foo = array[0];
bar.baz = array[0];
// With `object` enabled
const qux = object.qux;
const quux = object["quux"];

Examples of correct code for this rule:

js
// With `array` enabled
const [foo] = array;
const arr = array[someIndex];
[bar.baz] = array;

// With `object` enabled
const { baz } = object;
const obj = object.bar;

Options

This rule takes two arguments, both of which are objects. The first object parameter determines what types of destructuring the rule applies to. In the first object, there are two properties, array and object, that can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.

json
{
  "prefer-destructuring": ["error", { "array": true, "object": true }]
}

Alternatively, you can use separate configurations for different assignment types. The first argument accepts two other keys instead of array and object. One key is VariableDeclarator and the other is AssignmentExpression, which can be used to control the destructuring requirement for each of those types independently

json
{
  "prefer-destructuring": [
    "error",
    {
      "VariableDeclarator": { "array": true, "object": true },
      "AssignmentExpression": { "array": true, "object": true }
    }
  ]
}

enforceForRenamedProperties

The rule has a second object argument with a single key, enforceForRenamedProperties, which determines whether the object destructuring applies to renamed variables.

json
{
  "prefer-destructuring": ["error", { "array": true, "object": true }, { "enforceForRenamedProperties": true }]
}

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny prefer-destructuring
json
{
  "rules": {
    "prefer-destructuring": "error"
  }
}

References

Released under the MIT License.