Search code examples
javascriptobject-destructuring

JavaScript: Getting a Uncaught ReferenceError: Cannot access 'title' before initialization


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.


Solution

  • 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).