skip to Main Content

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


  1. let name = "Mike"
    let anotherStudent = {name, age = 20}
    

    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:

    let name = "Mike"
    let anotherStudent = {name, age: 20 /*Your number*/}
    

    In this case, you explicitly set the age property to 20 when creating the object literal.

    Login or Signup to reply.
  2. 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.

    // wrong:
    function getData({name, age: 20}) {…}
    // correct object destructuring:
    function getData({name, age = 20}) {…}
    // wrong:
    const {name, age: 20} = student;
    // correct object destructuring:
    const {name, age = 20} = student;
    
    // wrong:
    getData({name, age = 20});
    // correct object literal:
    getData({name, age: 20});
    // wrong:
    const student = {name, age = 20};
    // correct object literal:
    const student = {name, age: 20};
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search