JavaScript SyntaxError: Invalid shorthand property initializer
To fix JavaScript SyntaxError: Invalid shorthand property initializer, correct the value assignments made to properties of objects. Colon (:) is used for assigning values to properties of objects. Most of the developers type in assignment operator EqualTo(=) instead of Object Initializer (:), which causes SyntaxError.
Example
Following example reproduces the SyntaxError, and we shall correct the same.
index.html
<!doctype html>
<html>
<body>
<h1>JavaScript - SyntaxError: Invalid shorthand property initializer</h1>
<script>
var msg = "";
var mango = [type="fruit", native="India"];
console.log(mango.type);
</script>
</body>
</html>
Output would be
Uncaught SyntaxError: Invalid shorthand property initializer
at render (javascript-editor.php?file=test:126)
at submitCode (javascript-editor.php?file=test:149)
at HTMLButtonElement.onclick (javascript-editor.php?file=test:68)
The bug here is the line:10 var mango = [type=”fruit”, native=”India”]; .
The correct one is var mango = [type:”fruit”, native:”India”]; where we replaced = with : .
index.html
<!doctype html>
<html>
<body>
<h1>JavaScript - SyntaxError: Invalid shorthand property initializer</h1>
<script>
var msg = "";
var mango = [type:"fruit", native:"India"];
console.log(mango.type);
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about using Object Assignment Operator, Colon (:) while assigning values to properties of Objects, resolves JavaScript SyntaxError: Invalid shorthand property initializer.