Search code examples
javascriptif-statementdestructuring

destructured object not accesible in of statement


My code looks like this it's aiming to observe a modal content when it's open

const data = {
   modal: false,
   button: null
};

const updateData = () => {
   const {modal, button} = data

   if (document.querySelector('.modal')) {
       modal = true
       button = document.querySelector('.modalButton')
   }
};

I get the following error when I call updateData():

Uncaught ReferenceError: modal is not defined"

It works as intended when it's written like this:

const updateData = () => {

    if (document.querySelector('.modal')) {
        data.modal = true
        data.button = document.querySelector('.modalButton')
    }
};

I can't understand why destructured data isn't accessible in the if statement.


Solution

  • I'm still not 100% sure what you're trying to do, because you set the variables modal and button by destructuring them, and then you don't use those variables...

    You can do something like this:

    const data = {
       modal: false,
       button: null
    };
    
    const updateData = () => {
       const {modal, button} = data
    
       if (true) {
         return {
           modal, button
         }
       }
    };
    
    console.log(updateData());

    You cannot update properties of objects AFTER destructuring, by using the destructured variables, if that's what you're trying to do.

    If you want to update data.modal, you'll have to do data.modal = 'xx';