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 Basics | Introducing Variables: something's wrong with my code apparently - or maybe I misunderstood?

In the video, Dave says at this point

var message = "Hello!";
alert(message); 
message = "Welcome to JavaScript Basics"; 

the first "Hello!" message should disappear from my page (overwritten by the new one, I guess), but after I save and refresh the page the first message is still there. He also says that after I add another "alert(message);"

var message = "Hello!";
alert(message); 
message = "Welcome to JavaScript Basics"; 
alert(message);

the only dialog box should be the one that says "Welcome to JavaScript Basics". This doesn't happen. I copied and pasted the code exactly as it is.

2 Answers

In the video Introducing Variables, video 1 at around 4:25s Dave states the following:

"You don't need to use the var keyword again, you only use it when you first create the variable. When you use the variable later in your program or change the variable's contents, you don't need to use the var keyword again. The equal sign here assigns a new string to the variable. The old value, Hello, is gone. You can confirm this yourself by adding >another alert command like this. "

And then the below is written and executed:

var message = "Hello!";  //message assigned
alert(message);              //message displayed
message = "Welcome to JavaScript Basics";   //message reassignment 
alert(message);             //reassigned message displayed   ("Hello" is gone)

Note: the "//" is a comment and will not display as a part of the code - I hope it helped a little.

You don't link to the video you talk about, but you must have misunderstood some part of it. The behavior you experience is normal and intended.

JavaScript (for the most part) executes files from start to bottom, so even though you change what the message variable holds on line 3 that does not change what the alert call produces since that is placed on line 2.

Similarly for your second example since JavaScript just goes though your code top to bottom line by line it will run both of the alert functions you place, and they will print out what the message variable contained at the time that alert was called.

If you provide a link to the video I might be able to clarify what he meant a bit better.