Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAarti Chordia
Full Stack JavaScript Techdegree Student 4,580 PointsWhy did we declare const checkbox twice, in the form & UL event handlers? & How were we able to do it?
const form = document.querySelector("#registrar");
const input = form.querySelector("input");
const ul = document.querySelector("#invitedList");
form.addEventListener("submit", (e) => {
e.preventDefault();
const text = input.value;
input.value = "";
const item = document.createElement("li");
item.textContent = text;
const label = document.createElement("label");
label.textContent = "Confirmed";
const checkbox = document.createElement("input");
/*here we created the const checkbox for the first time*/
checkbox.type = "checkbox"
label.appendChild(checkbox);
item.appendChild(label);
ul.appendChild(item);
});
ul.addEventListener("change",(e) => {
const checkbox = e.target;
/*Why do we create it again and how are we able to?*/
const checked = checkbox.checked;
const listItem = checkbox.parentNode.parentNode;
if (checked) {
listItem.className = "responded"
} else {
listItem.className = "" }
});
1 Answer
Steven Parker
231,269 PointsThese are two different variables, and they both have a scope that is limited to the function they are defined in. This means they can only be accessed from code in the same function.
It doesn't matter that they have the same name, because even if they had different names they could not be accessed from the other function.