Consider an object
let student = {
name: "Josh"
}
and a function
function getData({name, age = 20}){
console.log(name, age)
}
This works as expected. We get console log of name
and age
with default value of 20.
However, how come below throws the error (Uncaught SyntaxError: Invalid shorthand property initializer)?
let name = "Mike"
let anotherStudent = {name, age = 20}
Why the shorthand {name, age = 20}
behaves differently in function parameters and object assignment?
2
Answers
This syntax is not valid for creating an object literal. The issue lies with the use of the age = 20 part. This syntax is allowed in function parameters for providing default values, but it’s not allowed in object literals directly.
If you want to achieve the same default value behavior when creating an object, you can use the following approach:
In this case, you explicitly set the age property to 20 when creating the object literal.
The difference is between assignment targets (function parameters, assignment lhs) and expressions (function call arguments, assignment rhs), not between functions and assignments. A destructuring pattern with a default initialiser is only valid as the target of an assignment.