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 does the console return newly-declared variables as undefined?

I feel like maybe I've misunderstood something fundamental here, which is why I'm asking! Hope this makes sense...

If I declare a variable and set its value in the same statement, for instance:

var x=9;

why does the console return 'undefined' when I run the code? If I then enter simply:

x;

the console returns:

9;

...as expected. So it obviously is storing the value - why is it telling me it's undefined after I first declare it? Have I misunderstood something really basic about either declaring variables or the meaning of undefined?

Many thanks,

Emma

1 Answer

The real answer is that JS is a bit of a quirky language. If you leave out the "var" and just enter "x = 9", the console returns 9.

But the more fundamental principle is the difference between an expression and a statement. The act of assigning a value to x (x = 9) doesn't have any value itself, it's a STATEMENT. However, in your second line, x is an EXPRESSION that evaluates to the number 9, just like "x == 9" is an expression (that in this case evaluates to true).