Skip to content
Advertisement

Destructuring In JavaScript and Initialization

How does initialization work in JavaScript? I am getting an error on the below code saying cannot access obj before initialization.

let a = 7;
let b = 10;

const obj = { a:23, b:35, c:70 }
({a, b} = obj);
console.log(a, b);

Advertisement

Answer

It’s because you’re relying on Automatic Semicolon Insertion and no automatic semicolon is added after the const obj... line. Without one, that line and the following one are treated as one expression which does indeed try to access obj before it’s initialized:

const obj = { a:23, b:35, c:70 }({a, b} = obj);

To the parser, that looks like a function call. If you weren’t trying to access obj in what the parser thinks is an arguments list, it would have failed when it got to the point of calling the object, since the object isn’t callable.

You need an explicit semicolon to separate the statements:

let a = 7;
let b = 10;

const obj = { a:23, b:35, c:70 }; // <==== Here
({a, b} = obj);
console.log(a, b);

Looking at your code, you probably just forgot this one since you include other ones. But if you’re going to rely on ASI, make sure you prefix every line starting with (, [, or ` with a ; to prevent that line from continuing the previous expression.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement