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 JavaScript Functions Pass Information Into Functions Function Declarations vs. Function Expressions

Victor Stanciu
seal-mask
.a{fill-rule:evenodd;}techdegree
Victor Stanciu
Full Stack JavaScript Techdegree Student 11,196 Points

Why is my variable initialized with the default value of `undefined`, if I declared it with `let` ?

Hi!

Going through the Teacher's Notes, I stumbled upon the link about Hoisting, from MDN https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#let_and_const_hoisting . It says:

"Variables declared with let and const are also hoisted, but unlike for var the variables are not initialized with a default value of undefined. Until the line in which they are initialized is executed, any code that accesses these variables will throw an exception."

I typed the following lines of code directly in the console. The return is commented after each line.

var a;  // returns undefined
let b;  // returns undefined
const c;  // returns Uncaught SyntaxError: Missing initializer in const declaration

My question is: Why is b initialized as undefined, if the documentation states that the JS engine should throw an exception? Did I misunderstand the documentation?

I reloaded the page and even tried the same lines of code in a new tab, but always get the same result.

Thanks so much for your help!

1 Answer

Steven Parker
Steven Parker
231,248 Points

It's a forward reference that throws the exception, not the declaration itself. For examples:

// example 1: both the declaration and initialization are hoisted:
console.log(a);  // will show "undefined"
var a;
// -------------------------------------------
// example 2: only the declaration is hoisted:
console.log(b);  // will cause exception
let b;
Victor Stanciu
seal-mask
.a{fill-rule:evenodd;}techdegree
Victor Stanciu
Full Stack JavaScript Techdegree Student 11,196 Points

Thanks! Your example helped me understand this better. I only declared the variables in my browser console, without actually trying to access (correct term?) their values with console.log.