Last updated: Mar 2, 2024
Reading timeยท2 min
The "SyntaxError: Invalid shorthand property initializer" occurs when we use an equal sign instead of a colon to separate the keys and values in an object.
To solve the error, make sure to use colons between the keys and values of the object.
Here's an example of how the error occurs.
// โ๏ธ Uncaught SyntaxError: Invalid shorthand property initializer const obj = { name = 'Bobby Hadz', // ๐๏ธ should be : and not = age = 30, }
Notice that we used equal signs to separate the key-value pairs in the object.
When declaring an object, use colons to separate the key-value pairs.
const obj = { name: 'Bobby Hadz', // โ use colons to separate key and value age: 30, }; console.log(obj); // ๐๏ธ {name: 'Bobby Hadz', age: 30} console.log(obj.name); // ๐๏ธ Bobby Hadz console.log(obj.age); // ๐๏ธ 30
Objects are a mapping of key-value pairs.
The syntax for a key-value pair in an object is key: value
.
notice that the code sample uses colons to separate each key and value.
Commas are used to separate the key-value pairs of the object.
const obj = { id: 1, name: 'Bobby Hadz', tasks: ['develop', 'test', 'ship'], address: { country: 'Austria', street: 'Example street 123', }, }; console.log(obj.name); // ๐๏ธ Bobby Hadz // ๐๏ธ Austria console.log(obj.address.country);
You can have a trailing comma after the last key-value pair of the object as shown in the code sample above.
However, if you want to add a new key-value pair to the object, you would use the equal sign.
const obj = { name: 'Bobby Hadz', age: 30, }; obj.country = 'Chile'; // ๐๏ธ {name: 'Bobby Hadz', age: 30, country: 'Chile'} console.log(obj);
If the key contains spaces or starts with a number or a special character, you have to use bracket notation, instead of dot notation, to add a key-value pair to the object.
const obj = { name: 'Bobby Hadz', age: 30, }; obj['street address'] = 'Example 1234'; // ๐๏ธ {name: 'Bobby Hadz', age: 30, 'street address': 'Example 123'} console.log(obj); console.log(obj['street address']); // ๐๏ธ Example 123
Using dot notation to access an object property is more concise but has some limitations.
You should use bracket notation if:
Make sure to use an equal sign when declaring a variable.
const name = 'Bobby Hadz'; console.log(name); const arr = ['bobby', 'hadz', 'com']; console.log(arr); const obj = {name: 'Bobby', age: 30}; console.log(obj);
The name of the variable is specified on the left-hand side of the assignment and the value on the right-hand side.
A single equal sign is used for assignment, whereas two or three equal signs are used for comparison.
const name = 'Bobby Hadz'; console.log(name); if (name === 'Bobby Hadz') { console.log('the values are equal') } else { console.log('the values are NOT equal') }