what is and why use block-scope const in js?

Hi, there. Below is the code example I encountered. It is my first time seeing const declared after a const. What are block-scoped const in js and why use them there? What would be the difference if the const declare globally? Thank you for your attention and help!
/*=============== SHOW MENU ===============*/
const navMenu = document.getElementById('nav-menu'),
navToggle = document.getElementById('nav-toggle'),
navClose = document.getElementById('nav-close')

/*===== MENU SHOW =====*/
/* Validate if constant exists */
if(navToggle){
navToggle.addEventListener('click', () =>{
navMenu.classList.add('show-menu')
})
}

/*===== MENU HIDDEN =====*/
/* Validate if constant exists */
if(navClose){
navClose.addEventListener('click', () =>{
navMenu.classList.remove('show-menu')
})
}
/*=============== SHOW MENU ===============*/
const navMenu = document.getElementById('nav-menu'),
navToggle = document.getElementById('nav-toggle'),
navClose = document.getElementById('nav-close')

/*===== MENU SHOW =====*/
/* Validate if constant exists */
if(navToggle){
navToggle.addEventListener('click', () =>{
navMenu.classList.add('show-menu')
})
}

/*===== MENU HIDDEN =====*/
/* Validate if constant exists */
if(navClose){
navClose.addEventListener('click', () =>{
navMenu.classList.remove('show-menu')
})
}
6 Replies
Wolle
Wolle•2y ago
This is just multiple declarations "in one line", it is the same as if you would write:
const navMenu =..;
const navToggle = ..;
const navClose = ..;
const navMenu =..;
const navToggle = ..;
const navClose = ..;
Block scoped const on the other hand is when you declare a const inside a scope (for example a function)
function blubb(){
const bla = 'test';
console.log(bla); // -> "test"
}
console.log(bla); // -> bla is not defined
function blubb(){
const bla = 'test';
console.log(bla); // -> "test"
}
console.log(bla); // -> bla is not defined
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
redtypoOooOo
redtypoOooOoOP•2y ago
hi Wolle, thanks! I understand now. Didn't know const can be written that way. Can you explain to me what
if(navToggle)
if(navToggle)
does? is it abbreviated?
Wolle
Wolle•2y ago
If document.getElementById (and querySelector/All) can not find the element, they return null, that is to make sure the HTML elements are there and already loaded.
redtypoOooOo
redtypoOooOoOP•2y ago
oh, so it mean "if ( there is this element called const navMenu), run the below code", right? thank you for your help! 🙂
Wolle
Wolle•2y ago
Yes. (correctly it asks if the content of navToggle is a truthy value. If you don't know what truthy/falsy is: https://medium.com/coding-at-dawn/what-are-falsy-values-in-javascript-ca0faa34feb4)
redtypoOooOo
redtypoOooOoOP•2y ago
got it! and thanks for the article, will read about it!
Want results from more Discord servers?
Add your server