How to destructure an object to an already defined variable

By

Learn how to destructure an object into already declared variables in JavaScript using the parentheses assignment syntax, with a leading semicolon for safety.

~~~

To destructure an object into variables that are already declared, wrap the assignment in parentheses: ;({ one, two } = test()). Let me show you how I got there, and why the parentheses are needed.

I had the need to assign the result of a function call to a variable already defined. The function returned an object:

function test() {
  return {
    one: 1,
    two: 2
  }
}

I thought I’ll just use object destructuring, like this:

const { one, two } = test()

But I had two already defined in my code (because of scoping issues) and I couldn’t redeclare it:

let two

//...

const { one, two } = test()
//SyntaxError: Identifier 'two' has already been declared

The workaround with a temporary variable

Simple way would be to have:

const result = test()

two = result.two
const { one } = result

This works, but it adds a result variable I don’t need for anything else.

The parentheses syntax

The cleaner option is to declare both variables first, then destructure into them, wrapping the assignment in parentheses:

let one, two

;({ one, two } = test())

No new declarations, both variables get their values from the returned object.

Why do we need the parentheses?

Try the same assignment without them:

let one, two

{ one, two } = test()
//SyntaxError: Unexpected token '='

When a statement starts with {, JavaScript parses it as a block, not as a destructuring pattern. The parser reaches the = and gives up.

Wrapping the whole thing in parentheses turns it into an expression, and the destructuring assignment works as expected.

Why the leading semicolon?

I added a ; before the parentheses to prevent JS to freak out, because I don’t use semicolons. Any line starting with ( must start with a semicolon, simple rule.

Without it, JavaScript can join the line with the previous one and interpret the ( as a function call on whatever expression came before. That kind of bug is confusing to track down, because the error shows up on a line that looks fine.

If you do end your statements with semicolons, you can drop the leading one.

~~~

Related posts about js: