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 trialCian Jochem
6,574 Pointswhy is 'i' not defined?
?
var section = document.querySelector('section');
var paragraphs = section.children;
for (i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.backgroundColor = 'blue';
}
<!DOCTYPE html>
<html>
<head>
<title>Child Traversal</title>
</head>
<body>
<section>
<p>This is the first paragraph</p>
<p>This is a slightly longer, second paragraph</p>
<p>Shorter, last paragraph</p>
</section>
<footer>
<p>© 2019</p>
</footer>
<script src="app.js"></script>
</body>
</html>
2 Answers
Ella Ruokokoski
20,881 PointsBecause you have not declared it anywhere. In the beginning of you for loop the i has to bee declared using let.
Cian Jochem
6,574 Pointsthx and sorry for this question...
Ella Ruokokoski
20,881 Pointsnp, and no need to be sorry for any questions!
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 PointsBrandon White
Full Stack JavaScript Techdegree Graduate 35,771 PointsI'm actually a bit surprised that your program told you that "i" was undefined. It shouldn't be. Ella's right in that you should include the let keyword when declaring "i" in your for loop, but not including the let keyword does not cause the "i" variable to not be created... it just creates it in the global scope. And so even after the for loop has finished executing, the window would still hold a variable named "i", and it's value would be 3.
The error you received appears to specifically be a Treehouse thing. The test the challenge is using to evaluate your code appears to be making sure that you include the let keyword, which again (is good practice). But it may also be important to understand that in a real world coding situation, you would not get an error for not including let or const before i (or any other variable). It just might cause other issues later in your program.