0

I begin with ES6 and I don't understand why I can't access to my constant in my function. Here my code for you to understand.

const menuMain1Desktop = function () {
    const LEVEL1_LINK_ALL = document.querySelectorAll('.menu-main-1__level-1-link')
    const LEVEL1_ITEM_ACTIVE = document.querySelector('.menu-main-1__level-1-item--active')
    // ...
    function openMenuMain1Level2(el) {
        LEVEL1_ITEM_ACTIVE.classList.remove('menu-main-1__level-1-item--active')
        // Here LEVEL1_ITEM_ACTIVE is null
    }

    for (let i = 0; i < LEVEL1_LINK_ALL.length; i++) {
        const level1ItemThis = this.parentNode            
        const level1ActiveClass = this.parentNode.classList.contains('menu-main-1__level-1-item--active')

        if (level1ActiveClass) {
            closeMenuMain1Level2(level1ItemThis)
        } else {
            openMenuMain1Level2(level1ItemThis)
        }
    }
}

In the function openMenuMain1Level2, LEVEL1_ITEM_ACTIVE is null, why? My constant is in global scope.

If I add constant LEVEL1_ITEM_ACTIVE in my function then it works.

Thanks

Icepickle
  • 12,014
  • 3
  • 29
  • 43
Steven Mouret
  • 5,242
  • 1
  • 14
  • 20
  • 2
    Because you don't have any element of class "menu-main-1__level-1-item--active" when menuMain1Desktop is called, probably. You should ensure the DOM is ready before calling it (if your elements aren't dynamically created the simplest solution is to call your script from the end of the body). – Denys Séguret Apr 05 '17 at 14:49
  • how is the code loaded, when does it get loaded? `const` is, like `let`, block level scope – Icepickle Apr 05 '17 at 14:51
  • Are you placing your script at the end of the file? – Emad Salah Apr 05 '17 at 15:12
  • Ok thanks guys, menu-main-1__level-1-item--active is added in openMenuMain1Level2 function so it's normal. – Steven Mouret Apr 05 '17 at 15:17
  • Your variables are definitely in scope, they just have the value `null`. – Bergi Apr 05 '17 at 16:18

0 Answers0