Assign an object property using optional chaining?

Let's assume that you have the following object:

let erik = { age: 31 }

You can't use the optional chaining operator to create/modify a new variable:

// ❌ Uncaught SyntaxError: Invalid left-hand side in assignment
erik.location?.city = 'Barcelona'

But you can do the following:

erik.location = erik.location || {} = 'Barcelona'

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.