Best practice in global vs. local scoped variables?

First of all, from my reading and understanding it usually seems like a better idea to declare variables that you will be modifying inside of the function that will act on it, so as not to have any accidents modifying globally declared variables, correct?

What about variables that will be used in multiple functions, like mobileNav, and body below? Is it still better practice to declare them multiple times inside the different functions, or just declare them once globally?

After typing this out I think I’ve answered this myself(better to declare them inside), but I would like to hear a more experienced opinion!

const btn = document.querySelector('.hamburger');
const mobileNav = document.getElementById('mobileNav');
const body = document.querySelector('body');

// Hamburger Menu open/close
function closeNav() {
    mobileNav.style.left = -100 + '%';
    body.style.overflow = '';
}

function openNav() {   
    const btnClose = document.querySelector('.hamburger_close');
    
    mobileNav.style.left = 0;
    body.style.overflow = 'hidden'; // Prevent scrolling when mobileNav is active

    btnClose.addEventListener('click', closeNav);
    window.addEventListener('resize', function() {  // Close mobile section automatically if
        if(window.innerWidth >= 998) {              // window is resized above 998px
            closeNav();
        }
    })
}   
   
 btn.addEventListener('click', openNav);

There are often reasons to have global variables. What you don’t want is to modify global variables inside functions. These are called “side effects”.

1 Like