Syntaxerror: invalid shorthand property initializer
error comes when we use equals operator rather than colon to separate key-values(properties) in object.
To resolve this issue, we need to use colon(:
) rather than equals operator(=) between key and values of an object
Let’s see with the help of example:
1 2 3 4 5 6 |
const country = { name = 'Bhutan', // 👈️ need to use : and not = population = 3000, } |
Notice that we have used =
between name
and Bhutan
.
To resolve this issue, use colon between key-value pair of an object.
1 2 3 4 5 6 7 |
const country = { name : 'Bhutan', // 👈️ Used : correctly population : 3000, }; console.log(country); |
1 2 3 |
{ name: 'Bhutan', population: 3000 } |
To use new key-value property, you can use =
sign.
1 2 3 4 5 6 7 8 9 |
const country = { name : 'Bhutan', // 👈️ Used : correctly population : 3000, }; country.capital = 'Thimphu' console.log(country); |
1 2 3 |
{ name: 'Bhutan', population: 3000, capital: 'Thimphu' } |
Conclusion
To resolve Syntaxerror: invalid shorthand property initializer
, use colon :
to separate key-value pairs of object rather than equals operator(=
).
That’s all about how to fix Syntaxerror: invalid shorthand property initializer.