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 trial

JavaScript

Shadab Khan
Shadab Khan
5,470 Points

Use of 'var' vs 'let' keyword in a function

Hi,

In the JavaScript practice workshop on using the 'let' and 'var' keyword, there is a function as below that counts the total no. of treehouse courses and teacher as below:

const courses = ['Introducing JavaScript',
                'JavaScript Basics',
                'JavaScript Loops, Arrays and Objects',
                'Getting Started with ES2015',
                'JavaScript and the DOM',
                'DOM Scripting By Example'];

var i = courses.length;

function printTreehouseSummary() {

  for (var 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`);
}

On output, why does this print 3 instead of 6 courses? The usage of 'var i' in the for loop is within the scope of a function, and from what I remember, any variable declared inside the scope of a function is exclusive to that function. Then why in the above scenario we see the 'variable shadowing' occurring whereby the 'var i' initialised in the for loop under the printTreehouseSummary function is overwriting the 'var i' variable declared and initialised at the global scope level? Please help me understand this.

1 Answer

All of the times you are referencing to 'i' you are inside the function, so it takes that i.

In this case, since the for loop has it's own block scope, if you'd use 'let' instead of 'var', it would use the other 'i' only inside the for loop.

However, it's way more clear to just use two different variables.