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 trialSamuel Kleos
Front End Web Development Techdegree Student 13,674 PointsWhat if . . . 🤔 I nested the `i` assignment inside another function. Why on earth does this work as a solution!?
Ok so of course I fixed the loop to scope i
inside the block as a let rather than a var.
But then I moved the assignment of the other i
INSIDE the addNewTeachers
function.
How/why is another i
being assigned when it was never declared?
const courses = [
'Introducing JavaScript',
'JavaScript Basics',
'JavaScript Loops, Arrays and Objects',
'Getting Started with ES2015',
'JavaScript and the DOM',
'DOM Scripting By Example'
];
function addNewTeachers(newTeachers) {
i = courses.length; // ❓ I moved `i` here from the global scope but I NEVER DECLARED IT
newTeachers.forEach((newTeacher) => {
teachers.push({name: newTeacher.name, topicArea: newTeacher.topicArea});
});
}
addNewTeachers(newTeachers)
function printTreehouseSummary() {
for (let i = 0; i < teachers.length; i++) {
console.log(`${teachers[i].name} teaches ${teachers[i].topicArea}`);
}
console.log(`Treehouse has ${i} JavaScript courses, and ${teachers.length} Javascript teachers`);
// ❓How on earth does it have access the correct value (6) here??
}
printTreehouseSummary();
CORRECT CONSOLE OUTPUT:
Ashley teaches Javascript
James teaches Javascript
Treasure teaches Javascript
Treehouse has 6 JavaScript courses, and 3 Javascript teachers
1 Answer
Brian Jensen
Treehouse StaffGreat question Samuel Kleos!
By default, if you assign a value to a variable that you have not declared, JavaScript implicitly declares that variable for you. Implicitly declared variables are always created as global variables, even if they are used within the body of a function.
However, if you enable strict mode by adding "use strict"
to the top of your JS file, it will disable that behavior and throw this error:
ReferenceError: i is not defined
Samuel Kleos
Front End Web Development Techdegree Student 13,674 PointsSamuel Kleos
Front End Web Development Techdegree Student 13,674 PointsWow amazing!