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

Why doesn't this var conflict with the const in this function?

'use strict';

(function () { const student = { name: 'James' };

function createStudent(name) { const student = { name: name }; return student; }

console.log(createStudent('Ken')); console.log(student); })();

I tried it in chrome dev tool and it didn't generate an error of "student is already assigned"? like the video about duplicate variables talked a bout?

Thank yoU!

1 Answer

In JavaScript, variables created with var inside of a function are "scoped" to that function, meaning they can only be reached from inside that function, other parts of the program do not "see" them. This also applies to nested functions - the outer function doesn't see what's going on in the inside one, you can define variables with the same name without problems.

The same applies to let and const, but they are scoped not only to the nearest function, but, more generally, the nearest curly brace-separated enclosing block (like a loop or an if-statement inside a function).