Solve - Invalid shorthand property initializer Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

Solve - Invalid shorthand property initializer Error #

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}.

syntaxerror invalid shorthand property initializer

Here's an example of how the error occurs.

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

index.js
// โœ… 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.

index.js
const obj = { name: 'Tom', age: 30, }; obj.country = 'Chile'; console.log(obj); // ๐Ÿ‘‰๏ธ {name: 'Tom', age: 30, country: 'Chile'}
Note that if the key contains spaces, starts with a number or a special character, you have to use bracket notation instead of dot notation when adding a key-value pair to an object.
index.js
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'}.

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