Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Introducing JavaScript The Console Challenge Answer

"Help me fix this program!"

How come the first alert "help me fix this program" didn't work until the second alert was fixed? I thought the script is read in order, from top to bottom?

2 Answers

Brandon Keene
Brandon Keene
7,217 Points

As I understand it, all the parameters passed to the functions are initialized before any of them are executed. So let's take a look at the code:

alert("Help me fix this program!");
alert("Can you get this message to appear?");
document.write("<h2>My first JavaScript program</h2>");
document.write("<p>I'm practicing 'debugging'.</p>");

Now remove any one of the " marks from inside the parantheses from any one line of the code, and none of it will execute. For example, stripping out the final " mark from the final line like so:

document.write("<p>I'm practicing 'debugging'.</p>);

will result in neither the alerts nor the document.writes running. However, if you make a mistake in the actual writing of the function, like missing a t in alert or a w in document.write, the code will execute until that line is encountered. For example, the following code will show both alerts and the first document.write:

alert("Help me fix this program!");
alert("Can you get this message to appear?");
document.write("<h2>My first JavaScript program</h2>");
document.rite("<p>I'm practicing 'debugging'."</p>");

Why is this? Like I said earlier, all the params are being initialized first, so as I understand it, all the params get checked for validity, and the system throws an error if any one of them is invalid. This error happens before any of the code is executed, and since running the code halts at an error, none of the code runs.

Conversely, if all the params are valid, it does run each line, in order, and only halts if there is an error in the exectution of a line.

That's my understanding, anyway. Hope this helps!

Your explanation makes perfect sense, but I'm just surprised to learn it works that way.

Brandon Keene
Brandon Keene
7,217 Points

You're not alone; it surprised me too!