Borislav Hadzhiev
Tue Oct 19 2021·1 min read
Photo by Thomas Bjornstad
The "Invalid shorthand property initializer" error occurs when we use an equal
sign instead of a colon to separate the values in an object. To solve the error,
make sure to use colons between the keys and values of an object when declaring
one, e.g. const obj = {name: 'Tom', age: 30}
.
Here's an example of how the error occurs.
// ⛔️ Uncaught SyntaxError: Invalid shorthand property initializer const obj = { name = 'Tom', // 👈️ should be : and not = age = 30, }
Notice that we used equal signs to separate the key-value pairs of the object.
When declaring an object, we should use a colon to separate the key-value pairs.
// ✅ Works const obj = { name: 'Tom', age: 30, }; console.log(obj); // 👉️ {name: 'Tom', age: 30}
However, if you want to add a new key-value pair to the object, you would use the equal sign.
const obj = { name: 'Tom', age: 30, }; obj.country = 'Chile'; console.log(obj); // 👉️ {name: 'Tom', age: 30, country: 'Chile'}
const obj = { name: 'Tom', age: 30, }; obj['street address'] = 'Example 1234'; // 👉️ {name: 'Tom', age: 30, 'street address': 'Example 123'} console.log(obj);
To solve the "Invalid shorthand property initializer" error, make sure to use
a colon instead of an equal sign between the key-value pairs of an object
literal, e.g. const obj = {country: 'Mexico', city: 'Juarez'}
.