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 trialBryan Land
10,306 PointsprintTreehouseSummary() function has incorrect template literal for courses
I was confused about why I was getting different output based on the value of a template literal on Line 45 of the work-space code:
console.log(`Treehouse has ${i} JavaScript courses, and ${teachers.length} Javascript teachers`);
When running my code with the ${i} template literal for "courses", I get a 6 for the output before calling the addNewTeachers function. After calling it, I'm then getting a 1. I figured out it's due to the way my function works and the scope of the for loop's counter variable, which I mistakenly made i. It was basically adding 2 people and making the "index" variable 1.
function addNewTeachers(newTeachers) {
// TODO: write a function that adds new teachers to the teachers array
// DONE
for (i in newTeachers) {
let teacherToAdd = newTeachers[i];
teachers.push(teacherToAdd);
}
}
The best fix I could come up with is removing the i variable and changing the template literal for courses to ${courses.length}. Ideally i should only be used inside of a loop for obvious reasons having to do with scope.
Just thought I would share this in case anyone else runs into the same problem. If anyone else has other ways they wrote the addNewTeachers function, let me know. Thanks!
1 Answer
Steven Parker
231,269 PointsTo constrain the scope of the variable "i" to the loop, you need to declare it with "var" or "let". Without an explicit declaration, it is implicitly global, which allows the function to impact the value of the similarly named variable outside the function.
Bryan Land
10,306 PointsBryan Land
10,306 PointsOkay that clears it up. Thanks!