arrow function returning object literal needs (...)❗️

🚧 under construction

JSobjectsarrow function ⟩ returning object literal needs (...)

const user = () => { age: 2019 };    // ❌ 
const user = () => ({ age: 2019 });  // ✅ 
  • the following code:

const user = () => { name: 'Gandalf', age: 2019 };
  • is interpreted as:

const user = () => { 
    name: 'Gandalf', age: 2019 
    //  ↳ ⛔️ SyntaxError: Unexpected token ':'
};
  • which causes an error:⛔️ SyntaxError: Unexpected token ':', have to wrap the object literal in parentheses to make it work.

// ⭐️ wrap object literal in parentheses
const user = () => ({ 
    name: 'Gandalf', 
    age: 2019 
});

console.log(user());         // { name: 'Gandalf', age: 2019 }

💾 replit:arrow function returning object literal

Last updated