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 did I not get an error when I forgot to declare each variable?

I didn't exactly write a ad-lib style story, but I got the idea.

However, for some reason I forgot to declare any of the variables, but did not get an errors from Chrome Dev Tools' JavaScript console. Why is that?

below is the entirety of what I wrote:

console.log ("Your Script started");

yourName = prompt("What's your Name?");

console.log ("Yes prompt 1");

yourAdjective = prompt("Pick an Adjective");

yourSentence = "Hey, " + yourName + ". You've got an "+ yourAdjective +" name. Jerk.";

document.write (yourSentence);

console.log ("Your Script Ended");

This was part of the Variable Challenge in JavaScript Basics.

I should mention the output in the preview performed exactly as expected.

Thanks, Elise!

1 Answer

Elise Kain
Elise Kain
54,392 Points

Hi Alexander - When you forget the "var", "let" or "const" keyword to declare variables, they are still created but are automatically put in the "global" scope (so they are accessible anywhere). This is not a best practice, so it should be avoided whenever possible. However, since it "works", the Chrome Dev Tools did not give you an error.

See https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals and https://gist.github.com/hallettj/64478 for some more detail.