-2

I am newbie to JavaScript. Here's the sample code.

let options = {
  title: "Menu",
  width: 100,
  height: 200
};

console.log(options.title);
let {title, width, height} = { options:title, options:width, options:height}; // clause 1

I am getting Uncaught ReferenceError: Cannot access 'title' before initialization on clause 1.

Why? The object options is initialized and hence i was able to print the options.title.

Again. Sorry for asking stupid question.
Thanks.

yapkm01
  • 3,590
  • 7
  • 37
  • 62
  • `let {title, width, height} = options;` – WilomGfx Apr 27 '23 at 14:27
  • 5
    The [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) should be `let {title, width, height} = options`. – Andy Apr 27 '23 at 14:28
  • you can print `options.title` but `options:title` is different – Chris G Apr 27 '23 at 14:28
  • i know this let {title, width, height} = options would work. I am just curious why the above does not work when the following works let {height, width, title} = { title: "Menu", height: 200, width: 100 } ?? – yapkm01 Apr 27 '23 at 14:29
  • 2
    Because `{ options:title, options:width, options:height }` isn't valid JS. @yapkm01 – Andy Apr 27 '23 at 14:31
  • 2
    Surely you can see what's different between `{ title: "Menu", height: 200, width: 100 }` and `{ options: title, options: width, options: height}`. If for some reason you'd want to create a new object then it should be `{ title: options.title, width: options.width, height: options.height}` – Guy Incognito Apr 27 '23 at 14:31

1 Answers1

1

In let {title, width, height} = { options:title, options:width, options:height}, the options: title part is trying to create an object property called options, setting its value using an in-scope title variable. The only title variable in your code is the one being defined by that let. The initializer on the right-hand side of that = is evaluated when the title variable has been declared but before it's initialized (ready to be used), so you get that reference error.

It's like doing this, which tries to use value after it's declared (because let declarations are hoisted to the top of their block) but before it's initialized (because let declarations aren't initialized until they're reached in the step-by-step execution of the code):

console.log(value);
let value = 42;

I suspect you just wanted to use options, so you got those values from the object you assigned to options earlier in the code:

let {title, width, height} = options;

Alternatively, from your comment, you may have meant to use options.title (note the ., not :) as a title in the object literal:

let {title, width, height} = { title: options.title, width: options.width, height: options.height};
//                      Colon −−−−−−^        ^−−− dot

That also works (though there's no need for that object literal).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875