Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
The "SyntaxError: 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.
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 set a variable to be equal to multiple objects without the objects being contained in an array.
// ⛔️ Uncaught SyntaxError: Invalid destructuring assignment target const obj = {name: 'Tom'}, {name: 'John'}
Instead, you should place the objects in an array or only assign a single value to the variable.
// ✅ declare array of objects const arr = [{name: 'Tom'}, {name: 'John'}]; console.log(arr[0]); // 👉️ { name: 'Tom' } // -------------------------------------------- // ✅ declare a single object const obj = {id: 1, name: 'Bobby Hadz'}; console.log(obj['name']); // 👉️ Bobby hadz
The square brackets []
syntax is used to declare an array and the curly braces
{}
syntax is used to declare an object.
Arrays are a collection of elements and objects are a mapping of key-value pairs.
The second example throws the error because we incorrectly destructure an object in a function's arguments.
// ⛔️ SyntaxError: invalid destructuring assignment target function log({ key: "value"}) { console.log(arg) };
If you're trying to provide a default value for a function, use the equal sign instead.
// ✅ set a default value for a function's parameter function log(obj = {key: 'value'}) { console.log(obj); // 👉️ {key: 'value'} } log();
And you can destructure a value from an object argument as follows.
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).
The screenshot above shows that the error occurs on line 11
in the index.js
file.
You can also hover over the squiggly red line to get additional information.