Solve - Invalid destructuring assignment target Error in JS

avatar

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:

index.js
// โ›”๏ธ 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.

index.js
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.

index.js
function log(obj = {key: 'value'}) { console.log(obj); // ๐Ÿ‘‰๏ธ {key: 'value'} } log();

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

index.js
function log({key} = {key: 'value'}) { console.log(key); // ๐Ÿ‘‰๏ธ "value" } log();

Here's the same example but with arrays.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee