What is the purpose of this statement?

In the article for modules, they mention the following example:

import domFunctions from '../modules/dom-functions.js';

const { toggleHiddenElement, changeToFunkyColor } = domFunctions;
 
const buttonElement = document.getElementById('secret-button');
const pElement = document.getElementById('secret-p');
 
buttonElement.addEventListener('click', () => {
  toggleHiddenElement(pElement);
  changeToFunkyColor(buttonElement);
});
  • this example can be found near the bottom of the article


I don’t understand what the third line does:

const { toggleHiddenElement, changeToFunkyColor } = domFunctions;
  • any help is greatly appreciated :slight_smile:

Hi @ammar-ghazal27406054
this is called destructuring assignment.
You can do that with arrays and objects. In this case, it is applied to an object.
You have an object with the keys toggleHiddenElement and changeToFunkyColor:

const domFunctions = {
 toggleHiddenElement: true,
 changeToFunkyColor: 'value'
}

and with the destructuring assignment, you assign the values of the object keys to variables with the names of the keys in a short hand syntax.

Doing this:

const { toggleHiddenElement, changeToFunkyColor } = domFunctions;

does the same as this:

const toggleHiddenElement = domFunctions.toggleHiddenElement;
const changeToFunkyColor = domFunctions.changeToFunkyColor;
1 Like

Thank you for explaining it!

1 Like