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 Understanding "this" in JavaScript

ilovecode
ilovecode
8,071 Points

Why is portland, seattle etc not declared with const or let?

This video has a lot of copying and pasting without any real explanations on some parts.

e.g

portland = new City();
seattle = new City('Seattle', 'Washington');
salem = new City('Salem');
vancouver = new City('Vancouver', 'Washington');

Why don't 'portland', 'seattle', 'salem', and 'vancouver' have the let or const keyword in front? Are they not normal variables? Please help!

Tim Oltman
Tim Oltman
7,730 Points

I found this stackoverflow post on the topic. Apparently, any variable can be declared without const, let, or var. For example, in the console, the following works just fine:

x = 5;
console.log(x); // 5

From the answer on stackoverflow:

If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches...This is, in my opinion, one of the most dangerous issues with javascript...

So it seems you can use a variable without declaring it first. Javascript will then look in every scope all the way up to the the global scope looking to overwrite the value of that variable. If it doesn't find it, it will attach it to the global scope. This could be really dangerous because, let's say you're using a package or some code written by somebody else and you don't know what they named their variables. x might be an array of values or an instance of a class and you just overwrote it with the value 5.

1 Answer

ilovecode
ilovecode
8,071 Points

Thank you Tim, it is good to know, I learnt something new!