Solve - Invalid destructuring assignment target Error in JS


Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Invalid destructuring assignment target Error #

The "Invalid destructuring assignment target" error occurs when we make a syntax error when declaring or destructuring an object, often in the arguments list of a function. To solve the error make sure to correct any syntax errors in your code.

syntaxerror invalid destructuring assignment target

Here are some examples of how the error occurs:

// ⛔️ Uncaught SyntaxError: Invalid destructuring assignment target const obj = {name: 'Tom'}, {name: 'John'} // ⛔️ invalid destructuring assignment target function log({ key: "value"}) { console.log(arg) }; // // ⛔️ invalid destructuring assignment target const example = (['a','b']) => { console.log('a'); };

The first example throws the error because we declare a variable to multiple objects without the objects being contained in an array.

Instead you should place the objects in an array or only assign a single value to the variable.

const arr = [{name: 'Tom'}, {name: 'John'}] const obj = {name: 'Tom'};
The second example throws the error because we incorrectly destructure an object in a function's arguments.

If you're trying to provide a default value for a function, use the equal sign instead.

function log(obj = {key: 'value'}) { console.log(obj); // 👉️ {key: 'value'} } log();

And you can destructure a value from an object argument like so:

function log({key} = {key: 'value'}) { console.log(key); // 👉️ "value" } log();

Here's the same example but with arrays.

function log([first, second] = ['one', 'two']) { console.log(first, second); // 👉️ "one", "two" } log();

If you can't figure out where exactly the error occurs, look at the error message in your browser's console or your terminal (if using Node.js).

syntaxerror invalid destructuring assignment target

The screenshot above shows that the error occurs in the index.js file on line 11.

You can also paste your code into an online Syntax Validator. The validator should be able to tell you on which line the error occurs.

You can also hover over the squiggly red line to get additional information.

Use the search field on my Home Page to filter through my more than 1,000 articles.