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 trialSharath Chandra
3,957 PointsJavaScript code execution order
My question is regarding the JavaScript code execution order. In the below code, the 3 alert boxes seem to pop up first and then it is written to the document. However, the last two variables in the document.write are printed out as undefined though the input has been provided. I understand that I should first define the variables and then use them but I wanted to know how JavaScript code is executed. Is it executed sequentially? Is the JavaScript code first checked for any syntax errors and if the program has no errors, is that when the code finally runs?
var adjective = prompt("Type the adjective word?");
document.write("There once was a " + adjective + "programmer who wanted to use JavaScript to" + verb + "the" + noun);
var verb = prompt("Type the verb?");
var noun = prompt("Type the noun?");
1 Answer
Steven Parker
231,275 PointsHi, I was alerted by your tag.
You're right, JavaScript is executed sequentially. But before execution starts, a principle called hoisting is applied that causes function definitions and variable declarations to be handled first. Note that only the declaration of the variable is applied first, it still will not get a value until the assignment statement is executed.
Syntax errors are detected during execution and will cause the execution to stop. Lines before the error are executed.
Sharath Chandra
3,957 PointsSharath Chandra
3,957 PointsSteven Parker or others Could you please help?