JavaScript DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

tomd
tomd
14,686 Points

Why is there a const for the ul? It was declared at the top of the page.

So i was going through the code and noticed 'const ul = li.parentnode' but we have 'const ul = document.getElementById('invitedList');' at the top. Why do we need the second const?

2 Answers

Neil McPartlin
Neil McPartlin
14,635 Points

Hi Tom. This is an example of global vs local scoping. The 'ul' you are seeing declared at the top is in the global scope and is visible everywhere. But the one you are seeing shown lower down is actually within a function. If that one had not been declared 'locally' with its own 'const' (or 'let'), any changes made to 'ul' within that function would accidentally also change the globally declared 'ul' which could lead to unforeseen consequences. I can't quickly find a nice MDN explanation about this but this one from w3schools is helpful.

https://www.w3schools.com/js/js_scope.asp

tomd
tomd
14,686 Points

Ohhh i see now. Thank you for clearing that up.