2

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);

4
  • const {a, b} = obj; Commented Feb 16, 2021 at 17:18
  • @Mellet - OP seems to want to update existing variables. Commented Feb 16, 2021 at 17:19
  • @T.J.Crowder Ah, yes. Sorry ;) Commented Feb 16, 2021 at 17:19
  • Does this answer your question? What are the rules for JavaScript's automatic semicolon insertion (ASI)? Commented Aug 25, 2021 at 1:56

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

T.J. Crowder Thanks a lot it worked. I was relying on ASI so i don't know how it missed it.
2

Put semicolon after the }

let a = 7;
let b = 10;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.